Ejemplo n.º 1
0
        public void ProxyShouldHaveReceivedExpectedSocksRequest()
        {
            var expectedSocksRequest = new List <byte>();

            //
            // Client greeting
            //

            // SOCKS version
            expectedSocksRequest.Add(0x05);
            // Number of authentication methods supported
            expectedSocksRequest.Add(0x02);
            // No authentication
            expectedSocksRequest.Add(0x00);
            // Username/password
            expectedSocksRequest.Add(0x02);

            //
            // Username/password authentication request
            //

            // Version of the negotiation
            expectedSocksRequest.Add(0x01);
            // Length of the username
            expectedSocksRequest.Add((byte)_connectionInfo.ProxyUsername.Length);
            // Username
            expectedSocksRequest.AddRange(Encoding.ASCII.GetBytes(_connectionInfo.ProxyUsername));
            // Length of the password
            expectedSocksRequest.Add((byte)_connectionInfo.ProxyPassword.Length);
            // Password
            expectedSocksRequest.AddRange(Encoding.ASCII.GetBytes(_connectionInfo.ProxyPassword));

            //
            // Client connection request
            //

            // SOCKS version
            expectedSocksRequest.Add(0x05);
            // Establish a TCP/IP stream connection
            expectedSocksRequest.Add(0x01);
            // Reserved
            expectedSocksRequest.Add(0x00);
            // Destination address type (IPv4)
            expectedSocksRequest.Add(0x01);
            // Destination address (IPv4)
            expectedSocksRequest.Add(0x7f);
            expectedSocksRequest.Add(0x00);
            expectedSocksRequest.Add(0x00);
            expectedSocksRequest.Add(0x01);
            // Destination port
            expectedSocksRequest.Add(0x03);
            expectedSocksRequest.Add(0x09);

            var errorText = string.Format("Expected:{0}{1}{0}but was:{0}{2}",
                                          Environment.NewLine,
                                          PacketDump.Create(expectedSocksRequest, 2),
                                          PacketDump.Create(_bytesReceivedByProxy, 2));

            Assert.IsTrue(expectedSocksRequest.SequenceEqual(_bytesReceivedByProxy), errorText);
        }
Ejemplo n.º 2
0
        public void Create_ByteArrayAndIndentLevel_DataIsEmpty()
        {
            var data = new byte[0];

            var actual = PacketDump.Create(data, 2);

            Assert.AreEqual(string.Empty, actual);
        }
        /// <summary>
        ///     This function reports a missing packet handler to the console. It writes the length and type of the
        ///     packet, then a packet dump to the console.
        /// </summary>
        /// <param name="packet">The packet buffer being reported.</param>
        public static void Report(byte[] packet)
        {
            ushort length   = BitConverter.ToUInt16(packet, 0);
            ushort identity = BitConverter.ToUInt16(packet, 2);

            // Print the packet and the packet header:
            Program.Log.WriteToFile($"Missing Packet Handler: {identity} (Length: {length})", "missing_packet");
            Program.Log.WriteToFile(PacketDump.Hex(packet), "missing_packet");
        }
