Esempio n. 1
0
        private void processClient(TcpClient client)
        {
            X509Certificate certificate = new X509Certificate("..\\..\\..\\Certificate\\Certificate.pfx", "KTYy77216");
            // SslStream; leaveInnerStreamOpen = false;
            SslStream stream = new SslStream(client.GetStream(), false);
            try
            {
                // clientCertificateRequired = false
                // checkCertificateRevocation = true;
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
                Console.WriteLine("Waiting for client message ...");

                // Read a message from the client
                string input = readMessage(stream);
                Console.WriteLine("Received: {0}", input);

                // Write a message to the client
                byte[] message = Encoding.UTF8.GetBytes("Hello client, this is a message from the server :)<EOF>");
                Console.WriteLine("Sending message to client ...");
                stream.Write(message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                stream.Close();
                client.Close();
                return;
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
Esempio n. 2
0
        static void ListenerThreadEntry()
        {
            try
            {
                var listener = new TcpListener(IPAddress.Any, Port);
                listener.Start();

                using (var socket = listener.AcceptSocket())
                {
                    var serverCertificate = new X509Certificate2(CertsPath + @"\test.pfx");
                    var stream = new NetworkStream(socket);
                    using (var sslStream = new SslStream(stream, false))
                    {
                        sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);

                        // terminate the connection
                        sslStream.Close();
                        socket.Disconnect(false);
                        socket.Close();

                        // this code will fail
                        using (var reader = new StreamReader(sslStream))
                        {
                            var line = reader.ReadLine();
                            Console.WriteLine("> " + line);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }
Esempio n. 3
0
        private void runClient()
        {
            TcpClient client = new TcpClient(server, port);
            Console.WriteLine("Client connected ...");

            // Create ssl stream
            SslStream stream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), null);

            stream.AuthenticateAsClient(server);

            // write message to server
            byte[] output = Encoding.UTF8.GetBytes("Message from client :D<EOF>");
            stream.Write(output);
            stream.Flush();

            // read message from server
            string input = readMessage(stream);
            Console.WriteLine("Received: {0}", input);

            // close everything
            stream.Close();
            client.Close();
            Console.WriteLine("Client closed connection ...");
            // Press any key to continue ...
            Console.ReadKey();
        }
Esempio n. 4
0
        public void Close()
        {
            --RefCount;
            //Debug.Log("TcpClients: Destroy " + RefCount);
            try
            {
                if (_ssl != null)
                {
                    _ssl.Close();
                }

                if (_net != null)
                {
                    _net.Close();
                }

                if (_client != null)
                {
                    _client.Close();
                }

                if (_async != null)
                {
                    _async = null;
                }
            }
            catch
            {
            }
            _client = null;
            _ssl    = null;
            _stream = null;
            _async  = null;
            _net    = null;
        }
Esempio n. 5
0
        protected override Stream OnPrepareStream(NetworkStream stream)
        {
            var sslStream = new SslStream(stream, false);

            try
            {
                sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls, 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.");
                sslStream.Close();
                return null;
            }

            return sslStream;
        }
Esempio n. 6
0
        /// <summary>
        /// Close the connection and release all resources.
        /// </summary>
        private void CloseEx()
        {
            try
            {
                if (_socket != null)
                {
                    _socket.Shutdown(SocketShutdown.Both);
                }
            }
            catch { }

            try
            {
                if (_socket != null)
                {
                    _socket.Disconnect(false);
                }
            }
            catch { }

            try
            {
                if (_socket != null)
                {
                    _socket.Close();
                }

                if (_sslStream != null)
                {
                    _sslStream.Close();
                }

                if (_networkStream != null)
                {
                    _networkStream.Close();
                }
            }
            catch { }
        }
Esempio n. 7
0
        public static Stream CreateClientSslStream(ConnectionBase connection,
                                               Stream baseStream,
                                               X509Certificate2Collection clientCertificates,
                                               RemoteCertificateValidationCallback serverCertificateValidationCallback,
                                               LocalCertificateSelectionCallback clientCertificateSelectionCallback)
        {
            var sslStream = new SslStream(baseStream,
                                    false,
                                    serverCertificateValidationCallback,
                                    clientCertificateSelectionCallback);

              try {
            sslStream.AuthenticateAsClient(connection.host,
                                       clientCertificates,
                                       SslProtocols.Default,
                                       true);

            return sslStream;
              }
              catch (AuthenticationException) {
            sslStream.Close();

            throw;
              }
        }
Esempio n. 8
0
        private void PopBeforeSmtp(MailParameters mailParams)
        {
            Stream stream = null;

            System.Net.Sockets.TcpClient popclient = null;
            try
            {
                string rstr;
                popclient = new System.Net.Sockets.TcpClient();

                // POPサーバーに接続
                popclient.Connect(mailParams.PopServer, mailParams.PopPort);
                logs.AppendLine("POP: Connected.");

                X509CertificateCollection clientCertificateCollection = new X509CertificateCollection();
                if (mailParams.IsClientCertValidate)
                {
                    var clientCertificate = Cert.GetCert(mailParams.ClientCertSerialNo);
                    clientCertificateCollection.Add(clientCertificate);
                }

                // サーバーとデータの送受信を行うストリームを取得する
                // 通信開始(SSL有り)
                switch (mailParams.PopSecureMode)
                {
                case SecureMode.SSL2:                   // SSL2で運用しているサーバは存在しないはずだが、一応対応しておく
                    stream = new System.Net.Security.SslStream(popclient.GetStream(), false, ServerCertificateValidation);
                    ((System.Net.Security.SslStream)stream).AuthenticateAsClient(mailParams.SmtpServer, clientCertificateCollection, SslProtocols.Ssl2, false);
                    logs.AppendLine("POP: socket is over SSL2.");
                    break;

                case SecureMode.SSL3:                   // SSL3で運用しているサーバはあるかもしれない
                    stream = new System.Net.Security.SslStream(popclient.GetStream(), false, ServerCertificateValidation);
                    ((System.Net.Security.SslStream)stream).AuthenticateAsClient(mailParams.SmtpServer, clientCertificateCollection, SslProtocols.Ssl3, false);
                    logs.AppendLine("POP: socket is over SSL3.");
                    break;

                case SecureMode.TLS:                    // TLSは現状では主流
                case SecureMode.STARTTLS:
                    stream = new System.Net.Security.SslStream(popclient.GetStream(), false, ServerCertificateValidation);
                    ((System.Net.Security.SslStream)stream).AuthenticateAsClient(mailParams.SmtpServer, clientCertificateCollection, SslProtocols.Tls, false);

                    logs.AppendLine("POP: socket is over TLS.");
                    break;

                case SecureMode.None:
                    stream = popclient.GetStream();
                    logs.AppendLine("POP: socket unsecure.");
                    break;
                }
                stream.ReadTimeout  = 5000;
                stream.WriteTimeout = 500;

                //サーバーからのはじめのメッセージを受信

                // POPサーバー接続時のレスポンス受信
                string connectstr = PopWriteAndRead(stream, "");
                if (connectstr.StartsWith("+OK") != true)
                {
                    throw new PopException("POPサーバー接続エラー");
                }

                switch (mailParams.PopAuth)
                {
                case PopAuthMethod.Standard:
                    // ユーザIDの送信
                    rstr = PopWriteAndRead(stream, "USER " + mailParams.PopUserId + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("ユーザIDエラー");
                    }

                    // パスワードの送信
                    rstr = PopWriteAndRead(stream, "PASS " + mailParams.PopPasswd + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("パスワードエラー");
                    }
                    break;

                case PopAuthMethod.APOP:
                    // APOP用のタイムスタンプ文字列を取得しておく
                    var timestamp = GetAPopTimeStamp(connectstr);
                    if (string.IsNullOrWhiteSpace(timestamp))
                    {
                        throw new PopException("APOP未対応");
                    }
                    Byte[] byt = System.Text.Encoding.ASCII.GetBytes(string.Format("<{0}>{1}", mailParams.PopUserId, mailParams.PopPasswd));
                    System.Security.Cryptography.MD5CryptoServiceProvider md5 =
                        new System.Security.Cryptography.MD5CryptoServiceProvider();
                    Byte[] res = md5.ComputeHash(byt);
                    string aps = BitConverter.ToString(res).Replace("-", "").ToLower();
                    rstr = PopWriteAndRead(stream, "APOP " + mailParams.PopUserId + " " + aps + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("ユーザIDまたはパスワードエラー");
                    }
                    break;

                case PopAuthMethod.NTLM:
                    // ユーザIDの送信
                    rstr = PopWriteAndRead(stream, "USER " + mailParams.PopUserId + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("ユーザIDエラー");
                    }

                    // パスワードの送信
                    rstr = PopWriteAndRead(stream, "PASS " + mailParams.PopPasswd + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("パスワードエラー");
                    }
                    break;

                case PopAuthMethod.CramMd5:
                    rstr = PopWriteAndRead(stream, "AUTH CRAM-MD5\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("CRAM-MD5未対応");
                    }

                    rstr = PopWriteAndRead(stream, CreateCramMd5ResponseString(rstr.Substring(4), mailParams.PopUserId, mailParams.PopPasswd) + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("認証エラー");
                    }
                    break;
                }

                // ステータスの送信
                rstr = PopWriteAndRead(stream, "STAT" + "\r\n");
                if (rstr.StartsWith("+OK") != true)
                {
                    throw new PopException("STATエラー");
                }

                // 終了の送信
                rstr = PopWriteAndRead(stream, "QUIT" + "\r\n");
                // 戻り値は無視
            }
            catch (PopException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new PopException("内部例外発生", ex);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                if (popclient != null)
                {
                    popclient.Close();
                }
            }
        }
Esempio n. 9
0
        public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
        {
            var encoding = Encoding.ASCII;

            var certificate = settings.Certificate;

            var certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                (sender, cert, chain, sslErrs) => { return true; },
                (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return certificate; });

            stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);

            //Set up
            byte[] buffer = new byte[38];
            int recd = 0;
            DateTime minTimestamp = DateTime.Now.AddYears(-1);

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0 && !cancelToken.IsCancellationRequested)
            {
                try
                {

                    //Get our seconds since 1970 ?
                    byte[] bSeconds = new byte[4];
                    byte[] bDeviceToken = new byte[32];

                    Array.Copy(buffer, 0, bSeconds, 0, 4);

                    //Check endianness
                    if (BitConverter.IsLittleEndian)
                        Array.Reverse(bSeconds);

                    int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                    //Add seconds since 1970 to that date, in UTC
                    var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds);

                    //flag to allow feedback times in UTC or local, but default is local
                    if (!settings.FeedbackTimeIsUTC)
                        timestamp = timestamp.ToLocalTime();

                    //Now copy out the device token
                    Array.Copy(buffer, 6, bDeviceToken, 0, 32);

                    var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                    //Make sure we have a good feedback tuple
                    if (deviceToken.Length == 64
                        && timestamp > minTimestamp)
                    {
                        //Raise event
                        RaiseFeedbackReceived(deviceToken, timestamp);
                    }

                }
                catch { }

                //Clear our array to reuse it
                Array.Clear(buffer, 0, buffer.Length);

                //Read the next feedback
                recd = stream.Read(buffer, 0, buffer.Length);
            }

            try
            {
                stream.Close ();
                stream.Dispose();
            }
            catch { }

            try
            {
                client.Client.Shutdown (SocketShutdown.Both);
                client.Client.Dispose ();
            }
            catch { }

            try { client.Close (); } catch { }
        }
        /// <summary>
        /// Make a request to get a valid access Token from the refresh token
        /// </summary>
        /// <returns>a valid access token from the refresh code request</returns>
        public GoogleOAuth2AccessToken GetAuthTokenFromReqeustToken()
        {
            byte[] contentAsBytes = null;
            int contentLength = 0;

            //Submit using TCP Protocol
            contentAsBytes = Encoding.ASCII.GetBytes(ContentBody);
            contentLength = contentAsBytes.Length;

            string header = BuildHeader(true, contentLength);
            byte[] headerAsBytes = Encoding.ASCII.GetBytes(header);

            TcpClient client = new TcpClient(Host, 443);
            Stream netStream = client.GetStream();
            SslStream sslStream = new SslStream(netStream);
            sslStream.AuthenticateAsClient(Host);

            sslStream.Write(headerAsBytes);
            sslStream.Write(contentAsBytes);
            GoogleOAuth2AccessToken token = new GoogleOAuth2AccessToken();

            StreamReader reader = new StreamReader(sslStream);

            int left;
            var quote = Convert.ToString(Convert.ToChar(34));
            while (reader.Peek() > 0)
            {
                string line = reader.ReadLine();
                if (line == null) break;

                left = line.IndexOf(": ") + 1;

                if (left > 0)
                {
                    var result = line.Substring(left).Replace(quote, "").Replace(",", "").Replace(":", "").Trim();

                    if (line.ToLower().Contains("access_token"))
                    {
                        token.access_token = result;
                    }
                    else if (line.ToLower().Contains("expires_in"))
                    {
                        token.expires_in = result;
                    }
                    else if (line.ToLower().Contains("token_type"))
                    {
                        token.token_type = result;
                    }
                    else if (line.ToLower().Contains("id_token"))
                    {
                        token.id_token = result;
                    }
                }
            }
            sslStream.Close();
            return token;
        }
