Example #1
0
        /// <inheritdoc/>
        public override void Process(BotData data)
        {
            base.Process(data);

            var  ws          = data.GetCustomObject(nameof(WebSocket)) as WebSocket;
            var  receivedMsg = string.Empty;
            bool onMsg       = false;

            switch (Command)
            {
            case WSCommand.Connect:
            {
                var inputs = ReplaceValues(Url, data);
                try { ws?.Close(CloseStatusCode.NoStatus); } catch { }
                ws = new WebSocket(inputs)
                {
                    Compression       = Compression,
                    Origin            = Origin,
                    WaitTime          = WaitTime,
                    EmitOnPing        = EmitOnPing,
                    EnableRedirection = Redirection,
                };
                ws.SslConfiguration.EnabledSslProtocols = SslProtocols;
                //ws.SetProxy()

                if (Credentials)
                {
                    ws.SetCredentials(ReplaceValues(Username, data), ReplaceValues(Password, data), PreAuth);
                }

                // Set cookies
                data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise));

                foreach (var cookie in CustomCookies)         // Add new user-defined custom cookies to the bot's cookie jar
                {
                    ws.SetCookie(new WebSocketSharp.Net.Cookie(ReplaceValues(cookie.Key, data), ReplaceValues(cookie.Value, data), "/"));
                    data.LogBuffer.Add(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.MediumTurquoise));
                }
                foreach (var cookie in data.Cookies)
                {
                    ws.SetCookie(new WebSocketSharp.Net.Cookie(ReplaceValues(cookie.Key, data), ReplaceValues(cookie.Value, data), "/"));
                    data.LogBuffer.Add(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.MediumTurquoise));
                }
#if DEBUG
                ws.Log.Level = WebSocketSharp.LogLevel.Trace;
#endif

                ws.OnMessage += new EventHandler <MessageEventArgs>((s, e) =>
                    {
                        onMsg   = true;
                        var msg = string.Empty;
                        if (e.IsText)
                        {
                            receivedMsg += $"{msg = e.Data}\n";
                        }
                        else if (e.IsBinary)
                        {
                            receivedMsg += $"{msg = Encoding.ASCII.GetString(e.RawData)}\n";
                        }

                        data.Log(new LogEntry($"On Message Ev: {msg}", Colors.Yellow));
                    });

                ws.ConnectAsync();

                if (!WaitForConnect(ws))
                {
                    throw new Exception($"Connection Status: {ws.ReadyState}");
                }

                data.CustomObjects[nameof(WebSocket)] = ws;
                data.Log(new LogEntry($"Succesfully connected to url: {inputs}.", Colors.LimeGreen));
                data.Log(new LogEntry($"Connection Status: {ws.ReadyState}", Colors.LimeGreen));
                data.Log(new LogEntry(receivedMsg, Colors.GreenYellow));
            }
            break;

            case WSCommand.Disconnect:
            {
                if (ws == null)
                {
                    throw new Exception("Make a connection first!");
                }
                ws.CloseAsync(CloseStatusCode.Normal);
                ws = null;
                data.Log(new LogEntry($"Succesfully closed", Colors.GreenYellow));
                data.CustomObjects[nameof(WebSocket)] = null;
            }
            break;

            case WSCommand.Send:
            {
                if (ws == null)
                {
                    throw new Exception("Make a connection first!");
                }
                var  msg           = ReplaceValues(Message, data);
                var  bytes         = Encoding.ASCII.GetBytes(msg.Unescape());
                bool?wsSendReplied = null;
                data.Log(new LogEntry($"Sending {Message}", Colors.GreenYellow));
                ws.SendAsync(bytes, (completed) =>
                    {
                        wsSendReplied = completed;
                        if (completed)
                        {
                            data.Log(new LogEntry("Success to send Message", Colors.GreenYellow));
                        }
                        else
                        {
                            data.Log(new LogEntry("Failure to send Message", Colors.Red));
                        }
                    });
                TaskExtensions.WaitUntil(() => wsSendReplied.HasValue, timeout: 100).Wait();
            }
            break;
            }
            try
            {
                TaskExtensions.WaitUntil(() => onMsg,
                                         timeout: 500)
                .Wait();
            }
            catch { }

            if (!string.IsNullOrEmpty(VariableName))
            {
                InsertVariable(data, IsCapture, receivedMsg, VariableName);
            }
        }
