Пример #1
0
        public static void Main(string[] args)
        {
            ushort tcpSourcePort = 123;
            ushort tcpDestinationPort = 321;
            var tcpPacket = new TcpPacket(tcpSourcePort, tcpDestinationPort);

            var ipSourceAddress = System.Net.IPAddress.Parse("192.168.1.1");
            var ipDestinationAddress = System.Net.IPAddress.Parse("192.168.1.2");
            var ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress);

            var sourceHwAddress = "90-90-90-90-90-90";
            var ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);
            var destinationHwAddress = "80-80-80-80-80-80";
            var ethernetDestinationHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(destinationHwAddress);
            // NOTE: using EthernetPacketType.None to illustrate that the ethernet
            //       protocol type is updated based on the packet payload that is
            //       assigned to that particular ethernet packet
            var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress,
                                                    ethernetDestinationHwAddress,
                                                    EthernetPacketType.None);

            // Now stitch all of the packets together
            ipPacket.PayloadPacket = tcpPacket;
            ethernetPacket.PayloadPacket = ipPacket;

            // and print out the packet to see that it looks just like we wanted it to
            Console.WriteLine(ethernetPacket.ToString());
        }
Пример #2
0
        public void SendSupplyBoxOpen()
        {
            byte[] packet = new byte[]
            {
               0x69, 0x04, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0xEC, 0x04, 0x8B, 0x11, 0x17, 0x00, 0x00, 0x00,
            0xEC, 0x04, 0x00, 0x1F, 0xF7, 0x51, 0x8D, 0x0A, 0x00, 0x61, 0x00, 0x73, 0x00, 0x64, 0x00, 0x66,
            0x00, 0x00, 0x00
            };

            packet[4] = (byte)((int)(packet[4] + 10));
            Gunz2Packet.Encrypt(packet, 12, (uint)packet.Length - 12, _cryptKey);

            var checksum = Gunz2Packet.CalculateChecksum(packet, packet.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(checksum), 0, packet, 10, 2);

            var tcp = new TcpPacket(_srcPort, 20100);
            var ip = new IPv4Packet(_srcIP, _destIP);
            var ether = new EthernetPacket(_srcPhsyical, _destPhysical, EthernetPacketType.None);

            tcp.Ack = true;
            tcp.Psh = true;
            tcp.PayloadData = packet;
            ip.PayloadPacket = tcp;
            ether.PayloadPacket = ip;

            Console.WriteLine(ether);
            _device.SendPacket(ether);
        }
Пример #3
0
 public Connection(PacketDotNet.TcpPacket packet)
 {
     m_srcIp   = (packet.ParentPacket as PacketDotNet.IPv4Packet).SourceAddress.ToString();
     m_dstIp   = (packet.ParentPacket as PacketDotNet.IPv4Packet).DestinationAddress.ToString();
     m_srcPort = (ushort)packet.SourcePort;
     m_dstPort = (ushort)packet.DestinationPort;
 }
Пример #4
0
        internal MetinPacket(TcpPacket p, ushort authPort, ushort gamePort, string process)
        {
            Length = p.PayloadData.Length;
            Crypted = false;
            Route = GetRouteString(p, authPort, gamePort);
            Metin2Process = process;

            if (Length <= 0)
            {
                PacketString = string.Format("{0} | ID: XX | Len: {1} | NO PSH", Route, Length);
                return;
            }

            Id = p.PayloadData[0];
            Data = p.PayloadData;
            DestinationPort = p.DestinationPort;
            SourcePort = p.SourcePort;
            _authPort = authPort;
            _gamePort = gamePort;

            PSH = p.Psh;

            DecryptPacket();

            PacketString = string.Format("{0} | ID: {1} - {3} | Len: {2} | GuessedType : {4}", Route, Id.ToString("X2"),
                                         Length.ToString("D4"), Id.ToString("D3"), Type);
        }
Пример #5
0
 public Connection(TcpPacket packet)
 {
     IpPacket ipPacket = (IpPacket)packet.ParentPacket;
     m_srcIp = ipPacket.SourceAddress.ToString();
     m_dstIp = ipPacket.DestinationAddress.ToString();
     m_srcPort = (ushort)packet.SourcePort;
     m_dstPort = (ushort)packet.DestinationPort;
 }
 public PacketWrapper(TcpRecon tcpRecon)
 {
     Count = ++CaptureForm.packetCount;
     ipPacket = tcpRecon.IpPacket;
     rawCapture = tcpRecon.RawCapture;
     tcpPacket = tcpRecon.TcpPacket;
     Msg = tcpRecon.Msg.ToString();
 }
        public void CreationAndReparsing()
        {
            var tcpPacket = TcpPacket.RandomPacket();

            var tcpPacket2 = new TcpPacket(new ByteArraySegment(tcpPacket.Bytes));

            Console.WriteLine("tcpPacket {0}", tcpPacket);
            Console.WriteLine("tcpPacket2 {0}", tcpPacket2);
        }
Пример #8
0
 public void InsertPreviousTcpPacket(TcpPacket newPacket)
 {
     if (newPacket != null)
     {
         this.FirstSequenceNumber = newPacket.SequenceNumber;
         InsertDataFirstPosition(newPacket.PayloadData);
     }
     CreationTime = DateTime.Now;
 }