Esempio n. 11
0
        /// <summary>
        /// 处理http数据
        /// </summary>
        /// <param name="client"></param>
        private static void DoHttpProcessing(TcpClient client)
        {
            Stream clientStream = client.GetStream();
            Stream outStream = clientStream; //use this stream for writing out - may change if we use ssl
            SslStream sslStream = null;
            StreamReader clientStreamReader = new StreamReader(clientStream);

            if (Server.DumpHeaders || Server.DumpPostData || Server.DumpResponseData)
            {
                //确保按顺序打印数据
                Monitor.TryEnter(_outputLockObj, TimeSpan.FromMilliseconds(-1.0));
            }

            try
            {
                //读取第一行(http cmd)
                String httpCmd = clientStreamReader.ReadLine();
                if (String.IsNullOrEmpty(httpCmd))
                {
                    clientStreamReader.Close();
                    return;
                }
                //分割为3段
                String[] splitBuffer = httpCmd.Split(spaceSplit, 3);

                String method = splitBuffer[0];
                String remoteUri = splitBuffer[1];
                Version version = new Version(1, 0);

                HttpWebRequest webRequest;
                HttpWebResponse webResponse = null;

                /**
                 * http包发往代理服务器时,方法包括(get,post,connect)
                 * 当方法为connect时,表示ssl连接
                 */
                if (splitBuffer[0].ToUpper() == "CONNECT")
                {
                    //
                    remoteUri = "https://" + splitBuffer[1];
                    while (!String.IsNullOrEmpty(clientStreamReader.ReadLine())) { }
                    StreamWriter connectStreamWriter = new StreamWriter(clientStream);
                    connectStreamWriter.WriteLine("HTTP/1.0 200 Connection established");
                    connectStreamWriter.WriteLine("Timestamp: {0}", DateTime.Now.ToString());
                    connectStreamWriter.WriteLine("Proxy-agent: altman-agent");
                    connectStreamWriter.WriteLine();
                    connectStreamWriter.Flush();

                    sslStream = new SslStream(clientStream, false);
                    try
                    {
                        //进行身份验证
                        sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
                    }
                    catch (Exception)
                    {
                        sslStream.Close();
                        clientStreamReader.Close();
                        connectStreamWriter.Close();
                        clientStream.Close();
                        return;
                    }

                    //创建https,加密client的通信
                    clientStream = sslStream;
                    clientStreamReader = new StreamReader(sslStream);
                    outStream = sslStream;
                    //读取新的http cmd
                    httpCmd = clientStreamReader.ReadLine();
                    if (String.IsNullOrEmpty(httpCmd))
                    {
                        clientStreamReader.Close();
                        clientStream.Close();
                        sslStream.Close();
                        return;
                    }
                    splitBuffer = httpCmd.Split(spaceSplit, 3);
                    method = splitBuffer[0];
                    remoteUri = remoteUri + splitBuffer[1];
                }

                //重新组合客户端请求的第一行
                webRequest = (HttpWebRequest)HttpWebRequest.Create(remoteUri);
                webRequest.Method = method;
                webRequest.ProtocolVersion = version;

                //读取客户端请求的headers,并复制
                int contentLen = ReadRequestHeaders(clientStreamReader, webRequest);

                webRequest.Proxy = null;
                webRequest.KeepAlive = false;
                webRequest.AllowAutoRedirect = false;
                webRequest.AutomaticDecompression = DecompressionMethods.None;

                //打印headers
                if (Server.DumpHeaders)
                {
                    //Console.WriteLine("{0} {1} HTTP/{2}", webRequest.Method, webRequest.RequestUri.AbsoluteUri, webRequest.ProtocolVersion);
                    DumpHeaderCollectionToConsole(webRequest.Headers);
                }

                if (method.ToUpper() == "GET")
                {
                    //
                }
                else if (method.ToUpper() == "POST")
                {
                    char[] postBuffer = new char[contentLen];
                    int bytesRead;
                    int totalBytesRead = 0;
                    StreamWriter sw = new StreamWriter(webRequest.GetRequestStream());
                    while (totalBytesRead < contentLen &&
                           (bytesRead = clientStreamReader.ReadBlock(postBuffer, 0, contentLen)) > 0)
                    {
                        totalBytesRead += bytesRead;
                        sw.Write(postBuffer, 0, bytesRead);
                        if (Server.DumpPostData)
                        {
                            if (ProxyReceiveToDo != null)
                                ProxyReceiveToDo(null, new ProxyReceiveEventArgs(new string(postBuffer)));
                        }
                    }

                    sw.Close();
                }

                webRequest.Timeout = 15000;

                try
                {
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                }
                catch (WebException webEx)
                {
                    webResponse = webEx.Response as HttpWebResponse;
                }
                if (webResponse != null)
                {
                    List<Tuple<String, String>> responseHeaders = ProcessResponse(webResponse);
                    StreamWriter myResponseWriter = new StreamWriter(outStream);
                    Stream responseStream = webResponse.GetResponseStream();
                    try
                    {
                        //发送response状态码和headers
                        WriteResponseStatus(webResponse.StatusCode, webResponse.StatusDescription, myResponseWriter);
                        WriteResponseHeaders(myResponseWriter, responseHeaders);

                        Byte[] buffer;
                        if (webResponse.ContentLength > 0)
                            buffer = new Byte[webResponse.ContentLength];
                        else
                            buffer = new Byte[BUFFER_SIZE];

                        int bytesRead;

                        while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            outStream.Write(buffer, 0, bytesRead);
                            if (Server.DumpResponseData)
                            {
                                if (ProxyReceiveToDo != null)
                                    ProxyReceiveToDo(null, new ProxyReceiveEventArgs(Encoding.Default.GetString(buffer, 0, bytesRead)));
                            }
                        }

                        responseStream.Close();
                        outStream.Flush();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        responseStream.Close();
                        webResponse.Close();
                        myResponseWriter.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (Server.DumpHeaders || Server.DumpPostData || Server.DumpResponseData)
                {
                    //release the lock
                    Monitor.Exit(_outputLockObj);
                }

                clientStreamReader.Close();
                clientStream.Close();
                if (sslStream != null)
                    sslStream.Close();
                outStream.Close();
            }

        }
        private static void DoHttpProcessing(TcpClient client)
        {
            Stream clientStream = client.GetStream();
            Stream outStream = clientStream; //use this stream for writing out - may change if we use ssl
            SslStream sslStream = null;
            StreamReader clientStreamReader = new StreamReader(clientStream);
            CacheEntry cacheEntry = null;
            MemoryStream cacheStream = null;

            if (Server.DumpHeaders || Server.DumpPostData || Server.DumpResponseData)
            {
                //make sure that things print out in order - NOTE: this is bad for performance
                Monitor.TryEnter(_outputLockObj, TimeSpan.FromMilliseconds(-1.0));
            }

            try
            {
                //read the first line HTTP command
                String httpCmd = clientStreamReader.ReadLine();
                if (String.IsNullOrEmpty(httpCmd))
                {
                    clientStreamReader.Close();
                    clientStream.Close();
                    return;
                }
                //break up the line into three components
                String[] splitBuffer = httpCmd.Split(spaceSplit, 3);

                String method = splitBuffer[0];
                String remoteUri = splitBuffer[1];
                Version version = new Version(1, 0);

                HttpWebRequest webReq;
                HttpWebResponse response = null;
                if (splitBuffer[0].ToUpper() == "CONNECT")
                {
                    //Browser wants to create a secure tunnel
                    //instead = we are going to perform a man in the middle "attack"
                    //the user's browser should warn them of the certification errors however.
                    //Please note: THIS IS ONLY FOR TESTING PURPOSES - you are responsible for the use of this code
                    remoteUri = "https://" + splitBuffer[1];
                    while (!String.IsNullOrEmpty(clientStreamReader.ReadLine())) ;
                    StreamWriter connectStreamWriter = new StreamWriter(clientStream);
                    connectStreamWriter.WriteLine("HTTP/1.0 200 Connection established");
                    connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
                    connectStreamWriter.WriteLine("Proxy-agent: tb-proxy");
                    connectStreamWriter.WriteLine();
                    connectStreamWriter.Flush();

                    sslStream = new SslStream(clientStream, false);
                    try
                    {
                        sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
                    }
                    catch (Exception)
                    {
                        sslStream.Close();
                        clientStreamReader.Close();
                        connectStreamWriter.Close();
                        clientStream.Close();
                        return;
                    }

                    //HTTPS server created - we can now decrypt the client's traffic
                    clientStream = sslStream;
                    clientStreamReader = new StreamReader(sslStream);
                    outStream = sslStream;
                    //read the new http command.
                    httpCmd = clientStreamReader.ReadLine();
                    if (String.IsNullOrEmpty(httpCmd))
                    {
                        clientStreamReader.Close();
                        clientStream.Close();
                        sslStream.Close();
                        return;
                    }
                    splitBuffer = httpCmd.Split(spaceSplit, 3);
                    method = splitBuffer[0];
                    remoteUri = remoteUri + splitBuffer[1];
                }

                //construct the web request that we are going to issue on behalf of the client.
                webReq = (HttpWebRequest)HttpWebRequest.Create(remoteUri);
                webReq.Method = method;
                webReq.ProtocolVersion = version;

                //read the request headers from the client and copy them to our request
                int contentLen = ReadRequestHeaders(clientStreamReader, webReq);

                webReq.Proxy = null;
                webReq.KeepAlive = false;
                webReq.AllowAutoRedirect = true;
                webReq.ProtocolVersion = HttpVersion.Version10;
                webReq.AutomaticDecompression = DecompressionMethods.None;

                if(Server.DumpHeaders)
                {
                    Console.WriteLine(String.Format("{0} {1} HTTP/{2}",webReq.Method,webReq.RequestUri.AbsoluteUri, webReq.ProtocolVersion));
                    DumpHeaderCollectionToConsole(webReq.Headers);
                }

                //using the completed request, check our cache
                if (method.ToUpper() == "GET")
                    cacheEntry = ProxyCache.GetData(webReq);
                else if (method.ToUpper() == "POST")
                {
                    char[] postBuffer = new char[contentLen];
                    int bytesRead;
                    int totalBytesRead = 0;
                    StreamWriter sw = new StreamWriter(webReq.GetRequestStream());
                    while (totalBytesRead < contentLen && (bytesRead = clientStreamReader.ReadBlock(postBuffer, 0, contentLen)) > 0)
                    {
                        totalBytesRead += bytesRead;
                        sw.Write(postBuffer, 0, bytesRead);
                        if (ProxyServer.Server.DumpPostData)
                            Console.Write(postBuffer, 0, bytesRead);
                    }
                    if (Server.DumpPostData)
                    {
                        Console.WriteLine();
                        Console.WriteLine();
                    }

                    sw.Close();
                }

                if (cacheEntry == null)
                {
                    //Console.WriteLine(String.Format("ThreadID: {2} Requesting {0} on behalf of client {1}", webReq.RequestUri, client.Client.RemoteEndPoint.ToString(), Thread.CurrentThread.ManagedThreadId));
                    webReq.Timeout = 15000;

                    try
                    {
                        response = (HttpWebResponse)webReq.GetResponse();
                    }
                    catch (WebException webEx)
                    {
                        response = webEx.Response as HttpWebResponse;
                    }
                    if (response != null)
                    {

                        // If TB Streamtags are requested
                        bool isTB = false;
                        string contentStr = "";
                        if (webReq.RequestUri.OriginalString.Contains("ChannelID=884") && webReq.RequestUri.OriginalString.Contains("Channel=TechnoBase"))
                        {
                            isTB = true; // yep
                            Console.WriteLine("[" + DateTime.Now.ToString("HH:mm:ss") + "] TechnoBase StreamTags requested"); // report to user

                            Random rnd = new Random(DateTime.Now.Millisecond);
                            TBParser tbp = new TBParser();
                            List<Track> trackList = tbp.getTracks();

                            string currentTimeStr = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff");
                            StringBuilder sb = new StringBuilder(); // Build StreamTag Response
                            sb.Append("count=" + trackList.Count);
                            sb.Append("<br>");
                            sb.Append("vintern=1452");
                            sb.Append("<br>");
                            sb.Append("clistvintern=2160");
                            sb.Append("<br>");
                            sb.Append("time-ref=" + currentTimeStr);
                            sb.Append("<br>");
                            sb.Append("offset=01.01.1900 00:00:00");
                            sb.Append("<br>");
                            sb.Append("serverTime=" + currentTimeStr);
                            sb.Append("<br>");
                            sb.Append("FSListVIntern=100");
                            sb.Append("<br>");
                            sb.Append("ChargedListVIntern=103");
                            sb.Append("<br>");
                            sb.Append("rankingvintern=0");
                            sb.Append("<br>");
                            sb.Append("ResCode=0");
                            sb.Append("<br>");
                            sb.Append("ComTimeStamp=0");
                            sb.Append("<br>");
                            sb.Append("PeerFlag=0");
                            sb.Append("<br>");

                            foreach (Track trk in trackList)
                            {
                                if (trk.ID > 0)
                                {
                                    string songMD5 = GetMD5Hash(trk.ToString()); // Generate unique Track ID
                                    string songID9 = songMD5.Substring(0, 9);
                                    string songID6 = songMD5.Substring(0, 6);
                                    string songID4 = songMD5.Substring(0, 4);
                                    sb.Append("49127-12110 ");
                                    sb.Append(DateTime.Now.ToString("dd.MM.yyyy") + " "); // To be fixed (Incorrect date, might cause problems at 23:59 - 00:00)
                                    sb.Append(trk.TimeStart.ToString("HH:mm:ss.fff") + " "); // Time Start
                                    sb.Append(DateTime.Now.ToString("dd.MM.yyyy") + " "); // To be fixed (Incorrect date, might cause problems at 23:59 - 00:00)
                                    sb.Append(trk.TimeEnd.ToString("HH:mm:ss.fff") + " "); // Time End
                                    sb.Append("\"" + trk.Title + "\" "); // Title
                                    sb.Append("8 "); // 8 seems to work...
                                    sb.Append(songID9 + " "); // Song ID
                                    sb.Append("\"" + trk.Artist + "\" "); // Artist
                                    sb.Append("\"\" "); // Album
                                    sb.Append("\"\" "); // URL
                                    sb.Append("\"0\" "); // ?
                                    sb.Append("\"2000\" "); // Year
                                    sb.Append("\"\" "); // ?
                                    sb.Append("\"\" "); // ?
                                    sb.Append("\"\" "); // Shop URL
                                    sb.Append("5 "); // ?
                                    sb.Append(songID6 + " "); // Song ID
                                    sb.Append(songID4 + " "); // Song ID
                                    sb.Append("0 ");
                                    sb.Append("0 ");
                                    sb.Append("\"" + trk.CoverURL + "\" "); // Cover Image URL
                                    sb.Append(songID9 + " "); // Song ID
                                    sb.Append("<br>");

                                    // Example Response:
                                    // 49127-12110 01.11.2012 17:24:33.393 01.11.2012 17:29:34.307 "Everything" 5 331039793 "Safri Duo" "Episode II" "http://www.safriduo.dk/" "151" "2001" "" "http://www.amazon.de/Episode-II-Safri-Duo/dp/B00005KKA5/ref=sr_1_2?ie=UTF8&s=music&qid=1216825657&sr=8-2" "http://www.amazon.de/Episode-II-Safri-Duo/dp/B00005KKA5/ref=sr_1_2?ie=UTF8&s=music&qid=1216825657&sr=8-2" 4 1083354 5870,5 0 0 "http://ecx.images-amazon.com/images/I/41W4SZVXERL._SX240_.jpg" "112545908757223"
                                }
                            }

                            contentStr = sb.ToString();
                        }

                        List<Tuple<String, String>> responseHeaders = ProcessResponse(response, contentStr.Length);
                        StreamWriter myResponseWriter = new StreamWriter(outStream);
                        Stream responseStream = response.GetResponseStream();

                        try
                        {
                            //send the response status and response headers
                            WriteResponseStatus(response.StatusCode, response.StatusDescription, myResponseWriter);
                            WriteResponseHeaders(myResponseWriter, responseHeaders);

                            DateTime? expires = null;
                            CacheEntry entry = null;
                            Boolean canCache = (sslStream == null && ProxyCache.CanCache(response.Headers, ref expires));
                            if (canCache)
                            {
                                entry = ProxyCache.MakeEntry(webReq, response,responseHeaders, expires);
                                if (response.ContentLength > 0)
                                    cacheStream = new MemoryStream(entry.ResponseBytes);
                            }

                            Byte[] buffer;
                            if (isTB)
                            {
                                buffer = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8.GetBytes(contentStr));
                            }
                            else
                            {
                                if (response.ContentLength > 0)
                                    buffer = new Byte[response.ContentLength];
                                else
                                    buffer = new Byte[BUFFER_SIZE];
                            }

                            int bytesRead;

                            if (isTB)
                            {
                                //myResponseWriter.WriteLine(contentStr);
                                outStream.Write(buffer, 0, buffer.Length);
                            }
                            else{
                                while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    if (cacheStream != null)
                                        cacheStream.Write(buffer, 0, bytesRead);
                                    outStream.Write(buffer, 0, bytesRead);
                                    //Console.WriteLine(bytesRead);
                                    if (Server.DumpResponseData)
                                        Console.Write(UTF8Encoding.UTF8.GetString(buffer, 0, bytesRead));
                                }
                            }

                            if (Server.DumpResponseData)
                            {
                                Console.WriteLine();
                                Console.WriteLine();
                            }

                            responseStream.Close();
                            if (cacheStream != null)
                            {
                                cacheStream.Flush();
                                cacheStream.Close();
                            }

                            outStream.Flush();
                            if (canCache)
                                ProxyCache.AddData(entry);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        finally
                        {
                            responseStream.Close();
                            response.Close();
                            myResponseWriter.Close();
                        }
                    }
                }
                else
                {
                    //serve from cache
                    StreamWriter myResponseWriter = new StreamWriter(outStream);
                    try
                    {
                        WriteResponseStatus(cacheEntry.StatusCode, cacheEntry.StatusDescription, myResponseWriter);
                        WriteResponseHeaders(myResponseWriter, cacheEntry.Headers);
                        if (cacheEntry.ResponseBytes != null)
                        {
                            outStream.Write(cacheEntry.ResponseBytes, 0, cacheEntry.ResponseBytes.Length);
                            if (ProxyServer.Server.DumpResponseData)
                                Console.Write(UTF8Encoding.UTF8.GetString(cacheEntry.ResponseBytes));
                        }
                        myResponseWriter.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        myResponseWriter.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (Server.DumpHeaders || Server.DumpPostData || Server.DumpResponseData)
                {
                    //release the lock
                    Monitor.Exit(_outputLockObj);
                }

                clientStreamReader.Close();
                clientStream.Close();
                if (sslStream != null)
                    sslStream.Close();
                outStream.Close();
                if (cacheStream != null)
                    cacheStream.Close();
            }
        }
Esempio n. 13
0
        static void ProcessClient(TcpClient client)
        {
            // A client has connected. Create the
            // SslStream using the client's network stream.
            SslStream sslStream = new SslStream(
                client.GetStream(), false);
            // Authenticate the server but don't require the client to authenticate.
            try
            {
                sslStream.AuthenticateAsServer(serverCertificate,
                    false, SslProtocols.Tls, true);
                // Display the properties and settings for the authenticated stream.
                DisplaySecurityLevel(sslStream);
                DisplaySecurityServices(sslStream);
                DisplayCertificateInformation(sslStream);
                DisplayStreamProperties(sslStream);

                // Set timeouts for the read and write to 5 seconds.
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                // Read a message from the client.
                Console.WriteLine("Waiting for client message...");
                string messageData = ReadMessage(sslStream);
                Console.WriteLine("Received: {0}", messageData);

                // Write a message to the client.
                byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>");
                Console.WriteLine("Sending hello message.");
                sslStream.Write(message);
            }
            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.");
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                // The client stream will be closed with the sslStream
                // because we specified this behavior when creating
                // the sslStream.
                sslStream.Close();
                client.Close();
            }
        }
Esempio n. 14
0
        private void SendFile(UploadData credential, FileStream fstream)
        {
            TcpClient client = new TcpClient(credential.ip, credential.port);
            SslStream ssl = new SslStream(
                client.GetStream(), false,
                new RemoteCertificateValidationCallback(AuthenticationPrimitives.ValidateServerCertificate),
                null, EncryptionPolicy.RequireEncryption);

            ssl.AuthenticateAsClient(credential.ip, null, System.Security.Authentication.SslProtocols.Tls12, false);
            ssl.Write(UsefullMethods.GetBytesFromString(credential.token));
            fstream.CopyTo(ssl);
            ssl.Close();
            fstream.Close();
        }
Esempio n. 15
0
        private void connect()
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(HOST, PORT);

            log("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
               client.GetStream(),
               false,
               new RemoteCertificateValidationCallback(ValidateServerCertificate),
               null
               );
            try
            {
                // The server name must match the name on the server certificate.
                sslStream.AuthenticateAsClient(CN);
                log("Server authenticated");
                protocol(sslStream);
                log("protocol finished. Exit...");
            }
            catch (AuthenticationException e)
            {
                logF("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    logF("Inner exception: {0}", e.InnerException.Message);
                }
                logF("Authentication failed - closing the connection.");
                client.Close();
                return;
            }
            finally
            {
                sslStream.Close();
                client.Close();
            }
        }
