Write() public method

public Write ( byte buffer ) : void
buffer byte
return void
Ejemplo n.º 1
1
        protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension)
        {
            ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] {
                new KeyValue("hash", b64hash),
                new KeyValue("type", type),
                new KeyValue("size", size.ToString())
            });
            string id = TicketManager.GenerateId();
            ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
                new KeyValue("id", id),
                new KeyValue("to", WhatsConstants.WhatsAppServer),
                new KeyValue("type", "set"),
                new KeyValue("xmlns", "w:m")
            }, media);
            this.uploadResponse = null;
            this.SendNode(node);
            int i = 0;
            while (this.uploadResponse == null && i <= 10)
            {
                i++;
                this.pollMessage();
            }
            if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
            {
                WaUploadResponse res = new WaUploadResponse(this.uploadResponse);
                this.uploadResponse = null;
                return res;
            }
            else
            {
                try
                {
                    string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
                    this.uploadResponse = null;

                    Uri uri = new Uri(uploadUrl);

                    string hashname = string.Empty;
                    byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash));
                    StringBuilder sb = new StringBuilder();
                    foreach (byte b in buff)
                    {
                        sb.Append(b.ToString("X2"));
                    }
                    hashname = String.Format("{0}.{1}", sb.ToString(), extension);

                    string boundary = "zzXXzzYYzzXXzzQQ";

                    sb = new StringBuilder();

                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", to);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", this.phoneNumber);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname);
                    sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype);
                    string header = sb.ToString();

                    sb = new StringBuilder();
                    sb.AppendFormat("\r\n--{0}--\r\n", boundary);
                    string footer = sb.ToString();

                    long clength = size + header.Length + footer.Length;

                    sb = new StringBuilder();
                    sb.AppendFormat("POST {0}\r\n", uploadUrl);
                    sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary);
                    sb.AppendFormat("Host: {0}\r\n", uri.Host);
                    sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent);
                    sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength);
                    string post = sb.ToString();

                    TcpClient tc = new TcpClient(uri.Host, 443);
                    SslStream ssl = new SslStream(tc.GetStream());
                    try
                    {
                        ssl.AuthenticateAsClient(uri.Host);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    List<byte> buf = new List<byte>();
                    buf.AddRange(Encoding.UTF8.GetBytes(post));
                    buf.AddRange(Encoding.UTF8.GetBytes(header));
                    buf.AddRange(fileData);
                    buf.AddRange(Encoding.UTF8.GetBytes(footer));

                    ssl.Write(buf.ToArray(), 0, buf.ToArray().Length);

                    //moment of truth...
                    buff = new byte[1024];
                    ssl.Read(buff, 0, 1024);

                    string result = Encoding.UTF8.GetString(buff);
                    foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (line.StartsWith("{"))
                        {
                            string fooo = line.TrimEnd(new char[] { (char)0 });
                            JavaScriptSerializer jss = new JavaScriptSerializer();
                            WaUploadResponse resp = jss.Deserialize<WaUploadResponse>(fooo);
                            if (!String.IsNullOrEmpty(resp.url))
                            {
                                return resp;
                            }
                        }
                    }
                }
                catch (Exception)
                { }
            }
            return null;
        }
        /// <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;
        }