Пример #9
0
        private void Receive(IpPacket ipPacket)
        {
            var protocol = ipPacket.Protocol;
            if (protocol != IPProtocolType.TCP)
            {
                return;
            }
            if (ipPacket.PayloadPacket == null)
            {
                return;
            }
            var tcpPacket = new TcpPacket(new ByteArraySegment(ipPacket.PayloadPacket.BytesHighPerformance));

            var isFirstPacket = tcpPacket.Syn;
            var sourceIp = new IPAddress(ipPacket.SourceAddress.GetAddressBytes()).ToString();
            var destinationIp = new IPAddress(ipPacket.DestinationAddress.GetAddressBytes()).ToString();
            var connectionId = new ConnectionId(sourceIp, tcpPacket.SourcePort, destinationIp, tcpPacket.DestinationPort);

            lock (_lock)
            {
                TcpConnection connection;
                bool isInterestingConnection;
                if (isFirstPacket)
                {
                    connection = new TcpConnection(connectionId, tcpPacket.SequenceNumber);
                    OnNewConnection(connection);
                    isInterestingConnection = connection.HasSubscribers;
                    if (!isInterestingConnection)
                    {
                        return;
                    }
                    _connections[connectionId] = connection;
                    Debug.Assert(ipPacket.PayloadPacket.PayloadData.Length == 0);
                }
                else
                {
                    isInterestingConnection = _connections.TryGetValue(connectionId, out connection);
                    if (!isInterestingConnection)
                    {
                        return;
                    }

                    if (!string.IsNullOrEmpty(TcpLogFile))
                    {
                        File.AppendAllText(TcpLogFile,
                            string.Format("{0} {1}+{4} | {2} {3}+{4} ACK {5} ({6})\r\n",
                                connection.CurrentSequenceNumber, tcpPacket.SequenceNumber, connection.BytesReceived,
                                connection.SequenceNumberToBytesReceived(tcpPacket.SequenceNumber),
                                ipPacket.PayloadLength, tcpPacket.AcknowledgmentNumber,
                                connection.BufferedPacketDescription));
                    }
                    connection.HandleTcpReceived(tcpPacket.SequenceNumber,
                        new ByteArraySegment(ipPacket.PayloadPacket.PayloadData));
                }
            }
        }
Пример #10
0
 public TcpReconstructorPacket(TcpPacket packet)
 {
     if (packet != null)
     {
         this.Data = packet.PayloadData;
         this.FirstSequenceNumber = this.LastSequenceNumber = packet.SequenceNumber;
         this.Length = this.Data.Length;
     }
     CreationTime = DateTime.Now;
 }
Пример #11
0
        private static void runTcpParsers(TcpPacket packet)
        {
            var http = Http.Parse (packet);
            if (http != null) {
                Console.WriteLine (http.Print ());
            }

            var word = WordDetector.Parse (packet);
            if ((word != null) && (word.Found.Count > 0)) {
                Console.WriteLine (word.Print ());
            }
        }
Пример #12
0
        static void HandleOnPacketReceived(PosixTimeval timeval, PacketDotNet.TcpPacket tcp, TcpConnection connection, TcpFlow flow)
        {
            lock (DictionaryLock)
            {
                if (!TcpPackets.ContainsKey(flow))
                {
                    TcpPackets[flow] = new List <Entry>();
                }

                var entry = new Entry(timeval, tcp);
                TcpPackets[flow].Add(entry);
            }
        }