Esempio n. 16
0
        public static void Main(string[] args)
        {
            // http://stackoverflow.com/questions/9726802/ssl-socket-between-net-and-java-with-client-authentication
            // http://stackoverflow.com/questions/27203741/java-equivalent-to-net-sslstream

            // X:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Extensions\TcpListenerExtensions.css
            // X:\jsc.svn\examples\javascript\Test\TestTCPMultiplex\TestTCPMultiplex\Application.cs

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201410/20141018-ssl
            // http://msdn.microsoft.com/en-us/library/ms733813.aspx
            // http://stackoverflow.com/questions/4095297/self-signed-certificates-performance-in-wcf-scenarios
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201510/20151009

            var CN = "device SSL authority for developers";


            #region CertificateRootFromCurrentUser
            Func<X509Certificate> CertificateRootFromCurrentUser =
                delegate
            {
                X509Store store = new X509Store(
                            StoreName.Root,
                    StoreLocation.CurrentUser);
                // https://syfuhs.net/2011/05/12/making-the-x509store-more-friendly/
                // http://ftp.icpdas.com/pub/beta_version/VHM/wince600/at91sam9g45m10ek_armv4i/cesysgen/sdk/inc/wintrust.h

                // Policy Information:
                //URL = http://127.0.0.5:10500

                try
                {

                    store.Open(OpenFlags.ReadOnly);

                    var item = store.Certificates.Find(X509FindType.FindBySubjectName, CN, true);

                    if (item.Count > 0)
                        return item[0];

                }
                finally
                {

                    store.Close();
                }

                return null;

            };
            #endregion

            // Error: There is no matching certificate in the issuer's Root cert store

            var r = CertificateRootFromCurrentUser();

            if (r == null)
            {
                Process.Start(
                                          new ProcessStartInfo(
                                          @"C:\Program Files (x86)\Windows Kits\8.0\bin\x64\makecert.exe",

                           // this cert is constant
                           "-r -cy authority -a SHA1 -n \"CN=" + CN + "\"  -len 2048 -m 72 -ss Root -sr currentuser"
                                          )

                {
                    UseShellExecute = false

                }

                ).WaitForExit();
            }

            // X:\jsc.svn\examples\java\hybrid\JVMCLRSSLTCPListener\JVMCLRSSLTCPListener\Program.cs
            // https://www.npmjs.org/package/port-mux
            // http://c-skills.blogspot.com/
            // http://httpd.apache.org/docs/trunk/ssl/ssl_faq.html


            //// match HTTP GET requests (using a prefix string match) and forward them to localhost:80
            //.addRule('GET ', 80)

            //// match TLS (HTTPS) requests (versions 3.{0,1,2,3}) using a regular expression
            //.addRule(/^\x16\x03[\x00 -\x03] /, '192.168.1.1:443') // regex match

            // f you wanted to be really clever, you could use a connection proxy thing to sniff the first couple of bytes of the incoming data stream, and hand off the connection based on the contents of byte 0: if it's 0x16 (the SSL/TLS 'handshake' byte), pass the connection to the SSL side, if it's an alphabetical character, do normal HTTP. My comment about port numbering applies.
            // http://serverfault.com/questions/47876/handling-http-and-https-requests-using-a-single-port-with-nginx
            // http://www.pond-weed.com/multiplex/


            //  http://stackoverflow.com/questions/463657/makecert-is-it-possible-to-change-the-key-size

            // The certificate has to be generated with "client authentication" option
            // http://stackoverflow.com/questions/18942848/authenticate-user-via-client-signed-ssl-certificate-in-asp-net-application
            // https://github.com/mono/mono/blob/master/mcs/tools/security/makecert.cs

            //X509CertificateBuilder
            // jsc can you build a cert anywhere?

            var port = new Random().Next(8000, 12000);

            // -l <link> Link to the policy information (such as a URL)


            // http://www.michael-thomas.com/tech/msiis/ssl_self_generating_certificates_for_iis_makecert.htm
            // -nscp Include netscape client auth extension
            // http://stackoverflow.com/questions/650017/what-does-subject-mean-in-certificate
            // http://technet.microsoft.com/en-us/library/aa998840.aspx

            // https://access.redhat.com/documentation/en-US/Red_Hat_Certificate_System/8.0/html/Admin_Guide/Managing_Subject_Names_and_Subject_Alternative_Names.html


            // http://blogs.technet.com/b/jhoward/archive/2005/02/02/365323.aspx
            // http://certificate.fyicenter.com/439_Windows__makecert.exe_-in_-eku__Certificate_for_Server_Aut.html

            // http://www.forumeasy.com/forums/archive/ldappro/201211/p135257621115.html


            //'-eku 1.3.6.1.5.5.7.3.1' specifies the new certificate is for "Server Authentication" purpose only.
            // http://stackoverflow.com/questions/12120630/how-do-i-identify-my-server-name-for-server-authentication-by-client-in-c-sharp
            // http://stackoverflow.com/questions/17477279/client-authentication-1-3-6-1-5-5-7-3-2-oid-in-server-certificates
            // http://security.stackexchange.com/questions/36932/what-is-the-difference-between-ssl-and-x-509-certificates
            // http://msdn.microsoft.com/en-us/library/windows/desktop/aa378132(v=vs.85).aspx


            //            Server Authentication (1.3.6.1.5.5.7.3.1)
            //Client Authentication (1.3.6.1.5.5.7.3.2)
            // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386968(v=vs.85).aspx
            // http://www.wilsonmar.com/1certs.htm
            // http://forums.iis.net/t/1180823.aspx

            // http://stackoverflow.com/questions/13806299/how-to-create-a-self-signed-certificate-using-c
            // https://clrsecurity.svn.codeplex.com/svn/Security.Cryptography/src/CngKeyExtensionMethods.cs




            //                ---------------------------
            //Security Warning
            //---------------------------
            //You are about to install a certificate from a certification authority (CA) claiming to represent:
            //127.0.0.101
            //Windows cannot validate that the certificate is actually from "127.0.0.101". You should confirm its origin by contacting "127.0.0.101". The following number will assist you in this process:
            //Thumbprint (sha1): 8B8942FB DEB64552 7BBDAD27 24B78664 A6D85D7E
            //Warning:
            //If you install this root certificate, Windows will automatically trust any certificate issued by this CA. Installing a certificate with an unconfirmed thumbprint is a security risk. If you click "Yes" you acknowledge this risk.
            //Do you want to install this certificate?
            //---------------------------
            //Yes   No   
            //---------------------------

            // http://msdn.microsoft.com/en-us/library/ms733813.aspx


            #region CertificateFromCurrentUserByLocalEndPoint
            Func<IPEndPoint, X509Certificate> CertificateFromCurrentUserByLocalEndPoint =
                LocalEndPoint =>
                {
                    var host = LocalEndPoint.Address.ToString();
                    var link = "http://" + host + ":" + LocalEndPoint.Port;


                    #region CertificateFromCurrentUser
                    Func<X509Certificate> CertificateFromCurrentUser =
                        delegate
                    {
                        X509Store store = new X509Store(
                            //StoreName.Root,
                            StoreName.My,
                            StoreLocation.CurrentUser);
                        // https://syfuhs.net/2011/05/12/making-the-x509store-more-friendly/
                        // http://ftp.icpdas.com/pub/beta_version/VHM/wince600/at91sam9g45m10ek_armv4i/cesysgen/sdk/inc/wintrust.h

                        // Policy Information:
                        //URL = http://127.0.0.5:10500

                        try
                        {

                            store.Open(OpenFlags.ReadOnly);
                            // Additional information: The OID value was invalid.
                            X509Certificate2Collection cers = store.Certificates;


                            foreach (var item in cers)
                            {
                                // http://comments.gmane.org/gmane.comp.emulators.wine.devel/86862
                                var SPC_SP_AGENCY_INFO_OBJID = "1.3.6.1.4.1.311.2.1.10";

                                // // spcSpAgencyInfo private extension

                                var elink = item.Extensions[SPC_SP_AGENCY_INFO_OBJID];
                                if (elink != null)
                                {
                                    var prefix = 6;
                                    var linkvalue = Encoding.UTF8.GetString(elink.RawData, prefix, elink.RawData.Length - prefix);

                                    Console.WriteLine(new { item.Subject, linkvalue });

                                    if (linkvalue == link)
                                        return item;
                                }
                            }
                        }
                        finally
                        {

                            store.Close();
                        }

                        return null;

                    };
                    #endregion

                    var n = CertificateFromCurrentUser();

                    if (n == null)
                    {
                        // http://stackoverflow.com/questions/13332569/how-to-create-certificate-authority-certificate-with-makecert
                        // http://www.jayway.com/2014/09/03/creating-self-signed-certificates-with-makecert-exe-for-development/
                        // http://stackoverflow.com/questions/4095297/self-signed-certificates-performance-in-wcf-scenarios

                        // logical store name
                        Process.Start(
                            new ProcessStartInfo(
                            @"C:\Program Files (x86)\Windows Kits\8.0\bin\x64\makecert.exe",
                //"-r  -n \"CN=localhost\" -m 12 -sky exchange -sv serverCert.pvk -pe -ss my serverCert.cer"
                //"-r  -n \"CN=localhost\" -m 12 -sky exchange -pe -ss my serverCert.cer -sr localMachine"
                //"-r  -n \"CN=localhost\" -m 12 -sky exchange -pe -ss my serverCert.cer -sr currentuser"
                //"-r  -a SHA1 -n \"CN=" + host + "\"  -len 2048 -m 1 -sky exchange -pe -ss my -sr currentuser -l " + link
                //"-r -cy authority -eku 1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2 -a SHA512 -n \"CN=" + host + "\"  -len 2048 -m 1 -sky exchange  -ss Root -sr currentuser -l " + link

                // chrome wont like SHA512
                // https://code.google.com/p/chromium/issues/detail?id=342230
                // http://serverfault.com/questions/407006/godaddy-ssl-certificate-shows-domain-name-instead-of-full-company-name
                // The certificate's O attribute in the subject (organization), along with the C attribute (country) determine what is displayed. If they are absent, it will simply display the primary subject domain name from the certificate.

                //"-r -cy authority -eku 1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2 -a SHA1 -n \"CN=" + host + ",O=JVMCLRTCPMultiplex\"  -len 2048 -m 1 -sky exchange  -ss Root -sr currentuser -l " + link
                //" -eku 1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2 -a SHA1 -n \"CN=" + host + "\"  -len 2048 -m 1 -sky exchange  -ss MY -sr currentuser -is Root -in \"" + CN + "\" -l " + link
                " -eku 1.3.6.1.5.5.7.3.1 -a SHA1 -n \"CN=" + host + "\"  -len 2048 -m 1 -sky exchange  -ss MY -sr currentuser -is Root -in \"" + CN + "\" -l " + link
                            )

                        {
                            UseShellExecute = false

                        }

                            ).WaitForExit();

                        n = CertificateFromCurrentUser();
                    }

                    return n;
                };
            #endregion




            //store.Open(OpenFlags.

            TcpListener listener = new TcpListener(IPAddress.Any, port);
            listener.Start();

            Process.Start(@"http://" + "127.0.0.101" + ":" + port); //.WaitForExit();
            //Process.Start(@"http://*****:*****@"X:\jsc.svn\examples\java\hybrid\JVMCLRSSLTCPListener\JVMCLRSSLTCPListener\bin\Debug\serverCert.cer.pfx", "xxx");


                        using (SslStream sslStream = new SslStream(
                            innerStream: p,
                            leaveInnerStreamOpen: false,

                            userCertificateSelectionCallback:
                                new LocalCertificateSelectionCallback(
                                    (object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) =>
                        {
                            return localCertificates[0];
                        }
                                ),
                            userCertificateValidationCallback:
                                new RemoteCertificateValidationCallback(
                                    (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                        {
                            Console.WriteLine(
                                new { certificate }
                                );

                            return true;
                        }
                                ),
                            encryptionPolicy: EncryptionPolicy.RequireEncryption

                            ))
                        {

                            try
                            {
                                // AuthenticateAsServer
                                // can this hang? if we use the wrong stream!

                                sslStream.AuthenticateAsServer(
                                    serverCertificate: CertificateFromCurrentUserByLocalEndPoint((IPEndPoint)clientSocket.Client.LocalEndPoint),
                                //clientCertificateRequired: false,
                                clientCertificateRequired: true,
                                // chrome for android does not like IIS TLS 1.2
                                enabledSslProtocols: System.Security.Authentication.SslProtocols.Tls12,
                                    checkCertificateRevocation: false
                                );

                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(new { ex.Message });

                                if (ex.InnerException != null)
                                    Console.WriteLine(new { ex.InnerException.Message });

                                return;
                            }

                            Console.WriteLine("read " + sslStream.GetHashCode());

                            x200(sslStream);
                            sslStream.Close();
                        }
                        Console.WriteLine("exit https");
                        return;
                    }


                    Console.WriteLine("exit other");
                    p.Close();

                };

            while (true)
                yield(
                    listener.AcceptTcpClient()
                );
            CLRProgram.CLRMain();

        }
        private void AcceptConnections(string threadName)
        {
            try
            {
                Thread.CurrentThread.Name = threadName;

                //m_sipConn.Listen(MAX_TCP_CONNECTIONS);
                m_tlsServerListener.Start(MAX_TLS_CONNECTIONS);

                logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " listening started.");

                while (!Closed)
                {
                    TcpClient tcpClient = m_tlsServerListener.AcceptTcpClient();
                    tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                    IPEndPoint remoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
                    logger.Debug("SIP TLS Channel connection accepted from " + remoteEndPoint + ".");

                    SslStream sslStream = new SslStream(tcpClient.GetStream(), false);

                    try
                    {
                        sslStream.AuthenticateAsServer(m_serverCertificate, false, SslProtocols.Tls, false);
                        // Display the properties and settings for the authenticated stream.
                        //DisplaySecurityLevel(sslStream);
                        //DisplaySecurityServices(sslStream);
                        //DisplayCertificateInformation(sslStream);
                        //DisplayStreamProperties(sslStream);

                        // Set timeouts for the read and write to 5 seconds.
                        sslStream.ReadTimeout = 5000;
                        sslStream.WriteTimeout = 5000;

                        SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
                        m_connectedSockets.Add(remoteEndPoint.ToString(), sipTLSConnection);

                        sipTLSConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
                        sipTLSConnection.SIPMessageReceived += SIPTLSMessageReceived;
                        //byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
                        sipTLSConnection.SIPStream.BeginRead(sipTLSConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), sipTLSConnection);
                    }
                    catch (Exception e)
                    {
                        logger.Error("SIPTLSChannel AuthenticationException. " + e.Message);
                        sslStream.Close();
                        tcpClient.Close();
                    }
                }

                logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " listening halted.");
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPTLSChannel Listen. " + excp.Message);
                //throw excp;
            }
        }