Example #2
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            // Get easy handles
            var tcp = data.GetCustomObject("TCPClient") as TcpClient;
            var net = data.GetCustomObject("NETStream") as NetworkStream;
            var ssl = data.GetCustomObject("SSLStream") as SslStream;

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

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

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

                if (tcp.Connected)
                {
                    net = tcp.GetStream();

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

                    if (WaitForHello)
                    {
                        // Read the stream to make sure we are connected
                        if (UseSSL)
                        {
                            bytes = ssl.Read(buffer, 0, buffer.Length);
                        }
                        else
                        {
                            bytes = net.Read(buffer, 0, buffer.Length);
                        }

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

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

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

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

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

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

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

                var    msg     = ReplaceValues(Message, data);
                byte[] b       = { };
                var    payload = Encoding.ASCII.GetBytes(msg.Unescape());

                // Manual implementation of the WebSocket frame
                if (WebSocket)
                {
                    #region WebSocket
                    List <byte> bl = new List <byte>();

                    // (FIN=1) (RSV1=0) (RSV2=0) (RSV3=0) (OPCODE=0001) = 128 + 1 = 129
                    bl.Add(129);

                    ulong pllen = (ulong)payload.Length;

                    // We add 128 because the mask bit (MSB) is always 1. In this case the payload len is 7 bits long
                    if (pllen <= 125)
                    {
                        bl.Add((byte)(pllen + 128));
                    }

                    // Payload len set to 126 -> Next 2 bytes are payload len
                    else if (pllen <= ushort.MaxValue)
                    {
                        bl.Add(126 + 128);
                        bl.Add((byte)(pllen >> 8));     // Shift by 1 byte
                        bl.Add((byte)(pllen % 255));    // Take LSB
                    }

                    // Payload len set to 127 -> Next 4 bytes are payload len
                    else if (pllen <= ulong.MaxValue)
                    {
                        bl.Add(127 + 128);
                        bl.Add((byte)(pllen >> 24));         // Shift by 3 bytes
                        bl.Add((byte)((pllen >> 16) % 255)); // Shift by 2 bytes and take LSB
                        bl.Add((byte)((pllen >> 8) % 255));  // Shift by 1 byte and take LSB
                        bl.Add((byte)(pllen % 255));         // Take LSB
                    }

                    // Set the mask used for this message
                    byte[] mask = new byte[4] {
                        61, 84, 35, 6
                    };
                    bl.AddRange(mask);

                    // Finally we add the payload XORed with the mask
                    for (int i = 0; i < payload.Length; i++)
                    {
                        bl.Add((byte)(payload[i] ^ mask[i % 4]));
                    }

                    b = bl.ToArray();
                    #endregion
                }
                else
                {
                    b = payload;
                }
                data.Log(new LogEntry("> " + msg, Colors.White));

                var TCPSSL = data.GetCustomObject("TCPSSL") as bool?;
                if (TCPSSL.HasValue && TCPSSL.Value)
                {
                    ssl.Write(b);
                    bytes = ssl.Read(buffer, 0, buffer.Length);
                }
                else
                {
                    net.Write(b, 0, b.Length);
                    bytes = net.Read(buffer, 0, buffer.Length);
                }

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

                if (VariableName != string.Empty)
                {
                    data.Variables.Set(new CVar(VariableName, response, IsCapture));
                    data.Log(new LogEntry($"Saved Response in variable {VariableName}.", Colors.White));
                }
                break;
            }
        }