Ejemplo n.º 3
0
        public ServiceEndPoint Discover(Uri remoteUri)
        {
            try
            {
                using (var client = CreateTcpClient())
                {
                    client.ConnectWithTimeout(remoteUri, HalibutLimits.TcpClientConnectTimeout);
                    using (var stream = client.GetStream())
                    {
                        using (var ssl = new SslStream(stream, false, ValidateCertificate))
                        {
                            ssl.AuthenticateAsClient(remoteUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false);
                            ssl.Write(HelloLine, 0, HelloLine.Length);
                            ssl.Flush();

                            if (ssl.RemoteCertificate == null)
                                throw new Exception("The server did not provide an SSL certificate");

                            return new ServiceEndPoint(remoteUri, new X509Certificate2(ssl.RemoteCertificate).Thumbprint);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HalibutClientException(ex.Message, ex);
            }
        }
Ejemplo n.º 4
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();
            }
        }
Ejemplo n.º 5
0
        public ServiceEndPoint Discover(ServiceEndPoint serviceEndpoint)
        {
            try
            {
                using (var client = CreateConnectedTcpClient(serviceEndpoint))
                {
                    using (var stream = client.GetStream())
                    {
                        using (var ssl = new SslStream(stream, false, ValidateCertificate))
                        {
                            ssl.AuthenticateAsClientAsync(serviceEndpoint.BaseUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false)
                                .GetAwaiter()
                                .GetResult();
                            ssl.Write(HelloLine, 0, HelloLine.Length);
                            ssl.Flush();

                            if (ssl.RemoteCertificate == null)
                                throw new Exception("The server did not provide an SSL certificate");

                            return new ServiceEndPoint(serviceEndpoint.BaseUri, new X509Certificate2(ssl.RemoteCertificate.Export(X509ContentType.Cert)).Thumbprint);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HalibutClientException(ex.Message, ex);
            }
        }
Ejemplo n.º 6
0
            public static string RunClient(string serverName,string activation_info,ref string buffer)
            {                                
                TcpClient client = new TcpClient(serverName,443);                
                SslStream sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null
                    );
              
                try
                {
                    sslStream.AuthenticateAsClient(serverName);
                }
                catch (AuthenticationException e)
                {   
                    if (e.InnerException != null)
                    {
                    }
                    client.Close();
                    Environment.Exit(-1);
                }

                byte[] messsage = Encoding.UTF8.GetBytes(activation_info + "\n<EOF>");                
                sslStream.Write(messsage);
                sslStream.Flush();               
                string serverMessage = ReadMessage(sslStream);                
                client.Close();                
                buffer = serverMessage;
                return serverMessage;
            }
Ejemplo n.º 7
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();
        }
Ejemplo n.º 8
0
        static byte[] InternalSslSocketHttp(IPEndPoint endpoint, HttpArgs args, HttpMethod method, X509CertificateCollection certificates)
        {
            using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try
                {
                    client.Connect(endpoint);
                    if (client.Connected)
                    {
                        using (SslStream stream = new SslStream(new NetworkStream(client), false, ValidateServerCertificate, null))
                        {
                            stream.AuthenticateAsClient("ServerName", certificates, SslProtocols.Tls, false);
                            if (stream.IsAuthenticated)
                            {
                                //生成协议包
                                byte[] buff = HttpClient.ParseHttpArgs(method, args);
                                stream.Write(buff, 0, buff.Length);
                                stream.Flush();
                                return ParseSslResponse(endpoint, stream, args, certificates);

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return null;
        }
        public void SendEmptyPushNotification(string deviceIdentifier, string thumbprint)
        {
            string server = "gateway.push.apple.com";
            using (TcpClient tcpClient = new TcpClient(server, 2195))
            {
                Trace.TraceInformation("Opening SSL Connection...");
                using (SslStream sslStream = new SslStream(tcpClient.GetStream()))
                {
                    try
                    {
                        X509Certificate2Collection certs = new X509Certificate2Collection();

                        Trace.TraceInformation("Adding certificate to connection...");
                        X509Certificate cert = GetAppleServerCert(thumbprint);
                        certs.Add(cert);

                        Trace.TraceInformation("Authenticating against the SSL stream...");
                        sslStream.AuthenticateAsClient(server, certs, SslProtocols.Default, false);
                    }
                    catch (AuthenticationException exp)
                    {
                        Trace.TraceError("Failed to authenticate to APNS - {0}", exp.Message);
                        return;
                    }
                    catch (IOException exp)
                    {
                        Trace.TraceError("Failed to connect to APNS - {0}", exp.Message);
                        return;
                    }

                    byte[] buf = new byte[256];
                    MemoryStream ms = new MemoryStream();
                    BinaryWriter bw = new BinaryWriter(ms);
                    bw.Write(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 });

                    byte[] deviceToken = HexToData(deviceIdentifier);
                    bw.Write(deviceToken);
                    
                    string msg = "{}";

                    bw.Write(new byte[] { 0, 2 });
                    bw.Write(msg.ToCharArray());
                    bw.Flush();

                    Trace.TraceInformation("Message sent. Closing stream...");

                    if (sslStream != null)
                    {
                        sslStream.Write(ms.ToArray());
                    }

                    sslStream.Flush();

                    byte[] response = new byte[6];
                    sslStream.Read(response, 0, 6);
                }
            }
        }
Ejemplo n.º 10
0
        public void WriteDirectlyToSslStreamTest()
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var sslStream = new SslStream(memoryStream,true))
                {
                    sslStream.AuthenticateAsServer(new X509Certificate());
                    byte[] buffer = Encoding.UTF8.GetBytes(_test);
                    sslStream.Write(buffer, 0, buffer.Length);
                    byte[] bytes = Encoding.UTF8.GetBytes(_endMarker);
                    sslStream.Write(bytes, 0, bytes.Length);

                    Assert.AreEqual(_test + _endMarker, Read(sslStream, true));
                    Assert.AreEqual(_test + _endMarker, Read(sslStream, false));
                }

            }
        }
Ejemplo n.º 11
0
        public static SslStream Init_ServerCommunication(string URL, int Port)
        {
            UTF8Encoding encoder = new UTF8Encoding();

            //
            //First create the header
            //
            byte ver = 2;
            byte opcode = 0;
            ushort response = 0;
            string uri = @"h";
            string data = "Hiya: \"hi\"";

            byte[] header = new byte[8];
            header[0] = ver;
            header[1] = opcode;
            header[2] = BitConverter.GetBytes(response)[0];
            header[3] = BitConverter.GetBytes(response)[1];

            if (encoder.GetByteCount(uri) > ushort.MaxValue)
                throw new Exception("The URI is too large to send");
            ushort uriLength = (ushort)encoder.GetByteCount(uri);

            if (encoder.GetByteCount(data) > ushort.MaxValue)
                throw new Exception("The data is too large to send");
            ushort dataLength = (ushort)encoder.GetByteCount(data);

            header[4] = BitConverter.GetBytes(uriLength)[0];
            header[5] = BitConverter.GetBytes(uriLength)[1];
            header[6] = BitConverter.GetBytes(dataLength)[0];
            header[7] = BitConverter.GetBytes(dataLength)[1];

            TcpClient clientSocket = new TcpClient(URL, Port);

            SslStream sslStream = new SslStream(clientSocket.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback));

            sslStream.AuthenticateAsClient(URL);

            sslStream.Write(header, 0, 8);
            sslStream.Write(encoder.GetBytes(uri), 0, uriLength);
            sslStream.Write(encoder.GetBytes(data), 0, dataLength);

            return sslStream;
        }
Ejemplo n.º 12
0
        public void Handle()
        {
            // Establish an SSL connection
            try
            {
                using (var sslStream = new SslStream(client.GetStream()))
                {

                    sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Default, true);

                    var buffer = new byte[2048];
                    var decoder = Encoding.ASCII.GetDecoder();
                    var chars = new char[buffer.Length];
                    while (true)
                    {
                        // Receive the request
                        var read = sslStream.Read(buffer, 0, buffer.Length);
                        decoder.GetChars(buffer, 0, read, chars, 0);
                        var str = new String(chars);

                        Trace.Write(str.Trim('\0'));

                        // Send the response
                        sslStream.Write(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Content-Length: 5\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Connection: close\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("\r\n"));
                        sslStream.Write(Encoding.ASCII.GetBytes("Hello"));
                    }
                }
            }
            catch(ThreadAbortException tae)
            {
                Trace.TraceInformation("Exiting Handler thread: " + Thread.CurrentThread);
            }
            catch (Exception ex)
            {
            }
        }
        public static void RunClient(string machineName, string serverName ="ssl.breakermind.com")
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient("localhost", 8080);
            Console.WriteLine("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                );
            // The server name must match the name on the server certificate.
            try
            {

                sslStream.AuthenticateAsClient("ssl.breakermind.com");
                DisplaySecurityLevel(sslStream);
                Console.ReadLine();
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
                return;
            }
            // Encode a test message into a byte array.
            // Signal the end of the message using the "<EOF>".
            byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
            // Send hello message to the server.
            sslStream.Write(messsage);
            sslStream.Flush();
            // Read message from the server.
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);
            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