Esempio n. 18
0
        public virtual string socketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<String, String> config)
        {
            string url = config["onlineBatchUrl"];
            int port = Int32.Parse(config["onlineBatchPort"]);
            TcpClient tcpClient = null;
            SslStream sslStream = null;

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

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

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

            using (FileStream readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open))
            {
                int bytesRead = -1;
                byte[] byteBuffer;

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

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

            string batchName = Path.GetFileName(xmlRequestFilePath);
            string destinationDirectory = Path.GetDirectoryName(xmlResponseDestinationDirectory);
            if (!Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

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

            using (FileStream writeFileStream = new FileStream(xmlResponseDestinationDirectory + batchName, FileMode.Create))
            {
                char[] charBuffer;
                byte[] byteBuffer;
                int bytesRead = 0;

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

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

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

            return xmlResponseDestinationDirectory + batchName;
        }
Esempio n. 19
0
        public static byte[] Conversation(byte[] request)
        {
            MemoryStream response = new MemoryStream();

            using (TcpClient client = new TcpClient("pkgdsprod.nintendo.co.jp", 12401))
            {
                SslStream sslClient = new SslStream(client.GetStream(), false, delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; });
                sslClient.AuthenticateAsClient("pkgdsprod.nintendo.co.jp");

                sslClient.Write(request, 0, request.Length);
                sslClient.CopyTo(response);
                sslClient.Close();
            }
            response.Flush();
            byte[] dataResponse = response.ToArray();

            int length = BitConverter.ToInt32(dataResponse, 0);
            AssertHelper.Equals(length, dataResponse.Length);

            return dataResponse;
        }
Esempio n. 20
0
        /// <summary>
        /// Sets up a connection to APNS and initializes the thread for sending notifications
        /// </summary>
        void _Connect()
        {
            var configuration = ApnsServiceConfiguration.GetConfiguration ();
            _certificate = new X509Certificate2 (File.ReadAllBytes (configuration.Certificate), configuration.Password,
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            try {
                if (!_connection.IsNullOrDefault ())
                    _connection.Close ();

            #if DEBUG
                NSLogger.Log (NSLogLevel.Info, "Connecting to APNS...");
            #endif
                _connection = new TcpClient (apnsHostName, 2195);

                if (!_sslStream.IsNullOrDefault ())
                    _sslStream.Close ();

                _sslStream = new SslStream (_connection.GetStream (), false,
                        new RemoteCertificateValidationCallback ((sender, cert, chain, sslPolicyErrors) => { return true; }),
                        new LocalCertificateSelectionCallback ((sender, targetHost, localCerts, remoteCert, acceptableIssuers) => {
                            return _certificate;
                        }));

                var certificates = new X509CertificateCollection { _certificate };
                _sslStream.AuthenticateAsClient (apnsHostName, certificates, SslProtocols.Ssl3, false);

                if (!_sslStream.IsMutuallyAuthenticated)
                    throw new ApplicationException ("SSL Stream Failed to Authenticate", null);

                if (!_sslStream.CanWrite)
                    throw new ApplicationException ("SSL Stream is not Writable", null);

            #if DEBUG
                NSLogger.Log (NSLogLevel.Info, "Connected!");
            #endif

            } catch (Exception) {
                if (_connection.Connected) {
                    _connection.Close ();
                }

                if (!_sslStream.IsNullOrDefault ()) {
                    _sslStream.Close ();
                    _sslStream.Dispose ();
                }
                throw;
            }
        }
        static void ProcessClient(TcpClient client)
        {
            SslStream sslStream = new SslStream(
                client.GetStream(), false);
            try
            {
                sslStream.AuthenticateAsServer(serverCertificate,
                    false, SslProtocols.Tls, true);
                DisplaySecurityLevel(sslStream);
                DisplaySecurityServices(sslStream);
                DisplayCertificateInformation(sslStream);
                DisplayStreamProperties(sslStream);
                  sslStream.ReadTimeout = 5000;
                    sslStream.WriteTimeout = 5000;
                // Read a message from the client.
                byte[] message = Encoding.UTF8.GetBytes("2 process avaiable");
                sslStream.Write(message);
                bool statelock = false;
                while (true)
                {
                    string name = ReadMessage(sslStream);
                    switch (name)
                    {
                        case "unlock<EOF>":
                            System.Diagnostics.Process.Start(@"c:\logon.exe", "-u koicho -p koicho");
                            statelock = false;
                            message = Encoding.UTF8.GetBytes("success");
                            sslStream.Write(message);
                            break;
                        case "lock<EOF>":
                            System.Diagnostics.Process.Start(@"c:\windows\system32\rundll32.exe", "user32.dll,LockWorkStation");
                            statelock = true;
                            message = Encoding.UTF8.GetBytes("success");
                            sslStream.Write(message);
                            break;
                        case "getstate<EOF>":
                            if (statelock)
                            {
                                message = Encoding.UTF8.GetBytes("locked");
                                sslStream.Write(message);
                            }
                            else
                            {
                                message = Encoding.UTF8.GetBytes("unlocked");
                                sslStream.Write(message);
                            }

                            break;
                        case "ping<EOF>":
                                message = Encoding.UTF8.GetBytes("pinged");
                                sslStream.Write(message);
                                break;
                        default:
                            message = Encoding.UTF8.GetBytes("invalid command");
                            sslStream.Write(message);
                            break;
                    }
                }
            }
            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.");
                sslStream.Close();
                client.Close();
                return;
            }
              catch (SocketException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Socket failure.");
                sslStream.Close();
                client.Close();
                return;
            }
            catch (IOException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Connection failure.");
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                sslStream.Close();
                client.Close();
            }
        }
Esempio n. 22
0
        public void Inspect(int mSecTimout)
        {
            this.ProtocolUsed = SslProtocols.None;
            this.ConnectivityWorks = false;
            this.CertificateErrors = new List<SSLCertError>();
            this.SpeaksSSL = false;

            TcpClient client = null;
            try {

                client = TimeOutSocket.Connect(host, port, mSecTimout);
            } catch(Exception) {

                return;
            }
            this.ConnectivityWorks = client.Connected ;

            if (!this.ConnectivityWorks)
            {
                return;
            }

            RemoteCertificateValidationCallback callback = new RemoteCertificateValidationCallback(OnCertificateValidation);
            SslStream stream = new SslStream(client.GetStream(), false, callback);
            X509CertificateCollection dummy = new X509CertificateCollection();
            try{

                    stream.AuthenticateAsClient(host,dummy, SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls | SslProtocols.Ssl3, false); //blocks
                    System.Threading.Thread.Sleep(100); //wait for good measure
            }
            catch (System.Net.Sockets.SocketException)
            {
                this.ConnectivityWorks = false;
                return;
            }
            catch (Exception)
            {
                //connection open, but not valid SSL
                this.ConnectivityWorks = true;
                return;
            }

            SpeaksSSL = true;
            this.ProtocolUsed = stream.SslProtocol;
            stream.Close();

            lock(locker) {
                try
                {
                    //there are weird conditions where the OnVertificate validation event has not fired yet, so we could get the errors collection modified
                    //if we are not careful. Wrap it to be safe
                    foreach (SSLCertError e in this.working)
                    {
                        this.CertificateErrors.Add(e);
                    }
                }
                catch (Exception)
                {

                }
            }
        }
        /// <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();
            }
        }