Ejemplo n.º 4
0
        public void Create_ByteArrayAndIndentLevel_DataIsLineWith()
        {
            var data = new byte[]
            {
                0x07, 0x00, 0x1f, 0x65, 0x20, 0x62, 0x09, 0x44, 0x7f, 0x0d, 0x0a, 0x36, 0x80, 0x53, 0x53, 0x48
            };
            var expected = "  00000000  07 00 1F 65 20 62 09 44 7F 0D 0A 36 80 53 53 48  ...e b.D...6.SSH";

            var actual = PacketDump.Create(data, 2);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Performs a blocking read on the socket until a line is read.
        /// </summary>
        /// <param name="socket">The <see cref="Socket"/> to read from.</param>
        /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until a line is read.</param>
        /// <param name="buffer">A <see cref="List{Byte}"/> to which read bytes will be added.</param>
        /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
        /// <exception cref="SocketException">An error occurred when trying to access the socket.</exception>
        /// <returns>
        /// The line read from the socket, or <c>null</c> when the remote server has shutdown and all data has been received.
        /// </returns>
        private static string SocketReadLine(Socket socket, TimeSpan timeout, List <byte> buffer)
        {
            var data = new byte[1];

            var startPosition = buffer.Count;

            // Read data one byte at a time to find end of line and leave any unhandled information in the buffer
            // to be processed by subsequent invocations.
            while (true)
            {
                var bytesRead = SocketAbstraction.Read(socket, data, 0, data.Length, timeout);
                if (bytesRead == 0)
                {
                    // The remote server shut down the socket.
                    break;
                }

                var byteRead = data[0];
                buffer.Add(byteRead);

                // The null character MUST NOT be sent
                if (byteRead == Null)
                {
                    throw new SshConnectionException(string.Format(CultureInfo.InvariantCulture,
                                                                   "The server response contains a null character at position 0x{0:X8}:{1}{1}{2}{1}{1}" +
                                                                   "A server must not send a null character before the Protocol Version Exchange is complete.{1}{1}" +
                                                                   "More information is available here:{1}" +
                                                                   "https://tools.ietf.org/html/rfc4253#section-4.2",
                                                                   buffer.Count,
                                                                   Environment.NewLine,
                                                                   PacketDump.Create(buffer.ToArray(), 2)));
                }

                if (byteRead == Session.LineFeed)
                {
                    if (buffer.Count > startPosition + 1 && buffer[buffer.Count - 2] == Session.CarriageReturn)
                    {
                        // Return current line without CRLF
                        return(Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 2)));
                    }
                    else
                    {
                        // Even though RFC4253 clearly indicates that the identification string should be terminated
                        // by a CR LF we also support banners and identification strings that are terminated by a LF

                        // Return current line without LF
                        return(Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 1)));
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 6
0
        public void Create_ByteArrayAndIndentLevel_DataIsMultipleOfLineWidth_IndentLevelZero()
        {
            var data = new byte[]
            {
                0x07, 0x00, 0x1f, 0x65, 0x20, 0x62, 0x09, 0x44, 0x7f, 0x0d, 0x0a, 0x36, 0x80, 0x53, 0x53, 0x48,
                0x2e, 0x4e, 0x45, 0x54, 0x20, 0x32, 0x30, 0x32, 0x30, 0x20, 0xf6, 0x7a, 0x32, 0x7f, 0x1f, 0x7e
            };
            var expected = "00000000  07 00 1F 65 20 62 09 44 7F 0D 0A 36 80 53 53 48  ...e b.D...6.SSH" +
                           Environment.NewLine +
                           "00000010  2E 4E 45 54 20 32 30 32 30 20 F6 7A 32 7F 1F 7E  .NET 2020 .z2..~";

            var actual = PacketDump.Create(data, 0);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 7
0
        public void Create_ByteArrayAndIndentLevel_DataIsGreaterThanLineWidthButLessThanMultipleOfLineWidth()
        {
            var data = new byte[]
            {
                0x07, 0x00, 0x1f, 0x65, 0x20, 0x62, 0x09, 0x44, 0x7f, 0x0d, 0x0a, 0x36, 0x80, 0x53, 0x53, 0x48,
                0x2e, 0x4e, 0x45, 0x54
            };
            var expected = "  00000000  07 00 1F 65 20 62 09 44 7F 0D 0A 36 80 53 53 48  ...e b.D...6.SSH" +
                           Environment.NewLine +
                           "  00000010  2E 4E 45 54                                      .NET";

            var actual = PacketDump.Create(data, 2);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 8
0
        public void Create_ByteArrayAndIndentLevel_DataIsNull()
        {
            const byte[] data = null;

            try
            {
                PacketDump.Create(data, 0);
                Assert.Fail();
            }
            catch (ArgumentNullException ex)
            {
                Assert.IsNull(ex.InnerException);
                Assert.AreEqual("data", ex.ParamName);
            }
        }
Ejemplo n.º 9
0
        public void Create_ByteArrayAndIndentLevel_IndentLevelLessThanZero()
        {
            var data = new byte[0];

            try
            {
                PacketDump.Create(data, -1);
                Assert.Fail();
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.IsNull(ex.InnerException);
                Assert.AreEqual(string.Format("Cannot be less than zero.{0}Parameter name: {1}", Environment.NewLine, ex.ParamName), ex.Message);
                Assert.AreEqual("indentLevel", ex.ParamName);
            }
        }
Ejemplo n.º 10
0
        public void ProxyShouldHaveReceivedExpectedSocksRequest()
        {
            var expectedSocksRequest = new byte[]
            {
                //
                // Client greeting
                //

                // SOCKS version
                0x05,
                // Number of authentication methods supported
                0x02,
                // No authentication
                0x00,
                // Username/password
                0x02,

                //
                // Client connection request
                //

                // SOCKS version
                0x05,
                // Establish a TCP/IP stream connection
                0x01,
                // Reserved
                0x00,
                // Destination address type (IPv4)
                0x01,
                // Destination address (IPv4)
                0x7f,
                0x00,
                0x00,
                0x01,
                // Destination port
                0x03,
                0x09
            };

            var errorText = string.Format("Expected:{0}{1}{0}but was:{0}{2}",
                                          Environment.NewLine,
                                          PacketDump.Create(expectedSocksRequest, 2),
                                          PacketDump.Create(_bytesReceivedByProxy, 2));

            Assert.IsTrue(expectedSocksRequest.SequenceEqual(_bytesReceivedByProxy), errorText);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Performs the SSH protocol version exchange.
        /// </summary>
        /// <param name="clientVersion">The identification string of the SSH client.</param>
        /// <param name="socket">A <see cref="Socket"/> connected to the server.</param>
        /// <param name="timeout">The maximum time to wait for the server to respond.</param>
        /// <returns>
        /// The SSH identification of the server.
        /// </returns>
        public SshIdentification Start(string clientVersion, Socket socket, TimeSpan timeout)
        {
            // Immediately send the identification string since the spec states both sides MUST send an identification string
            // when the connection has been established
            SocketAbstraction.Send(socket, Encoding.UTF8.GetBytes(clientVersion + "\x0D\x0A"));

            var bytesReceived = new List <byte>();

            // Get server version from the server,
            // ignore text lines which are sent before if any
            while (true)
            {
                var line = SocketReadLine(socket, timeout, bytesReceived);
                if (line == null)
                {
                    if (bytesReceived.Count == 0)
                    {
                        throw new SshConnectionException(string.Format("The server response does not contain an SSH identification string.{0}" +
                                                                       "The connection to the remote server was closed before any data was received.{0}{0}" +
                                                                       "More information on the Protocol Version Exchange is available here:{0}" +
                                                                       "https://tools.ietf.org/html/rfc4253#section-4.2",
                                                                       Environment.NewLine),
                                                         DisconnectReason.ConnectionLost);
                    }

                    throw new SshConnectionException(string.Format("The server response does not contain an SSH identification string:{0}{0}{1}{0}{0}" +
                                                                   "More information on the Protocol Version Exchange is available here:{0}" +
                                                                   "https://tools.ietf.org/html/rfc4253#section-4.2",
                                                                   Environment.NewLine,
                                                                   PacketDump.Create(bytesReceived, 2)),
                                                     DisconnectReason.ProtocolError);
                }

                var identificationMatch = ServerVersionRe.Match(line);
                if (identificationMatch.Success)
                {
                    return(new SshIdentification(GetGroupValue(identificationMatch, "protoversion"),
                                                 GetGroupValue(identificationMatch, "softwareversion"),
                                                 GetGroupValue(identificationMatch, "comments")));
                }
            }
        }
Ejemplo n.º 12
0
        private void LoadPacketDumpFromFile(string logPath)
        {
            // No file loaded, prompt for one.
            if (String.IsNullOrEmpty(logPath))
            {
                loadPacketDumpToolStripMenuItem_Click(null, null);
                return;
            }

            var packetList = new List <Packet>();

            if (!PacketDump.Load(logPath, ref packetList))
            {
                DisplayError("Failed to load packet dump. Please verify that the file exists, and is not currently in use.");
                return;
            }

            _logPath = logPath;

            Text = string.Format("{0} - {1}", _baseTitle, logPath);
            LoadPacketDump(packetList);
        }
        public void ProxyShouldHaveReceivedExpectedSocksRequest()
        {
            var expectedSocksRequest = new List <byte>();

            //
            // Client greeting
            //

            // SOCKS version
            expectedSocksRequest.Add(0x05);
            // Number of authentication methods supported
            expectedSocksRequest.Add(0x02);
            // No authentication
            expectedSocksRequest.Add(0x00);
            // Username/password
            expectedSocksRequest.Add(0x02);

            var errorText = string.Format("Expected:{0}{1}{0}but was:{0}{2}",
                                          Environment.NewLine,
                                          PacketDump.Create(expectedSocksRequest, 2),
                                          PacketDump.Create(_bytesReceivedByProxy, 2));

            Assert.IsTrue(expectedSocksRequest.SequenceEqual(_bytesReceivedByProxy), errorText);
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            MsgRequestInfo msg = new MsgRequestInfo();

            msg.Create(AutoUpdateRequestType.CheckForGameUpdates);
            Console.WriteLine(PacketDump.Hex(msg));

            MsgRequestInfo decode = new MsgRequestInfo(msg);

            Console.WriteLine(PacketDump.Hex(msg));

            StringPacker packer = new StringPacker("Testando", "Aurelio", "Felipe", "Teste", "StringPacker", "FTW! Masters");

            Console.WriteLine(PacketDump.Hex(packer.ToArray()));

            packer = new StringPacker(packer.ToArray());
            foreach (var str in packer.GetStrings())
            {
                Console.WriteLine(str);
            }

            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }