static void ProcessTcpClient(TcpClient client) { try { SslStream stream = new SslStream(client.GetStream()); X509Certificate cert = new X509Certificate2(Certificate.CreateSelfSignCertificatePfx( "CN=localhost", //host name DateTime.Parse("2000-01-01"), //not valid before DateTime.Parse("2099-01-01"), //not valid after "mypassword"), "mypassword"); //password to encrypt key file) stream.AuthenticateAsServer(cert); byte[] requestBuffer = new byte[8192]; int read = stream.Read(requestBuffer, 0, 8192); Array.Resize<byte>(ref requestBuffer, read); string request = Encoding.UTF8.GetString(requestBuffer); string requestedPath = request.Split('?')[0].Replace("GET ", ""); Console.WriteLine(client.GetHashCode() + " => " + requestedPath); string response = ""; if (requestedPath == "/gamepad/shardlist") { } else if (requestedPath == "/gamepad/lastshard") { } string header = "HTTP/1.1 200 OK\r\nDate: Fri, 10 Feb 2012 09:19:00 GMT\r\nServer: Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o\r\nContent-Length: " + response.Length + "\r\nContent-Type: text/html\r\n\r\n"; byte[] headerBytes = Encoding.UTF8.GetBytes(header); byte[] responseBytes = Encoding.UTF8.GetBytes(response); stream.Write(headerBytes); stream.Flush(); stream.Write(responseBytes); stream.Flush(); } catch (Exception e) { Console.WriteLine("Exception occured!\nMessage: " + e.Message + "\n" + e.StackTrace); } }
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); } }
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; }
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; }
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(); }
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); } }
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); } } }
static void Main (string [] args) { certfile = (args.Length > 1) ? args [0] : "ssl.cer"; keyfile = (args.Length > 1) ? args [1] : "ssl.pvk"; Socket listenSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint localEndPoint = new IPEndPoint (IPAddress.Any, 4433); Socket requestSocket; listenSocket.Bind (localEndPoint); listenSocket.Listen (10); while (true) { try { requestSocket = listenSocket.Accept (); using (NetworkStream ns = new NetworkStream (requestSocket, FileAccess.ReadWrite, true)) { using (SslStream s = new SslStream (ns, false, new RemoteCertificateValidationCallback (VerifyClientCertificate))) { s.AuthenticateAsServer (Certificate, false, SslProtocols.Default, false); StreamReader reader = new StreamReader (s); StreamWriter writer = new StreamWriter (s, Encoding.ASCII); string line; // Read request header do { line = reader.ReadLine (); if (line != null) Console.WriteLine (line); } while (line != null && line.Length > 0); string answer = String.Format ("HTTP/1.0 200{0}Connection: close{0}" + "Content-Type: text/html{0}Content-Encoding: {1}{0}{0}" + "<html><body><h1>Hello {2}!</h1></body></html>{0}", "\r\n", Encoding.ASCII.WebName, s.RemoteCertificate == null ? "World" : s.RemoteCertificate.GetName ()); // Send response writer.Write (answer); writer.Flush (); s.Flush (); ns.Flush (); } } } catch (Exception ex) { Console.WriteLine ("---------------------------------------------------------"); Console.WriteLine (ex.ToString ()); } } }
/// <summary> /// Send a packet.</summary> /// <param name="packet">The packet that will be send</param> /// <param name="ssl">The ssl stream</param> public static bool SendPacket(Packet packet, SslStream ssl) { BinaryFormatter binairyFormatter = new BinaryFormatter(); try { binairyFormatter.Serialize(ssl, packet); ssl.Flush(); } catch (Exception) { return false; } return true; }
/// <summary> /// Receive and read a packet.</summary> /// <param name="ssl">The ssl stream</param> public static Packet ReadPacket(SslStream ssl) { BinaryFormatter binairyFormatter = new BinaryFormatter(); Packet packet; try { packet = (Packet)binairyFormatter.Deserialize(ssl); ssl.Flush(); } catch (Exception) { return null; } return packet; }
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."); }
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."); }
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."); }
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(); }
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(); }
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; }
/// <summary> /// Performs performQuery() on Ews, asking how a doc processed. /// </summary> /// <param name="submittedFile">File to read parameters from</param> /// <param name="callerType">this.GetType() - since we're static, we need a way to load embedded resources</param> /// <returns>The XML as string as the webservice returns it</returns> public static string GetProcessingResult(XmlDocument submittedFile, Type callerType, string username, string password) { if (submittedFile == null) return null; // fill in query template Stream stream = callerType.Assembly.GetManifestResourceStream("XtbCnb2.performQueryTemplate.txt"); StreamReader sr = new StreamReader(stream); string query = sr.ReadToEnd(); sr.Close(); query = query.Replace("***USERNAME***", username); query = query.Replace("***PASSWORD***", password); XmlNode node = submittedFile.SelectSingleNode("/VYDANI/IDENTIFIKACE-VYKAZU/VYSKYT/STAV-KE-DNI"); // yyyymmdd -> dd.mm.yyyy string s = node.InnerText; query = query.Replace("***OBDOBIV***", s.Substring(6,2) + "." + s.Substring(4,2) + "." + s.Substring(0,4)); node = submittedFile.SelectSingleNode("/VYDANI/IDENTIFIKACE-VYKAZU/VYSKYT/SUBJEKT"); query = query.Replace("***SUBJEKTV***", node.InnerText); node = submittedFile.SelectSingleNode("/VYDANI/IDENTIFIKACE-VYKAZU/DATOVY-SOUBOR"); s = node.InnerText; int pos = s.IndexOf('.'); if (pos > 0) s = s.Substring(0, pos); query = query.Replace("***DATOVY-SOUBOR***", s); string t = query; t = t.Replace(password, "[[[CENSORED]]]"); string fnameForLog = "Q" + CnbData.ConstructCisloVydani().ToString() + ".xml"; Log.LogAsText("User " + username + " querying document status via document " + fnameForLog); Log.LogAsFile(t, fnameForLog); query = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(query), Base64FormattingOptions.InsertLineBreaks); // fill in SOAP template stream = callerType.Assembly.GetManifestResourceStream("XtbCnb2.QuerySOAPTemplate.txt"); sr = new StreamReader(stream); string soap = sr.ReadToEnd(); sr.Close(); soap = soap.Replace("***DATA-LENGTH***", (query.Length + 1).ToString()); // +1 for \n soap = soap.Replace("***DATA***", query); // fill in total length byte[] tData = System.Text.Encoding.UTF8.GetBytes(soap); byte lastByte = 0; for (pos = 0; pos < tData.Length; pos++) { if (lastByte == 10 && tData[pos] == 10) break; lastByte = tData[pos]; } int totalLength = tData.Length - pos - 1; soap = soap.Replace("***TOTAL-LENGTH***", totalLength.ToString()); // set up connection to webservice (we can't do this the comfy way as MS doesn't support SwA) ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; }; try { TcpClient client = new TcpClient(machineName, 443); client.SendTimeout = 2 * 60 * 1000; SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient(machineName, null, SslProtocols.Ssl2 | SslProtocols.Ssl3, false); byte[] messsage = System.Text.Encoding.UTF8.GetBytes(soap); // File.WriteAllBytes(@"C:\projekty\XtbCnb2\XtbCnb2\Tomas Drabek\soap.bin", messsage); // send request to ws sslStream.Write(messsage); sslStream.Flush(); // read ws response byte[] buffer = new byte[2048]; StringBuilder messageData = new StringBuilder(); int bytes = -1; do { bytes = sslStream.Read(buffer, 0, buffer.Length); if (bytes == 0) break; Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)]; decoder.GetChars(buffer, 0, bytes, chars, 0); messageData.Append(chars); } while (bytes != 0); client.Close(); // get the response part we care about string rawMessage = messageData.ToString(); rawMessage = rawMessage.Replace("\r\n", "\n"); string resfname = "S" + CnbData.ConstructCisloVydani().ToString() + ".txt"; Log.LogAsText("Response recorded as file " + resfname); Log.LogAsFile(rawMessage, resfname); // check HTTP result code Regex checkHeader = new Regex("HTTP/1.. 200.*"); if (!checkHeader.IsMatch(rawMessage)) throw new Exception("Webservice returned the following raw error:\n" + rawMessage); Regex regex = new Regex(".*?Content-Type: .*? boundary.?=.?\"(.*?)\".*"); Match match = regex.Match(rawMessage); string boundary = match.Groups[1].Value; pos = rawMessage.IndexOf(boundary); pos = rawMessage.IndexOf(boundary, pos + boundary.Length); pos = rawMessage.IndexOf(boundary, pos + boundary.Length); pos += boundary.Length; int partStart = pos; partStart = rawMessage.IndexOf("\n\n", partStart) + 2; int partEnd = rawMessage.IndexOf(boundary, pos) - 2; // mime prepends 2 minuses, we don't want them string b64Message = rawMessage.Substring(partStart, partEnd - partStart); // decode the part byte[] decoded = null; try { decoded = Convert.FromBase64String(b64Message); return System.Text.Encoding.UTF8.GetString(decoded); } catch (Exception) { return b64Message; } } catch (Exception e) { string msg = string.Format("Exception type: {0}, exception info: {1}", e.ToString(), e.Message); if (e.InnerException != null) msg += string.Format("\n\nInner exception type: {0}, exception info: {1}", e.InnerException.ToString(), e.InnerException.Message); MessageBox.Show(msg, "Exception Encountered"); return null; } }
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(); }
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; }
public static string HTTPFetch(string url, string method, WebHeaderCollection headers, byte[] streamBytes, int contentLength, out string[] responseFields, string contentType = "application/x-www-form-urlencoded", string requestAccept = null, string host = null) { _active = true; try { var uri = new Uri(url); if (EndpointCallback != null) EndpointCallback(uri.AbsolutePath); if (string.IsNullOrEmpty(host)) host = uri.Host; string reqStr = String.Format("{0} {1} HTTP/1.1\r\n", method, url) + String.Format("Host: {0}\r\n", host) + String.Format("Connection: Close\r\n"); if (!IsNullOrWhiteSpace(requestAccept)) reqStr += String.Format("Accept: {0}\r\n", requestAccept); if (contentType != null) reqStr += String.Format("Content-Type: {0}\r\n", contentType); if (headers != null) { for (int i = 0; i < headers.Count; ++i) { string header = headers.GetKey(i); foreach (string value in headers.GetValues(i)) { reqStr += String.Format("{0}: {1}\r\n", header, value); } } } reqStr += String.Format("Content-Length: {0}\r\n", contentLength); reqStr += "\r\n"; byte[] headerBytes = ToByteArray(reqStr); byte[] finalBytes = headerBytes; if (contentLength > 0) { var requestBytes = new byte[headerBytes.Length + contentLength]; Buffer.BlockCopy(headerBytes, 0, requestBytes, 0, headerBytes.Length); Buffer.BlockCopy(streamBytes, 0, requestBytes, headerBytes.Length, contentLength); finalBytes = requestBytes; } string responseFromServer = ""; responseFields = new string[] { }; var tcpClient = new TcpClient(); string responseStr = ""; int responseLength = 0; if (url.ToLower().StartsWith("https")) { //HTTPS tcpClient.Connect(uri.Host, 443); ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => true); //This has a bug on mono: Message "The authentication or decryption has failed." //Therefore unfortunately we have to ignore certificates. using (var s = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => true))) { s.AuthenticateAsClient(uri.Host, null, SslProtocols.Tls, false); if (UpstreamCallback != null && UpstreamCallbackRate > 0) { int i = 0; while (i < finalBytes.Length) { if (!_active) throw new Exception("Halt"); if (i + _upstreamCallbackRate > finalBytes.Length) { s.Write(finalBytes, i, finalBytes.Length - i); UpstreamCallback(contentLength, contentLength); break; } s.Write(finalBytes, i, (int)_upstreamCallbackRate); i += (int)_upstreamCallbackRate; UpstreamCallback(Math.Min(i, contentLength), contentLength); } } else s.Write(finalBytes, 0, finalBytes.Length); s.Flush(); while (true) { var responseBytes = new byte[8192]; int i = s.Read(responseBytes, 0, responseBytes.Length); if (i == 0) break; responseStr += Encoding.UTF8.GetString(responseBytes, 0, i); responseLength += i; } } } else { //HTTP tcpClient.Connect(uri.Host, 80); if (UpstreamCallback != null && UpstreamCallbackRate > 0) { var s = tcpClient.GetStream(); int i = 0; while (i < finalBytes.Length) { if (!_active) throw new Exception("Halt"); if (i + _upstreamCallbackRate > finalBytes.Length) { s.Write(finalBytes, i, finalBytes.Length - i); UpstreamCallback(contentLength, contentLength); break; } s.Write(finalBytes, i, (int)_upstreamCallbackRate); i += (int)_upstreamCallbackRate; UpstreamCallback(Math.Min(i, contentLength), contentLength); } } else tcpClient.Client.Send(finalBytes); while (true) { var responseBytes = new byte[8192]; int i = tcpClient.Client.Receive(responseBytes); if (i == 0) break; responseStr += Encoding.UTF8.GetString(responseBytes, 0, i); responseLength += i; } } tcpClient.Close(); var bodyPos = responseStr.IndexOf("\r\n\r\n"); if (bodyPos >= 0) { responseFields = responseStr.Substring(0, bodyPos).Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); bodyPos += 4; responseFromServer = responseStr.Substring(bodyPos, responseStr.Length - bodyPos); } Debug.WriteLine(String.Format("Response from URL {0}:", url), "HTTPFetch"); Debug.WriteLine(responseFromServer, "HTTPFetch"); if (VerboseCallback != null) { VerboseCallback(String.Format("Response from URL {0}:", url)); VerboseCallback(responseFromServer); } return responseFromServer; } catch (Exception e) { _active = false; throw e; } }
public ActionResult Edit(int id, Session updatedSession) { SessionModelContainer ctx = new SessionModelContainer(); Session currentSession = ctx.Sessions.First(s => s.Id == id); String message = currentSession.Code + ": "; bool changed = false; currentSession.Code = updatedSession.Code; if (currentSession.Title != updatedSession.Title) { currentSession.Title = updatedSession.Title; message += "Title changed to "+updatedSession.Title; changed = true; } if (currentSession.Room != updatedSession.Room) { currentSession.Room = updatedSession.Room; message += "Room changed to "+updatedSession.Room; changed = true; } if (changed) { // send a push notification message to the device string host = "gateway.sandbox.push.apple.com"; int port = 2195; // load the certificate file string certPath = @"c:\temp\teched_APN.p12"; X509Certificate2 clientCert = new X509Certificate2(certPath, "Password"); X509Certificate2Collection certCollection = new X509Certificate2Collection(clientCert); // open connection and connect TcpClient client = new TcpClient(host, port); SslStream sslStream = new SslStream(client.GetStream(), false); try { sslStream.AuthenticateAsClient(host, certCollection, SslProtocols.Tls, false); } catch (AuthenticationException ex) { Console.WriteLine(ex.InnerException.ToString()); Console.In.Read(); client.Close(); return RedirectToAction("Index"); } MemoryStream memoryStream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(memoryStream); // construct the message writer.Write((byte)0); // Command writer.Write((byte)0); // First byte of device ID length writer.Write((byte)32); // Device id length String deviceId = "e18ac3b8a408e4e972e171a05cdba8f046ff3724ef999093c2b479397b8c40fe"; //Simon's iPhone // convert to hex and write to message byte[] deviceToken = new byte[deviceId.Length / 2]; for (int i = 0; i < deviceToken.Length; i++) deviceToken[i] = byte.Parse(deviceId.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); writer.Write(deviceToken); // construct payload within JSON message framework String payload = "{\"aps\":{\"alert\":\""+message+"\",\"badge\":1}}"; // write payload data writer.Write((byte)0); // First byte of payload length writer.Write((byte)payload.Length); // Actual payload length byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload); writer.Write(b1); writer.Flush(); // send across the wire byte[] array = memoryStream.ToArray(); sslStream.Write(array); sslStream.Flush(); // Close the client connection. client.Close(); // Success Console.WriteLine("Message has been sent! Please check device."); Console.In.Read(); } ctx.SaveChanges(); return RedirectToAction("Index"); }
/// <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); }
private bool TestHttpViaSocket(Socket socket, TestInfo info) { try { using (var nets = new NetworkStream(socket)) { using (var ssls = new SslStream(nets, false, (sender, cert, chain, sslpe) => { var str = cert.Subject; var len = str.IndexOf(",", 3) - 3; info.CName = str.Substring(3, len > 0 ? len : str.Length - 3); return true; })) { ssls.AuthenticateAsClient(string.Empty); if (ssls.IsAuthenticated) { var data = Encoding.UTF8.GetBytes(string.Format("HEAD /search?q=g HTTP/1.1\r\nHost: www.google.com.hk\r\n\r\nGET /{0} HTTP/1.1\r\nHost: azzvxgoagent{1}.appspot.com\r\nConnection: close\r\n\r\n", Application.ProductVersion, Rand.Next(7))); ssls.Write(data); ssls.Flush(); using (var sr = new StreamReader(ssls)) { var text = sr.ReadToEnd(); if (text.Length == 0) { info.HttpOk = false; info.HttpMsg = "NN BadResponse"; } else { info.HttpMsg = "NN"; var ms = RxResult.Matches(text); for (var i = 0; i < ms.Count; i++) { if (ms[i].Groups[2].Value == "200" && ++i < ms.Count) switch (ms[i].Groups[3].Value) { case "gws\r": info.HttpOk = true; info.HttpMsg = "G" + info.HttpMsg[1]; break; case "Google Frontend\r": info.HttpOk = true; info.HttpMsg = info.HttpMsg[0] + "A"; break; default: i--; break; } } } } } else { info.HttpOk = false; info.HttpMsg = "NN SslInvalid"; } } } } catch (Exception ex) { info.HttpOk = false; info.HttpMsg = "NN " + ex.Message; } return info.HttpOk; }
public virtual string socketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<string, string> config) { var url = config["onlineBatchUrl"]; var port = int.Parse(config["onlineBatchPort"]); TcpClient tcpClient = null; SslStream sslStream = null; 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); } var stringBuilder = _cache[xmlRequestFilePath]; var buffer = Encoding.UTF8.GetBytes(stringBuilder.ToString()); sslStream.Write(buffer); sslStream.Flush(); var batchName = Path.GetFileName(xmlRequestFilePath); if ("true".Equals(config["printxml"])) { Console.WriteLine("Writing to XML File: " + xmlResponseDestinationDirectory + batchName); } var byteBuffer = new byte[2048]; var messageData = new StringBuilder(); var bytes = -1; do { // Read the client's test message. bytes = sslStream.Read(byteBuffer, 0, byteBuffer.Length); // Use Decoder class to convert from bytes to UTF8 // in case a character spans two buffers. var decoder = Encoding.UTF8.GetDecoder(); var chars = new char[decoder.GetCharCount(byteBuffer, 0, bytes)]; decoder.GetChars(byteBuffer, 0, bytes, chars, 0); messageData.Append(chars); } while (bytes != 0); _cache.Add(xmlResponseDestinationDirectory + batchName, messageData); tcpClient.Close(); sslStream.Close(); return xmlResponseDestinationDirectory + batchName; }
private static void ConnectAndSend() { TcpClient client = new TcpClient("localhost", port); SslStream sslStream = new SslStream( client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null ); // The server name must match the name on the server certificate. sslStream.AuthenticateAsClient("TempCert"); Debug.WriteLine("Client sending: hello"); sslStream.Write(Encoding.UTF8.GetBytes("hello \n")); sslStream.Flush(); Debug.WriteLine("Client sending: send"); sslStream.Write(Encoding.UTF8.GetBytes("send\n")); sslStream.Flush(); String line = ReadMessage(sslStream); Debug.WriteLine("Client got: " + line); client.Close(); Assert.IsTrue(!String.IsNullOrEmpty(line)); }
public void Connect() { string host = mUrl.DnsSafeHost; string path = mUrl.PathAndQuery; string origin = "http://" + host; mSslStream = CreateSocket(mUrl); StringBuilder extraHeaders = new StringBuilder(); if (mHeaders != null) { foreach (KeyValuePair<string, string> header in mHeaders) extraHeaders.Append(header.Key + ": " + header.Value + "\r\n"); } string request = "GET " + path + " HTTP/1.1\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Host: " + host + "\r\n" + "Sec-WebSocket-Version: 6\r\n" + "Sec-WebSocket-Origin: https://" + host + "\r\n" + "Sec-WebSocket-Extensions: deflate-stream\r\n" + "Sec-WebSocket-Key: HSmrc0sMlYUkAGmm5OPpG2HaGWk=\r\n" + // note see: https://en.wikipedia.org/wiki/WebSocket on draft-ietf-hybi-thewebsocketprotocol-06 version of protocol for instructions on how to construct the key extraHeaders.ToString() + "\r\n"; byte[] sendBuffer = Encoding.UTF8.GetBytes(request); mSslStream.Write(sendBuffer, 0, sendBuffer.Length); mSslStream.Flush(); string reply = ReadMessage(mSslStream); if (!reply.Equals("HTTP/1.1 101 Web Socket Protocol Handshake")) throw new IOException("Invalid handshake response"); if (!reply.Equals("Upgrade: WebSocket")) throw new IOException("Invalid handshake response"); if (!reply.Equals("Connection: Upgrade")) throw new IOException("Invalid handshake response"); mHandshakeComplete = true; }
SecureConnection EstablishNewConnection() { log.Write(EventType.OpeningNewConnection, "Opening a new connection"); var remoteUri = serviceEndpoint.BaseUri; var certificateValidator = new ClientCertificateValidator(serviceEndpoint.RemoteThumbprint); var client = CreateTcpClient(); client.ConnectWithTimeout(remoteUri, HalibutLimits.TcpClientConnectTimeout); log.Write(EventType.Diagnostic, "Connection established"); var stream = client.GetStream(); log.Write(EventType.Security, "Performing TLS handshake"); var ssl = new SslStream(stream, false, certificateValidator.Validate, UserCertificateSelectionCallback); ssl.AuthenticateAsClient(remoteUri.Host, new X509Certificate2Collection(clientCertificate), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false); ssl.Write(MxLine, 0, MxLine.Length); ssl.Flush(); log.Write(EventType.Security, "Secure connection established. Server at {0} identified by thumbprint: {1}, using protocol {2}", client.Client.RemoteEndPoint, serviceEndpoint.RemoteThumbprint, ssl.SslProtocol.ToString()); var protocol = new MessageExchangeProtocol(ssl, log); return new SecureConnection(client, ssl, protocol); }
public static void Send(string s, SslStream sslStream) { byte[] b = Encoding.ASCII.GetBytes(s); sslStream.Write(b, 0, b.Length); sslStream.Flush(); }
static byte[] InternalSslSocketHttp(IPEndPoint endpoint, X509CertificateCollection certificates, HttpArgs args, HttpMethod method) { TcpClient tcp = new TcpClient(); try { tcp.Connect(endpoint); if (tcp.Connected) { using (SslStream ssl = new SslStream(tcp.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null)) { ssl.AuthenticateAsClient("ServerName", certificates, SslProtocols.Tls, false); if (ssl.IsAuthenticated) { byte[] buff = ParseHttpArgs(method, args); //生成协议包 ssl.Write(buff); ssl.Flush(); return ParseSslResponse(endpoint, ssl, args, certificates); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; }
public static void SendPacket(Packet packet, SslStream stream) { try { ProtoFire reply = new ProtoFire(packet); byte[] result = reply.Encode(); if (packet.msgType == MessageType.NOTIFICATION) { LogNotification(packet); } else { LogResponse(packet); } stream.Write(result, 0, result.Length); stream.Flush(); } catch (Exception ex) { Log.Error(ex.ToString()); } }
private TestInfo TestBandwidth(TestInfo info) { const int m = 2; using (var socket = GetSocket(info, m)) { try { if (socket.BeginConnect(info.Target, null, null).AsyncWaitHandle.WaitOne(Config.ConnTimeout * m) && socket.Connected) { using (var nets = new NetworkStream(socket)) { using (var ssls = new SslStream(nets, false, (a, b, c, d) => true)) { ssls.AuthenticateAsClient(string.Empty); if (ssls.IsAuthenticated) { var data = Encoding.UTF8.GetBytes("GET /p/gogo-tester/source/browse/1m.wiki?repo=wiki HTTP/1.1\r\nHost: code.google.com\r\nConnection: close\r\n\r\n"); var time = Watch.ElapsedMilliseconds; ssls.Write(data, 0, data.Length); ssls.Flush(); using (var sr = new StreamReader(ssls)) { sr.BaseStream.ReadTimeout = 5000; try { var buf = sr.ReadToEnd(); info.Bandwidth = (buf.Length / (Watch.ElapsedMilliseconds - time)).ToString("D4") + " KB/s"; } catch (Exception) { info.Bandwidth = "TimeOut!"; } } } else { info.Bandwidth = "SslInvalid"; } } } } else { info.Bandwidth = "Timeout"; } } catch (Exception ex) { info.Bandwidth = ex.Message; } } return info; }