Esempio n. 24
0
        public string DonwloadTimeSheetMail()
        {
            string sUserid, sPassword;

            GetMailUseridAndPassword(out sUserid, out sPassword);

            string sTempDir = GetTempDir();
            string sPrefix  = GetTempFileNamePrefix();
            string sLpath   = sTempDir + "\\" + sPrefix + "maillog.txt";
//			if (File.Exists(sLpath)) File.Delete(sLpath);
            string sDpath = sTempDir + "\\" + sPrefix + "mailtext.txt";
//			if (File.Exists(sDpath)) File.Delete(sDpath);
            string sEpath = sTempDir + "\\" + sPrefix + "timesheet";
            string sRes;

            StreamWriter strmlgw = new System.IO.StreamWriter(System.IO.File.Create(sLpath));
            TcpClient    tcpclnt = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
            SslStream    sslstrm = new System.Net.Security.SslStream(tcpclnt.GetStream());

            // There should be no gap between the imap command and the \r\n
            // sslstrm.read() -- while sslstrm.readbyte!= eof does not work
            // because there is no eof from server and  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 sslstrm.timeout sets the underlying tcp connections
            // timeout if the read or writetime out exceeds then the undelying
            // connectionis closed.

            strmlgw.WriteLine("### START ====================================", sslstrm);
            sslstrm.AuthenticateAsClient("imap.gmail.com");
            strmlgw.WriteLine("# Send blank =================================", sslstrm);
            SendImapCommand("", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'LOGIN' ===============================", sslstrm);
            SendImapCommand("$ LOGIN " + sUserid + " " + sPassword + "  \r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'SELECT INBOX' ========================", sslstrm);
            SendImapCommand("$ SELECT INBOX\r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

//			strmlgw.WriteLine("# Send 'TATUS INBOX (MESSAGES)' ==============", sslstrm);
//			SendImapCommand("$ STATUS INBOX (MESSAGES)\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);
//			int number = 1;
//			strmlgw.WriteLine("# Send 'FETCH " + number.ToString() + " BODYSTRUCTURE' =======", sslstrm);
//			SendImapCommand("$ FETCH " + number + " bodystructure\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);
//			strmlgw.WriteLine("# Send 'FETCH " + number.ToString() + " BODY[HEADER]' ========", sslstrm);
//			SendImapCommand("$ FETCH " + number + " body[header]\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'FETCH 1 body[text]' ==================", sslstrm);
            SendImapCommand("$ FETCH 1 body[text]\r\n", sslstrm);
            ReceiveMailBody(sDpath, tcpclnt, sslstrm);

            string sTempTimeSheetPath = ExtractAttachedFile(sDpath, sEpath);

            strmlgw.WriteLine("# Send 'LOGOUT' ==============================", sslstrm);
            SendImapCommand("$ LOGOUT\r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);
            strmlgw.WriteLine("### END ======================================", sslstrm);

            strmlgw.Close(); strmlgw.Dispose();
            sslstrm.Close(); sslstrm.Dispose();
            tcpclnt.Close();

            File.Delete(sLpath);
            File.Delete(sDpath);

            return(sTempTimeSheetPath);
        }
        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))
            {
                int bytesRead;

                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 (destinationDirectory != null && !Directory.Exists(destinationDirectory)) 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;
        }
Esempio n. 26
0
        public virtual bool SetupServerSocket()
#endif
        {
            try
            {
                //keep
                bool isSecured = false;
                string sslProtocol = "";

                //check packer
                if (SupportedChannelSerializationModes.HasFlag(ChannelSerializationMode.MessagePack))
                    DebugEx.Assert(MsgPack != null, "MessagePack serializer not provided");

                //create network stream
#if NETFX
                //Stream _netstream = new BufferedStream(new NetworkStream(base._sock, true));
                Stream _netstream = new NetworkStream(base._sock, true);

                //Wrap with a secure stream?
                if (Server.Certificate != null)
                {
                    var sslstream = new SslStream(_netstream, false);
                    try
                    {
                        //try authenticate
                        sslstream.AuthenticateAsServer(Server.Certificate, false, SslProtocols.Tls | SslProtocols.Tls12 | SslProtocols.Tls11, true);

                        //checks
                        if (!sslstream.IsAuthenticated)
                        {
                            DebugEx.Assert("Not authenticated");
                            throw new Exception("Not authenticated");
                        }
                        if (!sslstream.IsEncrypted)
                        {
                            DebugEx.Assert("No encryption");
                            throw new Exception("Not encryption");
                        }

                        //get info
                        isSecured = true;
                        sslProtocol = sslstream.SslProtocol.ToStringInvariant();

                        //use this stream from now on
                        _netstream = sslstream;
                    }
                    catch (Exception ex)
                    {
                        var msg = ex.Message;
                        if (ex.InnerException != null && ex.InnerException.Message != ex.Message)
                            msg += "  (inner msg=" + ex.InnerException.Message + ")";
                        DebugEx.TraceError("Certificate not accepted, " + msg);
                        try { Close("Certificate not accepted, " + msg); } catch { }
                        try { sslstream.Close(); base._sock.Dispose(); } catch { }
                        try { _netstream.Close(); _netstream.Dispose(); } catch { }
                        try { _sock.Close(); _sock.Dispose(); } catch { }
                        return false; //failed
                    }
                }
#endif

                //read clients packers
                var clientPackers = ChannelSerializationMode.Unkown;
                var clientPreferredPackers = ChannelSerializationMode.Unkown;
#if NETFX
                clientPackers = (ChannelSerializationMode)_netstream.ReadByte();
                clientPreferredPackers = (ChannelSerializationMode)_netstream.ReadByte();
#elif UNIVERSAL
                clientPackers = (ChannelSerializationMode)_sock.InputStream.AsStreamForRead().ReadByte();
                clientPreferredPackers = (ChannelSerializationMode)_sock.InputStream.AsStreamForRead().ReadByte();
#endif

                //filter packers
                clientPackers = clientPackers & SupportedChannelSerializationModes;
                clientPreferredPackers = clientPackers & clientPreferredPackers;
                var serverPreferredPackers = clientPackers & PreferredChannelSerializationModes;
                var commonPreferredPackers = clientPreferredPackers & serverPreferredPackers;

                //choose packer
                if ((_ChannelSerializationMode = _choosePacker(commonPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(clientPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(serverPreferredPackers)) == ChannelSerializationMode.Unkown &&
                    (_ChannelSerializationMode = _choosePacker(clientPackers)) == ChannelSerializationMode.Unkown)
                {
                    DebugEx.TraceError("Could not decide on packer.");
                    try { Close("Could not decide on packer."); } catch { }
#if NETFX
                    try { _netstream?.Close(); _netstream?.Dispose(); } catch { }
                    try { _sock?.Close(); _sock?.Dispose(); } catch { }
#elif UNIVERSAL
                    try { _sock?.Dispose(); } catch { }
#endif
                    return false; //failed
                }

                //write packer
#if NETFX
                var _nodelay = _sock.NoDelay;
                _sock.NoDelay = true; //Disable the Nagle Algorithm
                _netstream.WriteByte((byte)_ChannelSerializationMode);
                _sock.NoDelay = _nodelay; //Restore (default:enable) the Nagle Algorithm
#elif UNIVERSAL
                {
                    var wStream = _sock.OutputStream.AsStreamForWrite();
                    wStream.WriteByte((byte)_ChannelSerializationMode);
                    wStream.Flush();
                }
#endif

                //setup info
                try
                {
#if NETFX
                    this.LocalHost = base._sock.LocalEndPoint.GetIPAddress().ToString();
                    this.RemotePort = _sock.LocalEndPoint.GetPort().ToStringInvariant();
#elif UNIVERSAL
                    this.LocalHost = _sock.Information.LocalAddress.ToString();
                    this.RemotePort = _sock.Information.LocalPort;
#endif
                }
                catch { }

                //setup info
#if NETFX
                this.RemoteHost = base._sock.RemoteEndPoint.GetIPAddress().ToString();
                this.RemotePort = _sock.RemoteEndPoint.GetPort().ToStringInvariant();
#elif UNIVERSAL
                this.LocalHost = _sock.Information.RemoteAddress.ToString();
                this.RemotePort = _sock.Information.RemotePort;
#endif

                //log
                DebugEx.TraceLog("YPServer (socks) new connection from " + RemoteHost + ":" + RemotePort + " (Secure=" + isSecured + ",SSL=" + sslProtocol + ")");

                //setup stream
#if NETFX
                SetupStream(_netstream);
#elif UNIVERSAL
                SetupStream();
#endif

                //all ok
                return true;
            }
            catch (Exception ex)
            {
                DebugEx.TraceError(ex, "Unhandled exception caught");
                return false;
            }
        }
Esempio n. 27
0
        /////////////////////////////////////////////////////
        //                                                 //
        // ProcessClient()                                 //
        //                                                 //
        /////////////////////////////////////////////////////
        //Description:  Opens an SSL stream with the client,
        //              authenticating both the server to the
        //              client and vice-versa.  Processes
        //              commands sent in this stream.
        //
        //Returns:      false if told to quit the agent service
        //              or a failure occurs
        /////////////////////////////////////////////////////
        internal unsafe bool ProcessClient(TcpClient client)
        {
            IntPtr hMemStore = IntPtr.Zero;
            X509Store store = null;

            // A client has connected. Create the SslStream using the client's network stream.
            //note the TCP connection stream is automatically closed when this SSL stream object is disposed.
            try
            {
                CurrentSslStream = new SslStream(client.GetStream(), false, ValidateRemoteClientCertificate);
            }
            catch (Exception ex)
            {
                WriteConnectionLog("CONNECT:  Failed to create SSL stream:  " + ex.Message);
                return true;
            }

            // Authenticate the server to the client and vice-versa
            #region client/server authentication code
            try
            {
                WriteConnectionLog("CONNECT:  Authenticating client and server...");

                //------------------------------------------
                //          LOAD PFX CERT STORE
                //------------------------------------------
                //load the x509certificate2 from the PFX
                try
                {
                    //** get password via securestring **//
                    IntPtr pptr = IntPtr.Zero;
                    char[] str = EncryptedPassword.ToCharArray();
                    SecureString certPwd = null;

                    fixed (char* pChars = str)
                    {
                        certPwd = new SecureString(pChars, str.Length);
                    }

                    //decrypt our password in memory
                    pptr = Marshal.SecureStringToBSTR(certPwd);

                    //get x509 cert store from PFX file
                    hMemStore = CwCryptoHelper.GetX509StoreHandleFromPFX(PFXFileName, Marshal.PtrToStringBSTR(pptr));

                    //now use managed code to iterate over the store we just created from PFX
                    store = new X509Store(hMemStore);

                    //there should only be ONE certificate in this PFX store!
                    if (store.Certificates.Count != 1)
                    {
                        WriteConnectionLog("Error:  There are " + store.Certificates.Count.ToString() + " certificates in this store.  I don't know which one to extract, sorry.");

                        CwAgent.Win32Helper.CertCloseStore(hMemStore, 0);
                        //CwCryptoHelper.DestroyStore(store.Name,store.Prov
                        CurrentSslStream.Close();
                        return false;
                    }

                    //zero the password memory
                    Marshal.ZeroFreeBSTR(pptr);
                }
                catch (Exception ex)
                {
                    WriteConnectionLog("Could not extract certificate from PFX file:  " + ex.Message);
                    CurrentSslStream.Close();
                    return false;
                }

                //------------------------------------------
                //              AUTHENTICATE
                //------------------------------------------
                foreach(X509Certificate2 cert in store.Certificates)
                {
                    if (cert.HasPrivateKey)
                    {
                        CurrentSslStream.AuthenticateAsServer(cert, true, SslProtocols.Tls, false);
                        break;
                    }
                }
            }
            catch (AuthenticationException ex)
            {
                WriteConnectionLog("CONNECT:  Authentication error:  " + ex.Message);
                if (ex.InnerException != null)
                    WriteConnectionLog("CONNECT:  Additional error details:  " + ex.InnerException.Message);

                //cleanup
                if (store != null) store.Close();
                if (hMemStore != IntPtr.Zero) CwAgent.Win32Helper.CertCloseStore(hMemStore, 0);
                if (CurrentSslStream != null) CurrentSslStream.Close();
                //CwCryptoHelper.DestroyStore(store.Name,store.Prov

                return false;
            }
            catch (Exception ex)
            {
                WriteConnectionLog("CONNECT:  Caught exception:  " + ex.Message);

                //cleanup
                if (store != null) store.Close();
                if (hMemStore != IntPtr.Zero) CwAgent.Win32Helper.CertCloseStore(hMemStore, 0);
                if (CurrentSslStream != null) CurrentSslStream.Close();
                //CwCryptoHelper.DestroyStore(store.Name,store.Prov

                return false;
            }

            //require strong authentication?
            if (this.RequireStrongAuthentication)
            {
                if (!EnforceStrongAuthentication())
                {
                    WriteConnectionLog("Strong authentication failed.");
                    //cleanup
                    if (store != null) store.Close();
                    if (hMemStore != IntPtr.Zero) CwAgent.Win32Helper.CertCloseStore(hMemStore, 0);
                    if (CurrentSslStream != null) CurrentSslStream.Close();
                    //CwCryptoHelper.DestroyStore(store.Name,store.Prov
                    return false;
                }
            }
            //enforce required issuer
            if (this.RequiredIssuer != "")
            {
                bool fail = false;
                if (CurrentSslStream.RemoteCertificate == null)
                {
                    fail = true;
                    WriteConnectionLog("Null client certificate not allowed, closing connection...");
                }
                else if (CurrentSslStream.RemoteCertificate.Issuer != this.RequiredIssuer)
                {
                    fail = true;
                    WriteConnectionLog("Client certificate issuer is invalid, closing connection...");
                }

                if (fail)
                {
                    //cleanup
                    if (store != null) store.Close();
                    if (hMemStore != IntPtr.Zero) CwAgent.Win32Helper.CertCloseStore(hMemStore, 0);
                    if (CurrentSslStream != null) CurrentSslStream.Close();
                    //CwCryptoHelper.DestroyStore(store.Name,store.Prov
                    return false;
                }
            }
            #endregion

            WriteConnectionLog("CONNECT:  Connection OK, awaiting commands...");

            //wait for commands and process them serially
            bool success=ProcessCommands();
            WriteConnectionLog("CONNECT:  Session complete, connection closed.");

            try
            {
                CurrentSslStream.Close();
                client.Close();
            }
            catch (Exception) { }

            if (store != null) store.Close();
            if (hMemStore != IntPtr.Zero) CwAgent.Win32Helper.CertCloseStore(hMemStore, 0);

            return success;
        }
Esempio n. 28
0
        /// <summary>
        /// Perform SSL Handshake on a connected socket
        /// </summary>
        /// <param name="clientSocket">Socket object returned by Connect()</param>
        /// <returns>Stream which may be used for secure communication</returns>
        /// <remarks>Ceritifacte validation depends on RemoteCertificateValidationCallback() method</remarks>
        protected SslStream Handshake(Socket clientSocket)
        {
            NetworkStream clientSocketStream = null;
            SslStream clientSslStream = null;

            try
            {
                clientSocketStream = new NetworkStream(clientSocket); // this stream is going to be controlled by SslStream
                clientSslStream = new SslStream(clientSocketStream, false, this.RemoteCertificateValidationCallback);

                clientSslStream.AuthenticateAsClient(CertificateCommonName);

                // SslStream is necessary to read/write data
                return clientSslStream;
            }
            catch (Exception e)
            {
                if (clientSocketStream != null)
                {
                    clientSocketStream.Close();
                }
                if (clientSslStream != null)
                {
                    clientSslStream.Close();
                }
                clientSocket.Close();

                throw new Exception("Could not perform handshake process.", e);
            }
        }
 /// <summary>
 /// Accept callback method for SSL connection.
 /// </summary>
 /// <param name="ar">The socket server</param>
 private void AcceptSSLCallback(IAsyncResult ar)
 {
     AbstractSocketServer server = (AbstractSocketServer)ar.AsyncState;
     SslStream sslStream = null;
     try
     {
         // Get the socket that handles the client request.
         TcpClient sslTcpClient = server.sslListener.EndAcceptTcpClient(ar);
         Trace.WriteLine("Start incoming ssl connection ...");
         sslStream = new SslStream(sslTcpClient.GetStream(), false, new RemoteCertificateValidationCallback(server.OnVerifyClientCertificate));
         sslStream.AuthenticateAsServer(server.serverCertificate, true, SslProtocols.Ssl3, false);
         Socket handler = sslTcpClient.Client;
         handler.Blocking = true;
         AbstractTcpSocketClientHandler clientHandler = this.GetHandler(handler, sslStream);
         clientHandler.KeepAlive = this.KeepAlive;
         clientHandler.ReceiveMessageEvent += new ReceiveMessageDelegate(server.OnReceiveMessage);
         clientHandler.CloseConnectionEvent += new SocketConnectionDelegate(server.clientHandler_CloseConnectionEvent);
         server.OnConnection(clientHandler);
         server.clientList.AddClient(this.GetClientInfo(clientHandler));
         clientHandler.StartReceive();
         Trace.WriteLine("New connection completed");
     }
     catch (Exception ex)
     {
         Trace.WriteLine(string.Format("Failed to accept incoming connection. Exception", ex));
         try
         {
             if (sslStream != null)
             {
                 sslStream.Close();
                 sslStream.Dispose();
             }
         }
         catch (Exception ex2)
         {
             Trace.WriteLine(ex2);
         }
     }
     finally
     {
         // Signal the main thread to continue.
         server.listenerCompleteConnectionEvent.Set();
     }
 }
Esempio n. 30
0
        private static void DoHttpProcessing(TcpClient client)
        {
            Stream clientStream = client.GetStream();
            Stream outStream = clientStream; //use this stream for writing out - may change if we use ssl
            SslStream sslStream = null;
            StreamReader clientStreamReader = new StreamReader(clientStream);
            CacheEntry cacheEntry = null;
            MemoryStream cacheStream = null;

            if (Server.DumpHeaders || Server.DumpPostData || Server.DumpResponseData)
            {
                //make sure that things print out in order - NOTE: this is bad for performance
                Monitor.TryEnter(_outputLockObj, TimeSpan.FromMilliseconds(-1.0));
            }

            try
            {
                //read the first line HTTP command
                String httpCmd = clientStreamReader.ReadLine();
                if (String.IsNullOrEmpty(httpCmd))
                {
                    clientStreamReader.Close();
                    clientStream.Close();
                    return;
                }
                //break up the line into three components
                String[] splitBuffer = httpCmd.Split(spaceSplit, 3);

                String method = splitBuffer[0];
                String remoteUri = splitBuffer[1];
                Version version = new Version(1, 0);

                HttpWebRequest webReq;
                HttpWebResponse response = null;
                if (splitBuffer[0].ToUpper() == "CONNECT")
                {
                    //Browser wants to create a secure tunnel
                    //instead = we are going to perform a man in the middle "attack"
                    //the user's browser should warn them of the certification errors however.
                    //Please note: THIS IS ONLY FOR TESTING PURPOSES - you are responsible for the use of this code
                    remoteUri = "https://" + splitBuffer[1];
                    while (!String.IsNullOrEmpty(clientStreamReader.ReadLine())) ;
                    StreamWriter connectStreamWriter = new StreamWriter(clientStream);
                    connectStreamWriter.WriteLine("HTTP/1.0 200 Connection established");
                    connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
                    connectStreamWriter.WriteLine("Proxy-agent: matt-dot-net");
                    connectStreamWriter.WriteLine();
                    connectStreamWriter.Flush();

                    sslStream = new SslStream(clientStream, false);
                    try
                    {
                        sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
                    }
                    catch (Exception)
                    {
                        sslStream.Close();
                        clientStreamReader.Close();
                        connectStreamWriter.Close();
                        clientStream.Close();
                        return;
                    }

                    //HTTPS server created - we can now decrypt the client's traffic
                    clientStream = sslStream;
                    clientStreamReader = new StreamReader(sslStream);
                    outStream = sslStream;
                    //read the new http command.
                    httpCmd = clientStreamReader.ReadLine();
                    if (String.IsNullOrEmpty(httpCmd))
                    {
                        clientStreamReader.Close();
                        clientStream.Close();
                        sslStream.Close();
                        return;
                    }
                    splitBuffer = httpCmd.Split(spaceSplit, 3);
                    method = splitBuffer[0];
                    remoteUri = remoteUri + splitBuffer[1];
                }

                //construct the web request that we are going to issue on behalf of the client.
                webReq = (HttpWebRequest)HttpWebRequest.Create(remoteUri);
                webReq.Method = method;
                webReq.ProtocolVersion = version;

                //read the request headers from the client and copy them to our request
                int contentLen = ReadRequestHeaders(clientStreamReader, webReq);

                webReq.Proxy = null;
                webReq.KeepAlive = false;
                webReq.AllowAutoRedirect = false;
                webReq.AutomaticDecompression = DecompressionMethods.None;

                if(Server.DumpHeaders)
                {
                    Console.WriteLine(String.Format("{0} {1} HTTP/{2}",webReq.Method,webReq.RequestUri.AbsoluteUri, webReq.ProtocolVersion));
                    DumpHeaderCollectionToConsole(webReq.Headers);
                }

                //using the completed request, check our cache
                if (method.ToUpper() == "GET")
                    cacheEntry = ProxyCache.GetData(webReq);
                else if (method.ToUpper() == "POST")
                {
                    char[] postBuffer = new char[contentLen];
                    int bytesRead;
                    int totalBytesRead = 0;
                    StreamWriter sw = new StreamWriter(webReq.GetRequestStream());
                    while (totalBytesRead < contentLen && (bytesRead = clientStreamReader.ReadBlock(postBuffer, 0, contentLen)) > 0)
                    {
                        totalBytesRead += bytesRead;
                        sw.Write(postBuffer, 0, bytesRead);
                        if (ProxyServer.Server.DumpPostData)
                            Console.Write(postBuffer, 0, bytesRead);
                    }
                    if (Server.DumpPostData)
                    {
                        Console.WriteLine();
                        Console.WriteLine();
                    }

                    sw.Close();
                }

                if (cacheEntry == null)
                {
                    //Console.WriteLine(String.Format("ThreadID: {2} Requesting {0} on behalf of client {1}", webReq.RequestUri, client.Client.RemoteEndPoint.ToString(), Thread.CurrentThread.ManagedThreadId));
                    webReq.Timeout = 15000;

                    try
                    {
                        response = (HttpWebResponse)webReq.GetResponse();
                    }
                    catch (WebException webEx)
                    {
                        response = webEx.Response as HttpWebResponse;
                    }
                    if (response != null)
                    {
                        List<Tuple<String,String>> responseHeaders = ProcessResponse(response);
                        StreamWriter myResponseWriter = new StreamWriter(outStream);
                        myResponseWriter.AutoFlush = true;
                        Stream responseStream = response.GetResponseStream();
                        try
                        {
                            //send the response status and response headers
                            WriteResponseStatus(response.StatusCode,response.StatusDescription, myResponseWriter);
                            WriteResponseHeaders(myResponseWriter, responseHeaders);

                            DateTime? expires = null;
                            CacheEntry entry = null;
                            Boolean canCache = (sslStream == null && ProxyCache.CanCache(response.Headers, ref expires));
                            if (canCache)
                            {
                                entry = ProxyCache.MakeEntry(webReq, response,responseHeaders, expires);
                                if (response.ContentLength > 0)
                                    cacheStream = new MemoryStream(entry.ResponseBytes);
                            }

                            Byte[] buffer;
                            if (response.ContentLength > 0)
                                buffer = new Byte[response.ContentLength];
                            else
                                buffer = new Byte[BUFFER_SIZE];

                            int bytesRead;

                            while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                if (cacheStream != null)
                                    cacheStream.Write(buffer, 0, bytesRead);
                                outStream.Write(buffer, 0, bytesRead);
                                if (Server.DumpResponseData)
                                    Console.Write(UTF8Encoding.UTF8.GetString(buffer, 0, bytesRead));
                            }
                            if (Server.DumpResponseData)
                            {
                                Console.WriteLine();
                                Console.WriteLine();
                            }

                            responseStream.Close();
                            if (cacheStream != null)
                            {
                                cacheStream.Flush();
                                cacheStream.Close();
                            }

                            outStream.Flush();
                            if (canCache)
                                ProxyCache.AddData(entry);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        finally
                        {
                            responseStream.Close();
                            response.Close();
                            myResponseWriter.Close();
                        }
                    }
                }
                else
                {
                    //serve from cache
                    StreamWriter myResponseWriter = new StreamWriter(outStream);
                    try
                    {
                        WriteResponseStatus(cacheEntry.StatusCode, cacheEntry.StatusDescription, myResponseWriter);
                        WriteResponseHeaders(myResponseWriter, cacheEntry.Headers);
                        if (cacheEntry.ResponseBytes != null)
                        {
                            outStream.Write(cacheEntry.ResponseBytes, 0, cacheEntry.ResponseBytes.Length);
                            if (ProxyServer.Server.DumpResponseData)
                                Console.Write(UTF8Encoding.UTF8.GetString(cacheEntry.ResponseBytes));
                        }
                        myResponseWriter.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        myResponseWriter.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (Server.DumpHeaders || Server.DumpPostData || Server.DumpResponseData)
                {
                    //release the lock
                    Monitor.Exit(_outputLockObj);
                }

                clientStreamReader.Close();
                clientStream.Close();
                if (sslStream != null)
                    sslStream.Close();
                outStream.Close();
                if (cacheStream != null)
                    cacheStream.Close();
            }
        }
Esempio n. 31
0
        void ExchangeMessages(TcpClient client, SslStream stream)
        {
            if (stream.RemoteCertificate == null)
            {
                log.Write(EventType.ClientDenied, "A client at {0} connected, and attempted a message exchange, but did not present a client certificate", client.Client.RemoteEndPoint);
                stream.Close();
                client.Close();
                return;
            }

            var thumbprint = new X509Certificate2(stream.RemoteCertificate).Thumbprint;
            var verified = verifyClientThumbprint(thumbprint);
            if (!verified)
            {
                log.Write(EventType.ClientDenied, "A client at {0} connected, and attempted a message exchange, but it presented a client certificate with the thumbprint '{1}' which is not in the list of thumbprints that we trust", client.Client.RemoteEndPoint, thumbprint);
                stream.Close();
                client.Close();
                return;
            }

            log.Write(EventType.Security, "Client authenticated as {0}", thumbprint);
            var protocol = new MessageExchangeProtocol(stream, log);
            protocolHandler(protocol);
        }
Esempio n. 32
0
        internal void Run()
        {
            tcpClient = new TcpClient(config.Server, config.Port);
            stream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            stream.BeginAuthenticateAsClient(config.Server, new AsyncCallback(ProcessAuthenticate), this);

            // AsyncCallback(ProcessAuthenticate) will pick up work after SSL auth :)

            // now bring up the console for good .. everything else will happen async in the background
            while (keepRunning)
            {
                var command = Console.ReadLine();
                if (command == "quit")
                    break;
                if (command.StartsWith(".leadmerge"))
                {
                    new Command.CommandLeadMerge(this, command).Run();
                }
                else if (command.StartsWith(".leadcorrect"))
                {
                    new Command.CommandLeadCorrect(this, command).Run();
                }
                else
                {
                    send(command + "\r\n");
                }
            }

            try { stream.Close(); tcpClient.Close(); }
            catch { }
        }
        private void DoHttpProcessing(TcpClient client)
        {      
        	var threadId = Thread.CurrentThread.ManagedThreadId;
        	if (ProxyDisabled)
        	{
        		"[DoHttpProcessing]: ProxyDisabled is set, aborting request".error();
        		return;
        	}
        	
            Stream clientStream = client.GetStream();
            Stream outStream = clientStream; //use this stream for writing out - may change if we use ssl
            SslStream sslStream = null;
            StreamReader clientStreamReader = new StreamReader(clientStream);
            
            MemoryStream cacheStream = null;			
            
            try
            {
            	HttpWebRequest webReq = null;
                HttpWebResponse response = null;
                var rawRequestHeaders = new StringBuilder();
                var rawResponseHeaders = new StringBuilder();
                byte[] requestPostBytes = null;                                								                              
                var contentLen = 0;
                var skipRemaingSteps = false; 
                
                //read the first line HTTP command
                String httpCmd = clientStreamReader.ReadLine();
                if (String.IsNullOrEmpty(httpCmd))
                {
                    clientStreamReader.Close();
                    clientStream.Close();
                    return;
                }
                //break up the line into three components
                String[] splitBuffer = httpCmd.Split(spaceSplit, 3);

                String method = splitBuffer[0];
                String remoteUri = splitBuffer[1];
                Version version = new Version(1, 0);

                ExtraLogging.ifDebug("[{2}][DoHttpProcessing]: Got request for: {0} {1} [{2}]", method, remoteUri, threadId);
                
                Action handleSLL_CONNECT_withCaller = 
                	()=>{
                			if (skipRemaingSteps)
								return;
																						
			                if (splitBuffer[0].ToUpper() == "CONNECT")
			                {
			                	ExtraLogging.ifInfo("[{1}][DoHttpProcessing][handleSLL_CONNECT_withCaller] {0} [{1}]", remoteUri, threadId);
			                    //Browser wants to create a secure tunnel
			                    //instead = we are going to perform a man in the middle "attack"
			                    //the user's browser should warn them of the certification errors however.
			                    //Please note: THIS IS ONLY FOR TESTING PURPOSES - you are responsible for the use of this code
			                    remoteUri = "https://" + splitBuffer[1];
			                    
			                    ExtraLogging.ifInfo("[{1}][DoHttpProcessing][handleSLL_CONNECT_withCaller] updated remoteUri {0}, [{1}]", remoteUri, threadId);
			                    
			                    while (!String.IsNullOrEmpty(clientStreamReader.ReadLine())) ;
			                    
			                    ExtraLogging.ifInfo("[{0}][DoHttpProcessing][handleSLL_CONNECT_withCaller] after clientStreamReader.ReadLine [{0}]", threadId);
			                    
			                    StreamWriter connectStreamWriter = new StreamWriter(clientStream);
			                    connectStreamWriter.WriteLine("HTTP/1.0 200 Connection established");
			                    connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
			                    connectStreamWriter.WriteLine("Proxy-agent: O2 Platform Web Proxy");
			                    connectStreamWriter.WriteLine();
			                    			                    
			                    connectStreamWriter.Flush();
			        //            ExtraLogging.ifDebug("[{0}][DoHttpProcessing][handleSLL_CONNECT_withCaller] afterFlush [{0}]", threadId);
			                    //connectStreamWriter.Close();   //see if it has side effects with ssl sites
			                    //ExtraLogging.ifDebug("[DoHttpProcessing][handleSLL_CONNECT_withCaller] afterClose");
/*			                }
						};

				Action handleSLL_CONNECT_withRemote = 
                	()=>{
                	
                			if (skipRemaingSteps)
								return;							
*/							
//			                if (splitBuffer[0].ToUpper() == "CONNECT")
//			                {			                			
			                	//ExtraLogging.ifInfo("[DoHttpProcessing][handleSLL_CONNECT_withRemote] {0}", remoteUri);								
			                    
			                    try
			                    {
			                    	var keepStreamOpen = true;
			                    	var checkCertificateRevocation = true;
			                    	ExtraLogging.ifInfo("[{1}][DoHttpProcessing][handleSLL_CONNECT_withCaller] creating sslStream and AuthenticateAsServer {0} [{1}]", remoteUri, threadId);
			                    	//sslStream = new SslStream(clientStream, false);		//original
			                    	sslStream = new SslStream(clientStream, keepStreamOpen);
			                        //sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);   //original
			                        //sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, false);			                        
			                        sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, checkCertificateRevocation);			                        			                        
			                    }
			                    catch (Exception ex)
			                    {
			                    	skipRemaingSteps = true;			                        
			                    	"[{1}][Proxy Server][handleSLL_CONNECT] in sslStream.AuthenticateAsServer: {0} [{1}]".error(ex.Message, threadId);			                    		
			                    	if (ex.Message == "Authentication failed because the remote party has closed the transport stream.")
			                    		"[Proxy Server][handleSLL_CONNECT] NOTE: this error is usually callsed by the browser not accepting the temp certificate".info();
			                    	else
			                    		"[Proxy Server][handleSLL_CONNECT] NOTE: this error is usually caused by running with UAC, start the script in non UAC".info();  //.lineBefore().lineBeforeAndAfter()
			                        try
			                        {
			                        	sslStream.Close();
			                        	clientStreamReader.Close();
			                        	connectStreamWriter.Close(); // check for side effect
			                        	clientStream.Close();			                    	
			                        }
			                        catch(Exception ex2)
			                        {
			                        	"[{1}][Proxy Server][handleSLL_CONNECT] in CATCH of sslStream.AuthenticateAsServer: {0} [{1}]".error(ex2.Message, threadId);
			                        }
			                    }			                    
			                    if (skipRemaingSteps)
			                    	return;
			
			                    //HTTPS server created - we can now decrypt the client's traffic
			                    clientStream = sslStream;
			                    clientStreamReader = new StreamReader(sslStream);
			                    outStream = sslStream;
			                    //read the new http command.
			                    try
			                    {
			                    	httpCmd = clientStreamReader.ReadLine();
			                    }
			                    catch(Exception ex)
			                    {
			                    	"[{1}][Proxy Server] in clientStreamReader.ReadLine() {0} [{1}]".error(ex.Message, threadId);
			                    	httpCmd = null;
			                    }
			                    if (String.IsNullOrEmpty(httpCmd))
			                    {
			                        clientStreamReader.Close();
			                        clientStream.Close();
			                        sslStream.Close();
			                        return;
			                    }
			                    splitBuffer = httpCmd.Split(spaceSplit, 3);
			                    method = splitBuffer[0];
			                    remoteUri = remoteUri + splitBuffer[1];
			                }
		                };
				
				Action createWebRequest =
					()=>{	
							if (skipRemaingSteps)
								return;
							ExtraLogging.ifInfo("[{1}][DoHttpProcessing][createWebRequest] {0} [{1}]", remoteUri, threadId);
							//construct the web request that we are going to issue on behalf of the client.
							remoteUri = remoteUri.uri().str();	// fixes some issues where the uri is missing the initial protocol
			                webReq = (HttpWebRequest)HttpWebRequest.Create(remoteUri);
			                webReq.Method = method;
			                webReq.ProtocolVersion = version;
			
			                //read the request headers from the client and copy them to our request
			                contentLen = ReadRequestHeaders(clientStreamReader, webReq, rawRequestHeaders);
			                
			                webReq.Proxy = null;
			                webReq.KeepAlive = false;
			                webReq.AllowAutoRedirect = false;
			                webReq.AutomaticDecompression = DecompressionMethods.None;
						};
						                
				Action capturePostData = 
					()=>{
							if (skipRemaingSteps)
								return;							
			                if (method.ToUpper() == "POST")
			                {			        			                	
			                	ExtraLogging.ifInfo("[{1}][DoHttpProcessing][capturePostData] {0} [{1}]", remoteUri, threadId);
			                	var bytesToRead = contentLen;
			                	var maxReadBlock = 2048;		// try 100 to see better what is going on			                	
			                				                    
			                    int bytesRead;
			                    //int totalBytesRead = 0;			                    
			                    var readString = new StringBuilder();
			                    var postData = new StreamWriter(new MemoryStream());
			                    //DCz I had to change how the original was doing since ReadBlock would free on large posts
			                    //while (totalBytesRead < contentLen && (bytesRead = clientStreamReader.ReadBlock(postBuffer, 0, contentLen)) > 0)
			                    do 
			                    {
			                    	var readThisBytes = (bytesToRead > maxReadBlock) 
						                					? maxReadBlock
						                					: bytesToRead;
			                    	char[] postBuffer = new char[readThisBytes];			                    	
			                    	bytesRead = clientStreamReader.Read(postBuffer, 0, readThisBytes);
			                    	//Weirdly the conversion into string gives me a more accurate length than bytes read
			                    	var snipptet = Encoding.UTF8.GetBytes(postBuffer).ascii();
			                    	readString.Append(snipptet);			                    	
			                        //totalBytesRead += snipptet.size(); 			                        
			                        postData.Write(postBuffer, 0, bytesRead);			                        			                        
			                        bytesToRead -= snipptet.size(); //depending on the chars this will change
			                        
			                        /*"bytes read:{0} of {1} (from {2}  still left {3})  {4}  readString: {4}".info(
			                    				bytesRead, readThisBytes, contentLen ,bytesToRead, 
			                    				snipptet, readString.size());*/
			                    }        
			                    while(bytesToRead >0 || bytesRead==0);			                    			                    
			                    postData.Flush();			                    
			                    requestPostBytes = (postData.BaseStream as MemoryStream).ToArray();				                    
			                } 
						};
				
				
				Action writePostDataToRequestStream =
					()=>{
							if (skipRemaingSteps)
								return;							
							if (method.ToUpper() == "POST")
			                {
			                	ExtraLogging.ifInfo("[{1}][DoHttpProcessing][writePostDataToRequestStream] {0} [{1}]", remoteUri, threadId);
			                	 var requestPostChars = Encoding.UTF8.GetChars(requestPostBytes);
								StreamWriter sw = new StreamWriter(webReq.GetRequestStream());
								sw.Write(requestPostChars.ToArray(), 0, requestPostChars.Length);
								sw.Flush();
								sw.Close();
							}
						};

				
				Action getResponse = 
					()=>{
							if (skipRemaingSteps)
								return;
							ExtraLogging.ifInfo("[{1}][DoHttpProcessing][getResponse] {0} [{1}]", remoteUri, threadId);
							
							webReq.Timeout = 15000;
		                    try
		                    {
		                        response = (HttpWebResponse)webReq.GetResponse();
		                    }
		                    catch (WebException webEx)
		                    {
		                        response = webEx.Response as HttpWebResponse;
		                        "[{1}][DoHttpProcessing][getResponse] {0} [{1}]: {2}".error( remoteUri, threadId, webEx.Message);		                        
		                        //webEx.log();
		                    }		                    
						};
				
				 
				Action handleResponse_viaCache = 
					()=>{
							if (skipRemaingSteps)
								return;
							ExtraLogging.ifInfo("[{1}][DoHttpProcessing][handleResponse_viaCache] {0} [{1}]", remoteUri, threadId);
							if (proxyCache.enabled())
	                        {	
	                        	ExtraLogging.ifInfo("[{1}][DoHttpProcessing][handleResponse_viaCache] Replying using Cache: {0} [{1}]", remoteUri, threadId);
	                        	//Stream responseStream = response.GetResponseStream();
	                        	var cacheObject = proxyCache.getMapping(webReq, requestPostBytes);
		                        if (cacheObject.notNull())
		                        {		                        			                
		                        	StreamWriter myResponseWriter = new StreamWriter(outStream);
		                        	WriteResponseStatus(cacheObject.WebResponse.StatusCode,
		                        					    cacheObject.WebResponse.StatusDescription, 
		                        					    myResponseWriter);
		                        					    
		                            WriteResponseHeaders(myResponseWriter, cacheObject.Response_Headers);		                            
		                        	outStream.Write(cacheObject.Response_Bytes, 0, cacheObject.Response_Bytes.Length);		                        			                        	
			                        //responseStream.Close();
			                        outStream.Flush();
			                        
			                        //responseStream.Close();
			                        //response.Close();
			                        myResponseWriter.Close();		                            		                        
			                        skipRemaingSteps = true;
			                    }
		                   	}							
						};
						
				Action handleResponse_viaRealTarget =  
					()=>{	
							if (skipRemaingSteps)
								return;
								
							ExtraLogging.ifInfo("[{1}][DoHttpProcessing][handleResponse_viaRealTarget]: {0} [{1}]", remoteUri, threadId);
							if (response == null)		                				                	
		                		"[{1}][ProxyServer][DoHttpProcessing][handleResponse_viaRealTarget] Response was null {0} [{1}]".error(remoteUri, threadId);
		                	
		                	StreamWriter myResponseWriter;
		                	Stream responseStream;
		                	List<Tuple<String,String>> responseHeaders = null;
		                	var memoryStream = new MemoryStream();
							var binaryWriter = new  BinaryWriter(memoryStream);
		                	
		                	Action addResponseToCache =
		                		()=>{
				                		var responseString = response.isNull()
				                								? ""
				                								:	(response.ContentEncoding == "gzip")
				                            							? memoryStream.ToArray().gzip_Decompress().ascii()
				                            							: memoryStream.ToArray().ascii();                            							                            	
		                            	                            	
		                            	var requestResponseData = proxyCache.add(webReq, response, requestPostBytes,  memoryStream.ToArray(), responseString);
		                            	
		                            	requestResponseData.Request_Headers_Raw = rawRequestHeaders.str();                            	
		                            	requestResponseData.Response_Headers_Raw = rawResponseHeaders.str();                            	
		                            	requestResponseData.Response_Headers = responseHeaders;                            	                            	
		                            	
			                            if (OnResponseReceived.notNull()) 	                            
			                            	OnResponseReceived(requestResponseData);//webReq, response,memoryStream.ToArray().ascii());//UTF8Encoding.UTF8.GetString(memoryStream.ToArray(), 0, (int)memoryStream.Length));
				                	};
		                	
		                	try
		                	{
		                		if (response.isNull() || response.StatusCode.str() == "BadRequest")
		                		{
		                			ExtraLogging.ifInfo("[{0}][ProxyServer][handleResponse] skipping due to response being null or response.StatusCode == BadRequest ", threadId);
		                			"[{0}][ProxyServer][handleResponse] skipping due to response being null or response.StatusCode == BadRequest ".error(threadId);
		                			addResponseToCache();
							    	return; 
		                		}
	                        	myResponseWriter = new StreamWriter(outStream);
	                        	responseStream = response.GetResponseStream();	                        	                        	                        		                   	
								responseHeaders = ProcessResponse(response, rawResponseHeaders);								
							}
							catch(Exception ex)
							{
							    "[{2}][ProxyServer][handleResponse] before processing response body:  {0}  {1} [{2}]".error(ex.Message,  remoteUri, threadId);
							    addResponseToCache();
							    return; 
							}
							
	                        try
	                        {	                        	
	                            //send the response status and response headers
	                            WriteResponseStatus(response.StatusCode,response.StatusDescription, myResponseWriter);
	                            WriteResponseHeaders(myResponseWriter, responseHeaders);	                            								
								
	                            Byte[] buffer;
	                            if (response.ContentLength > 0)
	                                buffer = new Byte[response.ContentLength];
	                            else
	                                buffer = new Byte[BUFFER_SIZE];
	
	                            int bytesRead;
	                            
								
																
	                            while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)	                            
	                            	binaryWriter.Write(buffer, 0, bytesRead);
	                            	
	                            binaryWriter.Flush();
	                            
	                            if (memoryStream.Length >  Int32.MaxValue)
	                            	"[ProxyServer][handleResponse]: memoryStream.Length >  Int32.MaxValue".error();
	                            
	                            try
	                            {
	                            	outStream.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
	                            }
	                            catch(Exception ex)
	                            {
	                            	"[{2}][ProxyServer][handleResponse] in outStream.Write: {0}  {1}".error(ex.Message,  remoteUri, threadId);	                            
	                            }
	                            
	                            addResponseToCache();
	                            		
	                            responseStream.Close();	                            	                            
	                            outStream.Flush();
	                        }
	                        catch (Exception ex)
	                        {	                            
	                            "[{2}][ProxyServer][handleResponse]  while processing response body: {0}  {1} [{2}]".error(ex.logStackTrace().Message,  remoteUri, threadId);	                            
	                        }
	                        finally
	                        {
	                            responseStream.Close();
	                            response.Close();
	                            myResponseWriter.Close();
	                        }		                    
						};																
				
				
				handleSLL_CONNECT_withCaller();
				//handleSLL_CONNECT_withRemote();								
				// O2 callback				
                if (InterceptRemoteUrl.notNull())						                                	
                    remoteUri = InterceptRemoteUrl(remoteUri);				
												
				createWebRequest();	
				capturePostData();
				
				//put capturePostDatainterceptor callback here				
				handleResponse_viaCache();												
				
				if (HandleWebRequestProxyCommands.notNull() && HandleWebRequestProxyCommands(webReq,remoteUri) == false )			// O2 callback
					skipRemaingSteps = true;				     

//				handleSLL_CONNECT_withRemote();

                if (InterceptWebRequest.notNull())
                    InterceptWebRequest(webReq);                                 
				
				writePostDataToRequestStream();
		
				getResponse();
							
				handleResponse_viaRealTarget();		                
				
				if (skipRemaingSteps)
					ExtraLogging.ifError("[{1}][DoHttpProcessing] skipRemaingSteps was set for: {0} [{1}]", remoteUri, threadId);
					
				ExtraLogging.ifDebug("[{1}][DoHttpProcessing] ended for: {0} [{1}]", remoteUri, threadId);
				
                
            }
            catch (Exception ex)
            {                
                "[ProxyServer][DoHttpProcessing]: {0}".error(ex.logStackTrace().Message);
            }
            finally
            {
                /*if (Server.DumpHeaders || Server.DumpPostData || Server.DumpResponseData)
                {
                    //release the lock
                    Monitor.Exit(_outputLockObj);
                }*/

                clientStreamReader.Close();
                clientStream.Close();
                if (sslStream != null)
                    sslStream.Close();
                outStream.Close();
                if (cacheStream != null)
                    cacheStream.Close();
            }            
        }
Esempio n. 34
0
        private static Stream GetSslTunnelStream(Stream stream, string version = "HTTP/1.1")
        {
            SslStream sslStream = null;
            //Browser wants to create a secure tunnel
            //read and ignore headers
            while (!String.IsNullOrEmpty(stream.ReadLine())) ;
            //tell the client that a tunnel has been established              
            LogMessage(string.Format("Doing CONNECT"));
            var connectStreamWriter = new BinaryWriter(stream);
            connectStreamWriter.WriteLine(version + " 200 Connection established");
            connectStreamWriter.WriteLine(String.Format("Timestamp: {0}", DateTime.Now.ToString()));
            connectStreamWriter.WriteLine("Proxy-agent: buskerproxy");
            connectStreamWriter.WriteLine();
            connectStreamWriter.Flush();

            //open a decrypting stream    
            sslStream = new SslStream(stream, false);
            try
            {
                sslStream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
            }
            catch (Exception ex)
            {
                stream.Close();
                sslStream.Close();
                return null;
            }
            return sslStream;
        }