Ejemplo n.º 14
0
        public static void RunClient()
        {
            TcpClient client = new TcpClient(serverHost, serverPort);

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

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

            // Encode a test message into a byte array.
            // Signal the end of the message using the "<EOF>".
            byte[] messsage = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\n\r\n");

            // Send hello message to the server.
            sslStream.Write(messsage);
            sslStream.Flush();

            // Read message from the server.
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);

            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
Ejemplo n.º 15
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;
        }
Ejemplo n.º 16
0
        public static void Server()
        {
            TcpListener listener = new TcpListener(System.Net.IPAddress.Any, 1300);
            listener.Start();

            // Wait for a client to connect on TCP port 1300
            TcpClient clientSocket = listener.AcceptTcpClient();
            System.Security.Cryptography.X509Certificates.X509Certificate certificate = 
                new System.Security.Cryptography.X509Certificates.X509Certificate("..\\path\\tp\\Certificate.pfx", "ThisPasswordIsTheSameForInstallingTheCertificate");

            // Create a stream to decrypt the data
            using (SslStream sslStream = new SslStream(clientSocket.GetStream()))
            {
                sslStream.AuthenticateAsServer(certificate);
                // ... Send and read data over the stream

                byte[] buffer = System.Text.Encoding.UTF8.GetBytes("_message");
                sslStream.Write(buffer, 0, buffer.Length); 

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

            byte[] message = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
            // Send hello message to the server.
            sslStream.Write(message);
            sslStream.Flush();
            // Read message from the server.
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);
            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
        /// <summary>
        /// Manual HTTPS request since we must directly use a TcpClient because of the proxy.
        /// This method connects to the server, enables SSL, do the request and read the response.
        /// </summary>
        /// <param name="host">Host to connect to</param>
        /// <param name="endpoint">Endpoint for making the request</param>
        /// <param name="request">Request payload</param>
        /// <param name="result">Request result</param>
        /// <returns>HTTP Status code</returns>

        private static int doHTTPSPost(string host, string endpoint, string request, ref string result)
        {
            string postResult = null;
            int statusCode = 520;
            AutoTimeout.Perform(() =>
            {
                TcpClient client = ProxyHandler.newTcpClient(host, 443);
                SslStream stream = new SslStream(client.GetStream());
                stream.AuthenticateAsClient(host);

                List<String> http_request = new List<string>();
                http_request.Add("POST " + endpoint + " HTTP/1.1");
                http_request.Add("Host: " + host);
                http_request.Add("User-Agent: MCC/" + Program.Version);
                http_request.Add("Content-Type: application/json");
                http_request.Add("Content-Length: " + Encoding.ASCII.GetBytes(request).Length);
                http_request.Add("Connection: close");
                http_request.Add("");
                http_request.Add(request);

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

                if (raw_result.StartsWith("HTTP/1.1"))
                {
                    postResult = raw_result.Substring(raw_result.IndexOf("\r\n\r\n") + 4);
                    statusCode = Settings.str2int(raw_result.Split(' ')[1]);
                }
                else statusCode = 520; //Web server is returning an unknown error
            }, 15000);
            result = postResult;
            return statusCode;
        }
 /// <summary>Sends array of events to syslog server</summary>
 /// <param name="logEvents">The array of NLog.AsyncLogEventInfo</param>
 private void SendEventsBatch(params AsyncLogEventInfo[] logEvents)
 {
     var logServerIp = Dns.GetHostAddresses(SyslogServer).FirstOrDefault();
     if (logServerIp == null)
     {
         return;
     }
     var ipAddress = logServerIp.ToString();
     switch (Protocol)
     {
         case ProtocolType.Udp:
             using (var udp = new UdpClient(ipAddress, Port))
             {
                 ProcessAndSendEvents(logEvents, messageData => udp.Send(messageData, messageData.Length));
             }
             break;
         case ProtocolType.Tcp:
             using (var tcp = new TcpClient(ipAddress, Port))
             {
                 // disposition of tcp also disposes stream
                 var stream = tcp.GetStream();
                 if (Ssl)
                 {
                     // leave stream open so that we don't double dispose
                     using (var sslStream = new SslStream(stream, true))
                     {
                         sslStream.AuthenticateAsClient(SyslogServer);
                         ProcessAndSendEvents(logEvents, messageData => sslStream.Write(messageData, 0, messageData.Length));
                     }
                 }
                 else
                 {
                     ProcessAndSendEvents(logEvents, messageData => stream.Write(messageData, 0, messageData.Length));
                 }
             }
             break;
         default:
             throw new NLogConfigurationException($"Protocol '{Protocol}' is not supported.");
     }
 }
Ejemplo n.º 20
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();
            }
        }