Example #3
0
        /// <inheritdoc/>
        public override void Process(BotData data)
        {
            base.Process(data);

            var  ws         = data.GetCustomObject(nameof(WebSocket)) as WebSocket;
            var  wsMessages = data.GetCustomObject(nameof(WebSocket) + "Messages") as List <string>;
            bool onMsg      = false;

            switch (Command)
            {
            case WSCommand.Connect:
            {
                var inputs = ReplaceValues(Url, data);
                try { ws?.Close(CloseStatusCode.NoStatus); } catch { }
                ws = new WebSocket(inputs)
                {
                    Compression       = Compression,
                    Origin            = Origin,
                    WaitTime          = WaitTime,
                    EmitOnPing        = EmitOnPing,
                    EnableRedirection = Redirection,
                };
                ws.SslConfiguration.EnabledSslProtocols = SslProtocols;

                if (data.UseProxies)
                {
                    if (data.Proxy.Type != Extreme.Net.ProxyType.Http)
                    {
                        throw new NotSupportedException("Only HTTP proxy is supported");
                    }
                    ws.SetProxy($"http://{data.Proxy.Host}:{data.Proxy.Port}", data.Proxy.Username, data.Proxy.Password);
                }

                if (Credentials)
                {
                    ws.SetCredentials(ReplaceValues(Username, data), ReplaceValues(Password, data), PreAuth);
                }

                // Set cookies
                data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise));

                foreach (var cookie in CustomCookies)         // Add new user-defined custom cookies to the bot's cookie jar
                {
                    ws.SetCookie(new WebSocketSharp.Net.Cookie(ReplaceValues(cookie.Key, data), ReplaceValues(cookie.Value, data), "/"));
                    data.LogBuffer.Add(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.MediumTurquoise));
                }
                foreach (var cookie in data.Cookies)
                {
                    ws.SetCookie(new WebSocketSharp.Net.Cookie(ReplaceValues(cookie.Key, data), ReplaceValues(cookie.Value, data), "/"));
                    data.LogBuffer.Add(new LogEntry($"{cookie.Key}: {cookie.Value}", Colors.MediumTurquoise));
                }
#if DEBUG
                ws.Log.Level = WebSocketSharp.LogLevel.Trace;
#endif

                if (wsMessages == null)
                {
                    wsMessages = new List <string>();
                }
                data.CustomObjects[nameof(WebSocket) + "Messages"] = wsMessages;
                ws.OnMessage += (sender, e) =>
                {
                    lock (wsMessages)
                    {
                        wsMessages.Add(e.Data);
                    }
                };

                // Connect
                ws.Connect();

                if (!WaitForConnect(ws))
                {
                    throw new Exception($"Connection Status: {ws.ReadyState}");
                }

                data.CustomObjects[nameof(WebSocket)] = ws;
                data.Log(new LogEntry($"Succesfully connected to url: {inputs}.", Colors.LimeGreen));
                data.Log(new LogEntry($"Connection Status: {ws.ReadyState}", Colors.LimeGreen));
            }
            break;

            case WSCommand.Disconnect:
            {
                if (ws == null)
                {
                    throw new NullReferenceException("Make a connection first!");
                }
                ws.Close();
                ws = null;
                data.Log(new LogEntry($"Succesfully closed", Colors.GreenYellow));
                data.CustomObjects[nameof(WebSocket)] = null;
            }
            break;

            case WSCommand.Send:
            {
                if (ws == null)
                {
                    throw new NullReferenceException("Make a connection first!");
                }
                var msg = ReplaceValues(Message, data);
                ws.Send(msg);
                data.Log(new LogEntry($"Sent {msg} to the server", Colors.LimeGreen));
            }
            break;

            case WSCommand.Read:
                if (ws == null)
                {
                    throw new NullReferenceException("Make a connection first!");
                }
                wsMessages = data.CustomObjects[nameof(WebSocket) + "Messages"] as List <string>;
                data.Log(new LogEntry($"Unread messages from server", Colors.LimeGreen));
                break;
            }

            if (!string.IsNullOrEmpty(VariableName))
            {
                InsertVariable(data, IsCapture, wsMessages, VariableName);
                wsMessages.Clear();
            }
        }