Пример #13
0
        public void TestSettingPayloadData()
        {
            byte[] data = new byte[10];
            for(int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            // NOTE: we use TcpPacket because it has a simple constructor. We can't
            //       create a Packet() instance because Packet is an abstract class
            var p = new TcpPacket(10, 10);
            p.PayloadData = data;
        }
Пример #14
0
        /// <summary>
        /// The main function of the class receives a tcp packet and reconstructs the stream
        /// </summary>
        /// <param name="tcpPacket"></param>
        public void ReassemblePacket(PacketDotNet.TcpPacket tcpPacket)
        {
            // if the paylod length is zero bail out
            //ulong length = (ulong)(tcpPacket.Bytes.Length - tcpPacket.TCPHeaderLength);
            //if (length == 0) return;
            if (tcpPacket.PayloadData == null || tcpPacket.PayloadData.Length == 0)
            {
                return;
            }

            reassemble_tcp((ulong)tcpPacket.SequenceNumber, (ulong)tcpPacket.PayloadData.Length,
                           tcpPacket.PayloadData, (ulong)tcpPacket.PayloadData.Length, tcpPacket.Syn,
                           (tcpPacket.ParentPacket as PacketDotNet.IPv4Packet).SourceAddress.Address,
                           (tcpPacket.ParentPacket as PacketDotNet.IPv4Packet).DestinationAddress.Address,
                           (uint)tcpPacket.SourcePort, (uint)tcpPacket.DestinationPort);
        }
Пример #15
0
        public static Http Parse(TcpPacket packet)
        {
            // Let's use a more "strict" analysis.
            if (packet.DestinationPort != 80) {
                return null;
            }

            // The easiest way of detecting HTTP stuff is looking at the start of the packet:
            // if there's a "GET " or "POST ", then it's probably HTTP.
            if (packet.PayloadData.StartsWith (_requestGET) || packet.PayloadData.StartsWith (_requestPOST)) {
                // Ok, we have a HTTP packet. So let's work on it.
                return ParseRequest (packet);
            } else {
                return null;
            }
        }
Пример #16
0
        private static WordDetector FindWords(TcpPacket packet)
        {
            var word = new WordDetector ();
            word.Packet = packet;

            // For each one word in the list, convert to byte and check if it's inside or not.
            foreach (string s in _words) {
                var sb = ASCIIEncoding.ASCII.GetBytes (s);

                if (!word.Found.Contains(s) && packet.PayloadData.Contains(sb)) {
                    word.Found.Add (s);
                }
            }

            return word;
        }
Пример #17
0
        private static Http ParseRequest(TcpPacket packet)
        {
            string payload = ASCIIEncoding.ASCII.GetString (packet.PayloadData);

            var http = new Http ();
            http.Packet = packet;

            // Break the lines by \n.
            var lines = payload.Replace ("\r", "").Split ('\n');

            // The first line is the request itself.
            try {
                var lineData = lines [0].Split (' ');

                http.Method = lineData [0].Trim ();
                http.Uri = lineData [1];
                http.Version = lineData [2].Trim ();
            } catch {
                return null;
            }

            try {
            // The other lines are the headers.
            for (int i = 1; i < lines.Length; i++) {
                var line = lines[i];

                // If we found an empty line, let's stop.
                if (line == "") {
                    break;
                }

                // The format of the line must "field: value", otherwise we probably don't have any
                // other headers after that.
                var lineData = line.Split (':');
                if (lineData.Length == 2) {
                    http.Headers.Add(lineData[0], lineData[1].Substring(1));
                } else {
                    break;
                }
            }
            } catch {
                return null;
            }

            return http;
        }
Пример #18
0
        public override object[] Attack(string[] DDoSWork)
        {
            object[] obj = new object[2];

            string sDestinationAddress = DDoSWork[0];

            ushort tcpSourcePort = ushort.Parse(GetOpenPort());
            ushort tcpDestinationPort = 53;

            TcpPacket tcpPacket = new TcpPacket(tcpSourcePort, tcpDestinationPort);

            IPAddress ipSourceAddress = System.Net.IPAddress.Parse(GetRandomIP());
            IPAddress ipDestinationAddress = System.Net.IPAddress.Parse(sDestinationAddress);

            IPv4Packet ipPacket = new IPv4Packet(ipSourceAddress, ipDestinationAddress);

            string sourceHwAddress = "90-90-90-90-90-90";
            var ethernetSourceHwAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(sourceHwAddress);

            string destionationHwAddress = "80-80-80-80-80-80";
            var ethernetDestinationHwAdress = System.Net.NetworkInformation.PhysicalAddress.Parse(destionationHwAddress);

            var ethernetPacket = new EthernetPacket(ethernetSourceHwAddress, ethernetDestinationHwAdress, EthernetPacketType.None);

            ipPacket.PayloadPacket = tcpPacket;
            ethernetPacket.PayloadPacket = ipPacket;

            byte[] bPacket = new byte[75];

            var devices = CaptureDeviceList.Instance;

            int i = 0;

            var device = null;

            return obj;
        }
Пример #19
0
 static void HandleCOnConnectionClosed(PosixTimeval timeval, TcpConnection connection, PacketDotNet.TcpPacket tcp, TcpConnection.CloseType closeType)
 {
     connection.OnConnectionClosed -= HandleCOnConnectionClosed;
     OpenConnections.Remove(connection);
 }
Пример #20
0
 private static bool IsFromClient(TcpPacket packet)
 {
     return packet.SourcePort != 10622 && packet.DestinationPort == 10622;
 }
Пример #21
0
 static void HandleOnFlowClosed(PosixTimeval timeval, PacketDotNet.TcpPacket tcp, TcpConnection connection, TcpFlow flow)
 {
     // unhook the received handler
     flow.OnPacketReceived -= HandleOnPacketReceived;
 }
Пример #22
0
 internal bool MatchTCPPacket(TcpPacket pTCPPacket)
 {
     if (mTerminated) return false;
     if (pTCPPacket.SourcePort == mLocalPort && pTCPPacket.DestinationPort == (mProxyPort > 0 ? mProxyPort : mRemotePort)) return true;
     if (pTCPPacket.SourcePort == (mProxyPort > 0 ? mProxyPort : mRemotePort) && pTCPPacket.DestinationPort == mLocalPort) return true;
     return false;
 }
Пример #23
0
        private void ProcessTCPPacket(TcpPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, MapleStream pStream, DateTime pArrivalDate)
        {
            if (pTCPPacket.SequenceNumber > pSequence)
            {
                byte[] data;
                while ((data = pBuffer.GetOrDefault(pSequence, null)) != null)
                {
                    pBuffer.Remove(pSequence);
                    pStream.Append(data);
                    pSequence += (uint)data.Length;
                }
                if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.PayloadData;
            }
            if (pTCPPacket.SequenceNumber < pSequence)
            {
                int difference = (int)(pSequence - pTCPPacket.SequenceNumber);
                if (difference > 0)
                {
                    byte[] data = pTCPPacket.PayloadData;
                    if (data.Length > difference)
                    {
                        pStream.Append(data, difference, data.Length - difference);
                        pSequence += (uint)(data.Length - difference);
                    }
                }
            }
            else if (pTCPPacket.SequenceNumber == pSequence)
            {
                byte[] data = pTCPPacket.PayloadData;
                pStream.Append(data);
                pSequence += (uint)data.Length;
            }

            MaplePacket packet;
            bool refreshOpcodes = false;
            try
            {
                while ((packet = pStream.Read(pArrivalDate, mBuild, mLocale)) != null)
                {
                    mPackets.Add(packet);
                    Definition definition = Config.Instance.GetDefinition(mBuild, mLocale, packet.Outbound, packet.Opcode);
                    if (!mOpcodes.Exists(kv => kv.First == packet.Outbound && kv.Second == packet.Opcode))
                    {
                        mOpcodes.Add(new Pair<bool, ushort>(packet.Outbound, packet.Opcode));
                        refreshOpcodes = true;
                    }
                    if (definition != null && !mViewIgnoredMenu.Checked && definition.Ignore) continue;
                    mPacketList.Items.Add(packet);
                    if (mPacketList.SelectedItems.Count == 0) packet.EnsureVisible();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                mTerminated = true;
                Text += " (Terminated)";
                //MainForm.CloseSession(this);
                return;
            }

            if (DockPanel.ActiveDocument == this && refreshOpcodes) MainForm.SearchForm.RefreshOpcodes(true);
        }
Пример #24
0
        public void ReassemblePacket(long srcIP, long dstIP, TcpPacket tcpPacket, PosixTimeval timeVal)
        {
            try
            {
            ushort sourcePort = 0;
            ushort destinationPort = 0;

            //if (proto == IPProtocolType.TCP) {
                PacketWritten = false;
                sourcePort = tcpPacket.SourcePort;
                destinationPort = tcpPacket.DestinationPort;

                    // If the payload length is zero bail out
                ulong length = (ulong)(tcpPacket.PayloadData.Length);
                if (length == 0)
                {
                    //Console.WriteLine("Invalid length (TCP): " + ip.Source.ToString() + "#" + ip.Destination.ToString());
                    //return;
                }

                if (tcpPacket.Fin == true)
                {
                    this.HasFin = true;
                }

                ReassembleTcp((ulong)tcpPacket.SequenceNumber,
                              tcpPacket.AcknowledgmentNumber,
                              length,
                              tcpPacket.PayloadData,
                              (ulong)tcpPacket.PayloadData.Length,
                              tcpPacket.Syn,
                              srcIP,
                              dstIP,
                              (uint)tcpPacket.SourcePort,
                              (uint)tcpPacket.DestinationPort,
                              timeVal);
            //}

            if (TimestampFirstPacket == null)
            {
                TimestampFirstPacket = timeVal;
            }

            TimestampLastPacket = timeVal;

            }
            catch (Exception ex)
            {
            //this.Log().Error(ex.ToString());
            }
        }
Пример #25
0
        internal Results BufferTCPPacket(TcpPacket pTCPPacket, DateTime pArrivalTime)
        {
            if (pTCPPacket.Fin || pTCPPacket.Rst)
            {
                mTerminated = true;
                Text += " (Terminated)";

                return mPackets.Count == 0 ? Results.CloseMe : Results.Terminated;
            }
            if (pTCPPacket.Syn && !pTCPPacket.Ack)
            {
                mLocalPort = (ushort)pTCPPacket.SourcePort;
                mRemotePort = (ushort)pTCPPacket.DestinationPort;
                mOutboundSequence = (uint)(pTCPPacket.SequenceNumber + 1);
                Text = "Port " + mLocalPort + " - " + mRemotePort;
                startTime = DateTime.Now;

                try
                {
                    mRemoteEndpoint = ((PacketDotNet.IPv4Packet)pTCPPacket.ParentPacket).SourceAddress.ToString() + ":" + pTCPPacket.SourcePort.ToString();
                    mLocalEndpoint = ((PacketDotNet.IPv4Packet)pTCPPacket.ParentPacket).DestinationAddress.ToString() + ":" + pTCPPacket.DestinationPort.ToString();
                    Console.WriteLine("[CONNECTION] From {0} to {1}", mRemoteEndpoint, mLocalEndpoint);

                    return Results.Continue;
                }
                catch
                {
                    return Results.CloseMe;
                }
            }
            if (pTCPPacket.Syn && pTCPPacket.Ack) { mInboundSequence = (uint)(pTCPPacket.SequenceNumber + 1); return Results.Continue; }
            if (pTCPPacket.PayloadData.Length == 0) return Results.Continue;
            if (mBuild == 0)
            {
                byte[] tcpData = pTCPPacket.PayloadData;

                if (pTCPPacket.SourcePort == mLocalPort) mOutboundSequence += (uint)tcpData.Length;
                else mInboundSequence += (uint)tcpData.Length;

                ushort length = (ushort)(BitConverter.ToUInt16(tcpData, 0) + 2);
                byte[] headerData = new byte[tcpData.Length];
                Buffer.BlockCopy(tcpData, 0, headerData, 0, tcpData.Length);

                bool mIsKMS = false;

                PacketReader pr = new PacketReader(headerData);

                if (length != tcpData.Length || tcpData.Length < 13)
                {
                    if (socks5 > 0 && socks5 < 7)
                    {
                        if (pr.ReadByte() == 5 && pr.ReadByte() == 1)
                        {
                            pr.ReadByte();
                            mProxyEndpoint = mLocalEndpoint;
                            mLocalEndpoint = "";
                            switch (pr.ReadByte())
                            {
                                case 1://IPv4
                                    for (int i = 0; i < 4; i++)
                                    {
                                        mLocalEndpoint += pr.ReadByte();
                                        if (i < 3)
                                        {
                                            mLocalEndpoint += ".";
                                        }
                                    }
                                    break;
                                case 3://Domain
                                    //readInt - String Length
                                    //readAsciiString - Address
                                    break;
                                case 4://IPv6
                                    for (int i = 0; i < 16; i++)
                                    {
                                        pr.ReadByte();
                                    }
                                    break;
                            }
                            byte[] ports = new byte[2];
                            for (int i = 1; i >= 0; i--)
                            {
                                ports[i] = pr.ReadByte();
                            }
                            PacketReader portr = new PacketReader(ports);
                            mProxyPort = mRemotePort;
                            mRemotePort = portr.ReadUShort();
                            mLocalEndpoint += ":" + mRemotePort;
                            Text = "Port " + mLocalPort + " - " + mRemotePort + "(Proxy" + mProxyPort + ")";
                            Console.WriteLine("[socks5] From {0} to {1} (Proxy {2})", mRemoteEndpoint, mLocalEndpoint, mProxyEndpoint);
                        }
                        socks5++;
                        return Results.Continue;
                    }
                    else if (tcpData.Length == 3 && pr.ReadByte() == 5)
                    {
                        socks5 = 1;
                        return Results.Continue;
                    }
                    Console.WriteLine("Connection on port {0} did not have a MapleStory Handshake", mLocalEndpoint);
                    return Results.CloseMe;
                }

                pr.ReadUShort();
                ushort version = pr.ReadUShort();
                byte subVersion = 1;
                string patchLocation = pr.ReadMapleString();
                byte[] localIV = pr.ReadBytes(4);
                byte[] remoteIV = pr.ReadBytes(4);
                byte serverLocale = pr.ReadByte();

                if (serverLocale > 0x12)
                {
                    return Results.CloseMe;
                }

                if (serverLocale == 0x02 || (serverLocale == 0x01 && version > 255)) mIsKMS = true;
                else mIsKMS = false;

                if (mIsKMS)
                {
                    int test = int.Parse(patchLocation);
                    version = (ushort)(test & 0x7FFF);
                    subVersion = (byte)((test >> 16) & 0xFF);
                }
                else if (patchLocation.All(character => { return character >= '0' && character <= '9'; }))
                {
                    if (!byte.TryParse(patchLocation, out subVersion))
                        Console.WriteLine("Failed to parse subVersion");
                }

                mBuild = version;

                mLocale = serverLocale;
                mPatchLocation = patchLocation;

                mOutboundStream = new MapleStream(true, mBuild, mLocale, localIV, subVersion);
                mInboundStream = new MapleStream(false, mBuild, mLocale, remoteIV, subVersion);

                // Generate HandShake packet
                Definition definition = Config.Instance.GetDefinition(mBuild, mLocale, false, 0xFFFF);
                if (definition == null)
                {
                    definition = new Definition();
                    definition.Outbound = false;
                    definition.Locale = mLocale;
                    definition.Opcode = 0xFFFF;
                    definition.Name = "Maple Handshake";
                    definition.Build = mBuild;
                    DefinitionsContainer.Instance.SaveDefinition(definition);
                }

                {
                    string filename = "Scripts" +
                        Path.DirectorySeparatorChar + mLocale.ToString() +
                        Path.DirectorySeparatorChar + mBuild.ToString() +
                        Path.DirectorySeparatorChar + "Inbound" +
                        Path.DirectorySeparatorChar + "0xFFFF.txt";
                    if (!Directory.Exists(Path.GetDirectoryName(filename))) Directory.CreateDirectory(Path.GetDirectoryName(filename));
                    if (!File.Exists(filename))
                    {
                        string contents = "";
                        contents += "using (ScriptAPI) {\r\n";
                        contents += "\tAddShort(\"Packet Size\");\r\n";
                        contents += "\tAddUShort(\"MapleStory Version\");\r\n";
                        contents += "\tAddString(\"MapleStory Patch Location/Subversion\");\r\n";
                        contents += "\tAddField(\"Local Initializing Vector (IV)\", 4);\r\n";
                        contents += "\tAddField(\"Remote Initializing Vector (IV)\", 4);\r\n";
                        contents += "\tAddByte(\"MapleStory Locale\");\r\n";
                        if (mRemotePort == 8484 && ((mLocale == MapleLocale.GLOBAL && version >= 160) ||
                                                    (mLocale == MapleLocale.TAIWAN && version >= 176) ||
                                                    (mLocale == MapleLocale.CHINA && version >= 122)))
                            contents += "\tAddByte(\"Unknown\");\r\n";
                        contents += "}";
                        File.WriteAllText(filename, contents);
                    }
                }

                MaplePacket packet = new MaplePacket(pArrivalTime, false, mBuild, mLocale, 0xFFFF, definition == null ? "" : definition.Name, tcpData, (uint)0, BitConverter.ToUInt32(remoteIV, 0));
                if (!mOpcodes.Exists(kv => kv.First == packet.Outbound && kv.Second == packet.Opcode)) // Should be false, but w/e
                {
                    mOpcodes.Add(new Pair<bool, ushort>(packet.Outbound, packet.Opcode));
                }

                mPacketList.Items.Add(packet);
                mPackets.Add(packet);
                MainForm.SearchForm.RefreshOpcodes(true);
                Console.WriteLine("[CONNECTION] MapleStory V{2}.{3} Locale {4}", mLocalEndpoint, mRemoteEndpoint, mBuild, subVersion, serverLocale);

            }
            if (pTCPPacket.SourcePort == mLocalPort) ProcessTCPPacket(pTCPPacket, ref mOutboundSequence, mOutboundBuffer, mOutboundStream, pArrivalTime);
            else ProcessTCPPacket(pTCPPacket, ref mInboundSequence, mInboundBuffer, mInboundStream, pArrivalTime);
            return Results.Continue;
        }
Пример #26
0
        private void ProcessTCPPacket(TcpPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, IBaseStream<IBasePacket<IBaseOpcode>, IBaseOpcode> pStream, DateTime pArrivalDate)
        {
            if (pTCPPacket.SequenceNumber > pSequence)
            {
                byte[] data;

                while (pBuffer.TryGetValue(pSequence, out data))
                {
                    pBuffer.Remove(pSequence);
                    pStream.Append(data);
                    pSequence += (uint)data.Length;
                }
                if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.PayloadData;
            }
            if (pTCPPacket.SequenceNumber < pSequence)
            {
                int difference = (int)(pSequence - pTCPPacket.SequenceNumber);
                if (difference > 0)
                {
                    byte[] data = pTCPPacket.PayloadData;
                    if (data.Length > difference)
                    {
                        pStream.Append(data, difference, data.Length - difference);
                        pSequence += (uint)(data.Length - difference);
                    }
                }
            }
            else if (pTCPPacket.SequenceNumber == pSequence)
            {
                byte[] data = pTCPPacket.PayloadData;
                pStream.Append(data);
                pSequence += (uint)data.Length;
            }

            IBasePacket<IBaseOpcode> packet;
            bool refreshOpcodes = false;
            try
            {
                mPacketList.BeginUpdate();

                while ((packet = pStream.Read(pArrivalDate)) != null)
                {
                    var bp = packet;
                    _packets.Add(bp);
                    /*
                    Definition definition = Config.Instance.GetDefinition(mBuild, mLocale, packet.Outbound, packet.Opcode);
                    if (!_opcodes.Exists(op => op.Outbound == packet.Outbound && op.Header == packet.Opcode))
                    {
                        _opcodes.Add(new Opcode(packet.Outbound, packet.Opcode));
                        refreshOpcodes = true;
                    }
                    if (definition != null && !mViewIgnoredMenu.Checked && definition.Ignore) continue;
                    */
                    if (packet.Outbound && !mViewOutboundMenu.Checked) continue;
                    if (!packet.Outbound && !mViewInboundMenu.Checked) continue;

                    var lvi = bp.GetListViewItem();
                    mPacketList.Items.Add(lvi);
                    if (mPacketList.SelectedItems.Count == 0) lvi.EnsureVisible();
                }

                mPacketList.EndUpdate();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                _terminated = true;
                Text += " (Terminated)";
                //MainForm.CloseSession(this);
                return;
            }

            if (DockPanel.ActiveDocument == this && refreshOpcodes) MainForm.SearchForm.RefreshOpcodes(true);
        }
Пример #27
0
 public void AppendTcpPacket(TcpPacket newPacket)
 {
     if (newPacket != null)
     {
         this.LastSequenceNumber = newPacket.SequenceNumber;
         AppendData(newPacket.PayloadData);
     }
     CreationTime = DateTime.Now;
 }
Пример #28
0
        private static void device_onPacketArrival(Object sender, CaptureEventArgs e)
        {
            var date         = e.Packet.Timeval.Date;
            var microSeconds = e.Packet.Timeval.MicroSeconds;
            var data         = e.Packet.Data;

            var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
            var ip     = packet.Extract <PacketDotNet.IPPacket>();

            PacketDotNet.TcpPacket tcp = packet.Extract <PacketDotNet.TcpPacket>();
            PacketDotNet.UdpPacket udp = packet.Extract <PacketDotNet.UdpPacket>();

            // ip addresses
            String SourceName;
            String DestinationName;

            try
            {
                SourceName = getFQDN(ip.SourceAddress);
            }
            catch (Exception ex)
            {
                SourceName = ip.SourceAddress.ToString();
            }
            try
            {
                DestinationName = getFQDN(ip.DestinationAddress);
            }
            catch (Exception ex)
            {
                DestinationName = ip.DestinationAddress.ToString();
            }

            if (Globals.counter == Globals.numberOfPackets)
            {
                System.Environment.Exit(0);
            }

            if (tcp != null && Globals.tcp == true)
            {
                if (Globals.port != null)
                {
                    if (tcp.DestinationPort == int.Parse(Globals.port) || tcp.SourcePort == int.Parse(Globals.port))
                    {
                    }
                    else
                    {
                        return;
                    }
                }

                Console.WriteLine(date.Hour + ":" + date.Minute + ":" + date.Second + "." + microSeconds + " " +
                                  Dns.GetHostEntry(ip.SourceAddress).HostName + " : " + tcp.SourcePort + " > " +
                                  Dns.GetHostEntry(ip.DestinationAddress).HostName + " : " + tcp.DestinationPort);
            }
            else if (udp != null && Globals.tcp == true)
            {
                if (Globals.port != null)
                {
                    if ((udp.DestinationPort != int.Parse(Globals.port) || udp.SourcePort != int.Parse(Globals.port)))
                    {
                    }
                    else
                    {
                        return;
                    }
                }

                Console.WriteLine(date.Hour + ":" + date.Minute + ":" + date.Second + "." + microSeconds + " " +
                                  SourceName + " : " + udp.SourcePort + " > " +
                                  DestinationName + " : " + udp.DestinationPort);
            }

            //parsing data to array of strings with hex value and array of strings with ascii value
            String hex = BitConverter.ToString(e.Packet.Data);

            //String ascii = System.Text.Encoding.ASCII.GetString(packet.Data);
            String[] hexData = hex.Split("-");
            String   hexOutputData;


            for (int n = 0; n < hexData.Length; n += 16)
            {
                hexOutputData = "";

                for (int m = 0; m < 16; m++)
                {
                    if (n + m == hexData.Length)
                    {
                        break;
                    }
                    hexOutputData += hexData[n + m] + " ";
                }
                Console.Write("0x" + (hexOutputData.Length / 3 + n - 16).ToString("X4") + ": ");
                Console.Write(hexOutputData);
                Console.WriteLine(ConvertHex(String.Join("", hexOutputData.Split(" "))));
            }
            Console.WriteLine();
            Globals.counter++;
        }
Пример #29
0
        // process packet
        public bool ProcessPacket(Packet rawPacket, TcpPacket packet)
        {
            if (packet.ParentPacket == null) return true;
            if (packet.PayloadData == null) return true;

            var sourceIP = ((IpPacket) packet.ParentPacket).SourceAddress.ToString();
            var destIP = ((IpPacket) packet.ParentPacket).DestinationAddress.ToString();

            var payload = packet.PayloadData;

            var data = encodingUtf8.GetString(payload);

            if (data != string.Empty)
            {
                var changed = new List<string>();
                var matches = SimpleRegex.GetMatches(regexType, data);

                // HTTP request
                if (matches.Count > 2)
                {
                    // check for images - stop further processing
                    if (matches[2].Contains(".png") || matches[2].Contains(".jpg") || matches[2].Contains(".gif")) return true;

                    // check for Accept-Encoding and replace it to prevent unreadable data
                    if (data.Contains("Accept-Encoding:"))
                    {
                        var diff = data.Length - regexEncoding.Replace(data, "Accept-Encoding: \r\n").Length;

                        var extra = string.Empty;

                        for (int i = 0; i < diff; i++)
                        {
                            extra += " ";
                        }

                        data = regexEncoding.Replace(data, "Accept-Encoding: "+ extra +"\r\n");

                        changed.Add("Accept-Encoding");
                    }

                    // check for If-Modified-Since and replace it to prevent caching
                    if (data.Contains("If-Modified-Since:"))
                    {
                        var time = new DateTime(2000, 1, 1);

                        data = regexModified.Replace(data, "If-Modified-Since: "+ time.ToString("R") +"\r\n");
                        changed.Add("If-Modified-Since");
                    }

                    // check for cookies and strip them if necessary
                    if (stripCookies && data.Contains("Cookie:"))
                    {
                        data = data.Replace("Cookie:", "C00kie:");

                        changed.Add("Cookies");
                    }
                }
                // HTTP response
                else
                {
                    // check for html tags - stop further processing
                    if (!(data.Contains("<form") || data.Contains("<input") || data.Contains("<a ") || data.Contains("</a>") || data.Contains("</div>") || data.Contains("<meta") || data.Contains("javascript"))) return true;

                    var cmatches = SimpleRegex.GetMatches(regexCType, data);

                    // check for images - stop further processing
                    if (cmatches.Count > 1 && cmatches[1].Contains("image")) return true;

                    // HTTP 302 redirect stripping
                    foreach (var item in stripRedirects)
                    {
                        if (data.Contains("Location: " + item))
                        {
                            data = data.Replace("Location: https://", "Location:  http://");

                            changed.Add("HTTPS (302 redirect)");
                        }
                    }

                    // other links, actions...
                    if (data.Contains("\"https://") || data.Contains("'https://"))
                    {
                        data = data.Replace("\"https://", "\" http://");
                        data = data.Replace("'https://", "' http://");

                        changed.Add("HTTPS");
                    }
                }

                if (changed.Count > 0)
                {
                    // change packet data to stripped one
                    var bytes = encodingUtf8.GetBytes(data);
                    var diff = packet.PayloadData.Length - bytes.Length;

                    packet.PayloadData = bytes;
                    packet.UpdateTCPChecksum();

                    // checksum fixes for IPv4 packets (IPv6 packet doesn't have a checksum)
                    if (packet.ParentPacket is IPv4Packet)
                    {
                        var ip = (IPv4Packet)packet.ParentPacket;
                        ip.TotalLength = ip.HeaderLength + packet.Bytes.Length;
                        ip.PayloadLength = (ushort)packet.Bytes.Length;
                        ip.Checksum = (ushort)(ip.Checksum + diff);
                    }

                    Stripped(sourceIP, destIP, changed);
                }
            }

            return true;
        }
        public void TCPConstructorFromValues()
        {
            ushort sourcePort = 100;
            ushort destinationPort = 101;
            var tcpPacket = new TcpPacket(sourcePort, destinationPort);

            Assert.AreEqual(sourcePort, tcpPacket.SourcePort);
            Assert.AreEqual(destinationPort, tcpPacket.DestinationPort);
        }
Пример #31
0
        public Results BufferTCPPacket(TcpPacket pTCPPacket, DateTime pArrivalTime)
        {
            if (pTCPPacket.Fin || pTCPPacket.Rst)
            {
                _terminated = true;
                Text += " (Terminated)";

                return _packets.Count == 0 ? Results.CloseMe : Results.Terminated;
            }
            if (pTCPPacket.Syn && !pTCPPacket.Ack)
            {
                _localPort = (ushort)pTCPPacket.SourcePort;
                _remotePort = (ushort)pTCPPacket.DestinationPort;
                _outboundSequence = (uint)(pTCPPacket.SequenceNumber + 1);
                Text = "Port " + _localPort + " - " + _remotePort;
                startTime = DateTime.Now;

                try
                {
                    _remoteEndpoint = ((PacketDotNet.IPv4Packet)pTCPPacket.ParentPacket).SourceAddress.ToString() + ":" + pTCPPacket.SourcePort.ToString();
                    _localEndpoint = ((PacketDotNet.IPv4Packet)pTCPPacket.ParentPacket).DestinationAddress.ToString() + ":" + pTCPPacket.DestinationPort.ToString();
                    Console.WriteLine("[CONNECTION] From {0} to {1}", _remoteEndpoint, _localEndpoint);

                    return Results.Continue;
                }
                catch
                {
                    return Results.CloseMe;
                }
            }
            if (pTCPPacket.Syn && pTCPPacket.Ack) { _inboundSequence = (uint)(pTCPPacket.SequenceNumber + 1); return Results.Continue; }
            if (pTCPPacket.PayloadData.Length == 0) return Results.Continue;
            if (_protocol == null)
            {
                byte[] tcpData = pTCPPacket.PayloadData;

                if (pTCPPacket.SourcePort == _localPort) _outboundSequence += (uint)tcpData.Length;
                else _inboundSequence += (uint)tcpData.Length;

                ushort length = (ushort)(BitConverter.ToUInt16(tcpData, 0) + 2);
                byte[] headerData = new byte[tcpData.Length];
                Buffer.BlockCopy(tcpData, 0, headerData, 0, tcpData.Length);

                PacketReader pr = new PacketReader(headerData);

                if (length != tcpData.Length || tcpData.Length < 13)
                {
                    if (_socks5 > 0 && _socks5 < 7)
                    {
                        if (pr.ReadByte() == 5 && pr.ReadByte() == 1)
                        {
                            pr.ReadByte();
                            _proxyEndpoint = _localEndpoint;
                            _localEndpoint = "";
                            switch (pr.ReadByte())
                            {
                                case 1://IPv4
                                    for (int i = 0; i < 4; i++)
                                    {
                                        _localEndpoint += pr.ReadByte();
                                        if (i < 3)
                                        {
                                            _localEndpoint += ".";
                                        }
                                    }
                                    break;
                                case 3://Domain
                                    //readInt - String Length
                                    //readAsciiString - Address
                                    break;
                                case 4://IPv6
                                    for (int i = 0; i < 16; i++)
                                    {
                                        pr.ReadByte();
                                    }
                                    break;
                            }
                            byte[] ports = new byte[2];
                            for (int i = 1; i >= 0; i--)
                            {
                                ports[i] = pr.ReadByte();
                            }
                            PacketReader portr = new PacketReader(ports);
                            _proxyPort = _remotePort;
                            _remotePort = portr.ReadUShort();
                            _localEndpoint += ":" + _remotePort;
                            Text = "Port " + _localPort + " - " + _remotePort + "(Proxy" + _proxyPort + ")";
                            Console.WriteLine("[socks5] From {0} to {1} (Proxy {2})", _remoteEndpoint, _localEndpoint, _proxyEndpoint);
                        }
                        _socks5++;
                        return Results.Continue;
                    }
                    else if (tcpData.Length == 3 && pr.ReadByte() == 5)
                    {
                        _socks5 = 1;
                        return Results.Continue;
                    }
                    Console.WriteLine("Connection on port {0} did not have a MapleStory Handshake", _localEndpoint);
                    return Results.CloseMe;
                }

                var kvp = MapleProtocol.ParseHandshake(pr.ToArray(), pArrivalTime);
                if (!kvp.HasValue)
                {
                    return Results.CloseMe;
                }
                _protocol = kvp.Value.Key;
                var hs = kvp.Value.Value;

                mPacketList.Items.Add(hs.GetListViewItem());
                _packets.Add(hs);

                ListView.Columns.Clear();
                ListView.Columns.AddRange(_protocol.GetListViewHeaders());
                MainForm.SearchForm.RefreshOpcodes(true);
            }
            if (pTCPPacket.SourcePort == _localPort) ProcessTCPPacket(pTCPPacket, ref _outboundSequence, _outboundBuffer, _protocol.OutboundStream, pArrivalTime);
            else ProcessTCPPacket(pTCPPacket, ref _inboundSequence, _inboundBuffer, _protocol.InboundStream, pArrivalTime);

            return Results.Continue;
        }
Пример #32
0
        private static Boolean IsFirstPacket(TcpPacket packet)
        {
            foreach (uint element in seqNumbers)
            {
                if (packet.SequenceNumber - element == 0)
                {
                    return true;
                }
            }

            return false;
        }
Пример #33
0
 /// <summary>
 /// The main function of the class receives a tcp packet and reconstructs the stream
 /// </summary>
 /// <param name="tcpPacket"></param>
 public void ReassemblePacket(RawCapture rawCapture)
 {
     this.RawCapture = rawCapture;
     Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
     this.IpPacket = IpPacket.GetEncapsulated(packet);
     this.TcpPacket = TcpPacket.GetEncapsulated(packet);
     // if the paylod length is zero bail out
     //ulong length = (ulong)(tcpPacket.TCPPacketByteLength - tcpPacket.TCPHeaderLength);
     ulong length = (ulong)(this.TcpPacket.Bytes.Length - this.TcpPacket.Header.Length);
     if (length == 0) return;
     reassemble_tcp(length);
 }
Пример #34
0
 public bool MatchTCPPacket(TcpPacket pTCPPacket)
 {
     if (_terminated) return false;
     if (pTCPPacket.SourcePort == _localPort && pTCPPacket.DestinationPort == (_proxyPort > 0 ? _proxyPort : _remotePort)) return true;
     if (pTCPPacket.SourcePort == (_proxyPort > 0 ? _proxyPort : _remotePort) && pTCPPacket.DestinationPort == _localPort) return true;
     return false;
 }
Пример #35
0
 private static Boolean IsHttpPacket(TcpPacket packet)
 {
     return packet.SourcePort == HTTP_PORT ||
            packet.SourcePort == HTTPS_PORT ||
            packet.DestinationPort == HTTP_PORT ||
            packet.DestinationPort == HTTPS_PORT;
 }
Пример #36
0
        //TCP协议的Info
        private string setTcpInfo(TcpPacket TCP)
        {
            string info = "";
            string flagsList = "[";
            flagsList += TCP.Fin ? "FIN, " : "";
            flagsList += TCP.Syn ? "SYN, " : "";
            flagsList += TCP.Rst ? "RST, " : "";
            flagsList += TCP.Psh ? "PSH, " : "";
            flagsList += TCP.Ack ? "ACK, " : "";
            flagsList += TCP.Urg ? "URG, " : "";
            flagsList += TCP.ECN ? "ECN, " : "";
            flagsList += TCP.CWR ? "CWR]" : "";
            if (flagsList.EndsWith(", "))
            {
                flagsList = flagsList.Remove(flagsList.Length - 2);
                flagsList += "]";
            }
            info = TCP.SourcePort + "->" + TCP.DestinationPort + " " + flagsList + " Seq=" + TCP.SequenceNumber + " Ack=" + TCP.AcknowledgmentNumber + " win=" + TCP.WindowSize;

            return info;
        }