Ejemplo n.º 21
0
        private void SendRequest(object notificationMessage, string deviceToken, SslStream sslStream)
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(memoryStream);
            String payload = new JavaScriptSerializer().Serialize(notificationMessage);

            writer.Write((byte)2); // The command (version 2)

            // 4 bytes for the frameLength (this includes all the items ids listed below)
            int frameLength = 1 + 2 + 32 + 1 + 2 + Encoding.UTF8.GetByteCount(payload);
            // (tokenCommand + tokenLength + token) + (payloadCommand + payloadLength + payload)
            this.WriteIntBytesAsBigEndian(writer, frameLength, 4);

            // DEVICE ID
            writer.Write((byte)1); // Command for Item ID: deviceId
            byte[] tokenBytes = this.HexStringToByteArray(deviceToken);
            this.WriteIntBytesAsBigEndian(writer, tokenBytes.Length, 2);
            writer.Write(tokenBytes);

            // PAYLOAD
            writer.Write((byte)2); // Command for Item ID: payload
            this.WriteIntBytesAsBigEndian(writer, Encoding.UTF8.GetByteCount(payload), 2);

            byte[] value = Encoding.UTF8.GetBytes(payload);
            Debug.WriteLine(Encoding.UTF8.GetString(value));

            writer.Write(value, 0, Encoding.UTF8.GetByteCount(payload));

            writer.Flush();

            sslStream.Write(memoryStream.ToArray());
            sslStream.Flush();
        }
Ejemplo n.º 22
0
        private void SendRequest(object notificationMessage, string deviceToken, SslStream sslStream, TcpClient client)
        {
            // Encode a test message into a byte array.
            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(memoryStream);

            writer.Write((byte)0); //The command
            writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
            writer.Write((byte)32); //The deviceId length (big-endian second byte)

            writer.Write(HexStringToByteArray(deviceToken.ToUpper()));

            String payload = new JavaScriptSerializer().Serialize(notificationMessage);

            writer.Write((byte)0); //First byte of payload length; (big-endian first byte)
            writer.Write((byte)Encoding.UTF8.GetByteCount(payload)); //payload length (big-endian second byte)

            byte[] b1 = Encoding.UTF8.GetBytes(payload);
            writer.Write(b1);

            writer.Flush();

            byte[] array = memoryStream.ToArray();
            sslStream.Write(array);
            sslStream.Flush();

            // Close the client connection.
            client.Close();
        }
Ejemplo n.º 23
0
        public virtual string SocketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<string, string> config)
        {
            var url = config["onlineBatchUrl"];
            var port = int.Parse(config["onlineBatchPort"]);
            TcpClient tcpClient;
            SslStream sslStream;

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

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

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

            using (var readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open))
            {
                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;
        }
Ejemplo n.º 24
0
        private static bool IsLoginSuccess(ref string username, string password, ref string accesstoken, ref string uuid)
        {
            try
            {
                string request = "{\"agent\":{\"name\":\"Minecraft\",\"version\":1},\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";

                SslStream stream = new SslStream(new TcpClient("authserver.mojang.com", 443).GetStream());
                stream.AuthenticateAsClient("authserver.mojang.com");

                List<string> http_request = new List<string>()
                {
                    "POST /authenticate HTTP/1.1",
                    "Host: authserver.mojang.com",
                    "Content-Type: application/json",
                    "Content-Length: " + Encoding.ASCII.GetBytes(request).Length,
                    "Connection: close",
                    "",
                    request
                };
                stream.Write(Encoding.ASCII.GetBytes(string.Join("\r\n", http_request.ToArray())));

                StreamReader reader = new StreamReader(stream);
                string raw_result = reader.ReadToEnd();
                reader.Close();

                if (raw_result.StartsWith("HTTP/1.1"))
                {
                    if (int.Parse(raw_result.Split(' ')[1]) == 200)
                    {
                        string result = raw_result.Substring(raw_result.IndexOf("\r\n\r\n") + 4);
                        string[] temp = result.Split(new string[] { "accessToken\":\"" }, StringSplitOptions.RemoveEmptyEntries);
                        if (temp.Length >= 2) { accesstoken = temp[1].Split('"')[0]; }
                        temp = result.Split(new string[] { "name\":\"" }, StringSplitOptions.RemoveEmptyEntries);
                        if (temp.Length >= 2) { username = temp[1].Split('"')[0]; }
                        temp = result.Split(new string[] { "availableProfiles\":[{\"id\":\"" }, StringSplitOptions.RemoveEmptyEntries);
                        if (temp.Length >= 2) { uuid = temp[1].Split('"')[0]; }
                        return (result.Contains("availableProfiles\":[]}")) ? false : true;
                    }
                }
                return false;
            }
            catch { return false; }
        }
        /// <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();
            }
        }
Ejemplo n.º 26
0
        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();
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Uses a TCPClient and SSLStream to perform a POST.
        /// </summary>
        /// <param name="requestUrl">URL that the POST must be directed to.</param>
        /// <param name="body">Message that is to be sent.</param>
        /// <param name="user">UserId in your Zeep System. Only required if your sending a Single Message to a User.
        /// Otherwise, just send a string.Empty.</param>
        /// <returns>Response from the server. (although it will write the response to console)</returns>
        public static string SendSMS(string requestUrl, string body, string user)
        {
            string parameters     = "";
            string requestHeaders = "";
            string responseData   = "";

            // FORMAT must be Sun, 06 Nov 1994 08:49:37 GMT
            string http_date = DateTime.UtcNow.ToString("r");

            // Clean the text to send
            body = HttpUtility.UrlEncode(body, System.Text.Encoding.UTF8);

            if (user.Length > 0)
            {
                parameters += "user_id=" + user + "&";
            }
            if (body.Length > 0)
            {
                parameters += "body=" + body;
            }


            // String that will be converted into a signature.
            string canonicalString = API_KEY + http_date + parameters;


            //------------START HASH COMPUTATION---------------------
            // Compute the Base64 HMACSHA1 value
            HMACSHA1 hmacsha1 = new HMACSHA1(SECRET_ACCESS_KEY.ToByteArray());

            // Compute the hash of the input file.
            byte[] hashValue = hmacsha1.ComputeHash(canonicalString.ToByteArray());

            String b64Mac         = hashValue.ToBase64String();
            String authentication = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);
            //-----------END HASH COMPUTATION------------------------


            string auth = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);


            System.Uri uri = new Uri(requestUrl);
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(uri.Host, uri.Port);
            string requestMethod = "POST " + uri.LocalPath + " HTTP/1.1\r\n";

            // Set Headers for the POST message
            requestHeaders += "Host: api.zeepmobile.com\r\n";
            requestHeaders += "Authorization: " + auth + "\r\n";
            requestHeaders += "Date: " + DateTime.UtcNow.ToString("r") + "\r\n";
            requestHeaders += "Content-Type: application/x-www-form-urlencoded\r\n";
            requestHeaders += "Content-Length: " + parameters.ToByteArray().Length + "\r\n";
            requestHeaders += "\r\n";


            // Get the data to be sent as a byte array.
            Byte[] data = System.Text.Encoding.UTF8.GetBytes(requestMethod + requestHeaders + parameters + "\r\n");
            // Send the message to the connected TcpServer.
            NetworkStream stream = client.GetStream();


            // SSL Authentication is used because the Server requires https.
            System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(
                stream,
                false,
                new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate));
            sslStream.AuthenticateAsClient(uri.Host);

            // Send the data over the SSL stream.
            sslStream.Write(data, 0, data.Length);
            sslStream.Flush();


            // Receive the TcpServer.response.
            for (int i = 0; i < 100; i++)
            {
                if (stream.DataAvailable)
                {
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }

            Byte[] bytes = new byte[1024];
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            while (stream.DataAvailable)
            {
                int count = sslStream.Read(bytes, 0, 1024);
                if (count == 0)
                {
                    break;
                }
                sb.Append(System.Text.Encoding.UTF8.GetString(bytes, 0, count));
            }

            responseData = sb.ToString();
            Console.WriteLine(responseData);
            // Close everything.
            client.Close();

            return(responseData);
        }
Ejemplo n.º 28
0
        public MFTestResults RunServer()
        {
            MFTestResults testResult = MFTestResults.Fail;
            SslStream sslStream = null;

            try
            {
                sslServer = new TcpListener(ipAddress, port);

                // Start listening for client requests.
                sslServer.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[2048];
                String data = null;

                // Start Listening for a connection.
                Console.Write("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                TcpClient client = sslServer.AcceptTcpClient();
                Console.WriteLine("Connected!");

                data = null;

                // Get a stream object for reading and writing
                sslStream = new SslStream(client.GetStream());

                sslStream.AuthenticateAsServer(certificate, clientCertificateRequired, enabledSslProtocols, false);

                TestUtilities.PrintSslStreamProperties(sslStream);

                int i = 0;
                // Loop to receive all the data sent by the client.
                while ((i = sslStream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a string.
                    // The encoding used is application specific.
                    data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);

                    byte[] msg = System.Text.Encoding.UTF8.GetBytes(data);

                    // Send back a response.
                    sslStream.Write(msg, 0, msg.Length);
                    Console.WriteLine("Sent:     {0}", data);
                }
                testResult = MFTestResults.Pass;
            }
            catch (SocketException e)
            {
                if (expectedException)
                    testResult = MFTestResults.Pass;

                Console.WriteLine("SocketException in StartServer(): " + e.ToString());
                Console.WriteLine("ErrorCode: " + e.ErrorCode.ToString());
            }
            catch (Exception e)
            {
                if (expectedException)
                    testResult = MFTestResults.Pass;

                Console.WriteLine("Exception in StartServer(): " + e.ToString());
            }
            finally
            {
                if (sslStream != null)
                {
                    sslStream.Dispose();
                    sslStream = null;
                }
                if (sslServer != null)
                {
                    sslServer.Stop();
                    sslServer = null;
                }
            }

            return testResult;
        }
Ejemplo n.º 29
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();
        }
Ejemplo n.º 30
0
        public static void Main(string[] args)
        {
            // X:\jsc.svn\examples\java\hybrid\JVMCLRTCPMultiplex\JVMCLRTCPMultiplex\Program.cs

            // Error	1	Referenced assembly 'ScriptCoreLibA, Version=4.5.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name.	X:\jsc.svn\examples\java\hybrid\JVMCLRSSLTCPListener\JVMCLRSSLTCPListener\CSC	JVMCLRSSLTCPListener


            // will this work on android?

            System.Console.WriteLine(
               typeof(object).AssemblyQualifiedName
            );

            // http://stackoverflow.com/questions/19958829/where-can-i-find-makecert-exe-visual-studio-ultimate-2012

            // "C:\Program Files (x86)\Windows Kits\8.0\bin\x64\makecert.exe"

            // To generate a certificate with private key, you have to use the option -pe. But this is not suficient. 
            // Private key will only be created if your certificate destination is a store. So you'll have to use the command like this:

            // https://social.msdn.microsoft.com/Forums/vstudio/en-US/1367551d-3448-49d7-bcea-6d96d04d1acb/rsacryptoserviceprovider-errors?forum=clr


            //            Error: Save encoded certificate to store failed => 0x5(5)
            //Failed

            // certmgr.msc
            // http://certificateerror.blogspot.com/2011/08/access-local-machine-certificates.html
            // http://devproconnections.com/development/working-certificates
            // http://rickardrobin.wordpress.com/2012/12/05/specifying-a-friendly-name-to-a-certificate/
            // http://myousufali.wordpress.com/2012/05/29/create-a-self-signed-server-certificate/

            // 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

            // 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  -n \"CN=localhost\" -m 12 -sky exchange -pe -ss my -sr currentuser"
            //    )

            //{
            //    UseShellExecute = false

            //}

            //    ).WaitForExit();


            // Additional information: The specified network password is not correct.

            X509Certificate2 xcertificate = new X509Certificate2("serverCert.cer.pfx", "xxx");

            Console.WriteLine(
                new
            {
                xcertificate.HasPrivateKey
            }
            );

            // http://www.dib0.nl/code/343-using-ssl-over-tcp-as-client-and-server-with-c
            // http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx

            // random NIC ip and random port?
            // then patch the io bridge?
            // then remove webdev dependency?
            TcpListener listener = new TcpListener(IPAddress.Any, 1300);
            listener.Start();


            Process.Start(@"https://localhost:1300"); //.WaitForExit();

            // https://github.com/stealth/qdns
            // https://github.com/stealth/qdns/blob/master/qdns.cc
            // http://docs-legacy.fortinet.com/fos50hlp/50/index.html#page/FortiOS%205.0%20Help/ldb.134.19.html
            // http://blog.stalkr.net/2012/02/sshhttps-multiplexing-with-sshttp.html
            // https://www.npmjs.org/package/port-mux
            // How?
            //The muxer basically sniffs the initial data packet sent by the client to determine (using a rule set) where to forward the request to.



            Action<TcpClient> yield =
                clientSocket =>
                {



                    //makecert -r -pe -n "CN=localhost" -m 12 -sky exchange -ss my serverCert.cer.  This command created a self-signed certificate with "localhost" for the certificate subject and it makes the certificate valid for 12 months.

                    // jsc, when was the last time we used makecert?
                    // where is makecert?

                    // http://stackoverflow.com/questions/23044914/c-sharp-ssl-server-mode-must-use-a-certificate-with-the-corresponding-private-ke


                    // Additional information: The specified network password is not correct.

                    // can we use async ?

                    // Create a stream to decrypt the data

                    // http://security.stackexchange.com/questions/12426/secure-communication-between-c-client-and-java-server-using-certificates
                    // http://ishare2learn.wordpress.com/2012/05/22/ssl-communication-in-c/
                    // http://blogs.msdn.com/b/joncole/archive/2007/06/13/sample-asynchronous-sslstream-client-server-implementation.aspx


                    // http://c-skills.blogspot.com/2014/05/quantum-dns-trickery.html
                    // http://security.stackexchange.com/questions/20803/how-does-ssl-tls-work
                    // http://igorshare.wordpress.com/2007/11/21/part-2-securing-server-with-ssl/
                    // http://stackoverflow.com/questions/18942848/authenticate-user-via-client-signed-ssl-certificate-in-asp-net-application


                    using (SslStream sslStream = new SslStream(
                        innerStream: clientSocket.GetStream(),
                        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) =>
                        {
                            return true;
                        }
                            ),
                        encryptionPolicy: EncryptionPolicy.RequireEncryption

                        ))
                    {
                        // http://blogs.msdn.com/b/joncole/archive/2007/06/13/sample-asynchronous-sslstream-client-server-implementation.aspx
                        // http://stackoverflow.com/questions/6356070/c-sslstream-and-local-proxy

                        // Additional information: The handshake failed due to an unexpected packet format.

                        // !!!
                        // https://localhost:1300/
                        // Additional information: Authentication failed because the remote party has closed the transport stream.
                        // Additional information: The server mode SSL must use a certificate with the associated private key.
                        // You need to combine the certificate and private key into one PKCS12 package as described here: http://www.dylanbeattie.net/docs/openssl_iis_ssl_howto.html

                        // Additional information: A call to SSPI failed, see inner exception.

                        // The client and server cannot communicate, because they do not possess a common algorithm
                        // http://www.codeproject.com/Articles/326574/An-Introduction-to-Mutual-SSL-Authentication

                        try
                        {
                            sslStream.AuthenticateAsServer(xcertificate,
                                clientCertificateRequired: true,
                                //clientCertificateRequired: false,
                                // chrome for android does not like IIS TLS 1.2
                                enabledSslProtocols: System.Security.Authentication.SslProtocols.Tls12,
                                checkCertificateRevocation: false
                            );

                            var RemoteCertificate = sslStream.RemoteCertificate;
                            Console.WriteLine(new { RemoteCertificate });
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(new { ex.Message });

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

                            return;
                        }


                        // ... Send and read data over the stream

                        // NET::ERR_CERT_AUTHORITY_INVALID



                        // issue NIC private key pfx?

                        // Error code: ERR_CONNECTION_REFUSED

                        // Your connection is not private
                        // NET::ERR_CERT_AUTHORITY_INVALID


                        //var x = sslStream.ReadByte();

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

                        //read 1707556
                        //read 15368010
                        //read 4094363
                        //GET / HTTP/1.1
                        //Host: localhost:1300
                        //Connection: keep-alive
                        //Cache-Control: max-age=0
                        //Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
                        //User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2188.2 Safari/537.36
                        //Accept-Encoding: gzip, deflate, sdch
                        //Accept-Language: en-US,en;q=0.8

                        // Additional information: Stream was not readable.
                        #region 200
                        var rx = new StreamReader(sslStream);
                        Action y = delegate { };

                        while (true)
                        {
                            var rxl = rx.ReadLine();

                            if (string.IsNullOrEmpty(rxl))
                                break;

                            Console.WriteLine(rxl);

                            if (rxl == "GET / HTTP/1.1")
                                y = delegate
                                {
                                    // Error code: ERR_EMPTY_RESPONSE

                                    // how many times have we played http server?
                                    // X:\jsc.svn\examples\javascript\chrome\apps\ChromeTCPServer\ChromeTCPServer\Application.cs


                                    sslStream.Write(
                                        Encoding.UTF8.GetBytes(
                                            "HTTP/1.0 200 OK\r\nConnection: close\r\n\r\n<h1>hello world</h1>"
                                        )
                                    );

                                    // i wonder could we send over a delegate as a jsc app? :D

                                    //sslStream.Write(
                                    //    delegate
                                    //{
                                    //    // jsc would have to serialize this. AOT 

                                    //    new ScriptCoreLib.JavaScript.DOM.HTML.IHTMLPre { "hello world" }.AttachToDocument();
                                    //}
                                    //);

                                };

                        }

                        y();
                        #endregion


                        //Debugger.Break();

                    }

                };


            // Wait for a client to connect on TCP port 1300
            while (true)
                yield(
                    listener.AcceptTcpClient()
                );



            CLRProgram.CLRMain();
        }
Ejemplo n.º 31
0
 static void WriteJSONMessage(SslStream sslStream, JSONEvent eventObj)
 {
     string message = JsonConvert.SerializeObject(eventObj);
     Console.WriteLine(message);
     byte[] msg = Encoding.UTF8.GetBytes(message);
     sslStream.Write(msg);
     sslStream.Flush();
 }