Ejemplo n.º 1
0
        private static bool readNetworkHeaders(BinaryReader binaryReader)
        {
            EthernetHeader ethernetHeader = EthernetHeader.read(binaryReader);

            // Skip non-IP packets
            if (ethernetHeader.proto != 8)
            {
                throw new InvalidDataException();
            }

            IpHeader ipHeader = IpHeader.read(binaryReader);

            // Skip non-UDP packets
            if (ipHeader.proto != 17)
            {
                throw new InvalidDataException();
            }

            UdpHeader udpHeader = UdpHeader.read(binaryReader);

            bool isSend = (udpHeader.dPort >= 9000 && udpHeader.dPort <= 9013);
            bool isRecv = (udpHeader.sPort >= 9000 && udpHeader.sPort <= 9013);

            // Skip non-AC-port packets
            if (!isSend && !isRecv)
            {
                throw new InvalidDataException();
            }

            return(isSend);
        }
Ejemplo n.º 2
0
    public static EthernetHeader read(BinaryReader binaryReader)
    {
        EthernetHeader newObj = new EthernetHeader();

        newObj.dest   = binaryReader.ReadBytes(6);
        newObj.source = binaryReader.ReadBytes(6);
        newObj.proto  = binaryReader.ReadUInt16();
        return(newObj);
    }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            var pcap = new Pcap();

            pcap.Open(ConfigurationManager.AppSettings["Adapter"]);

            var address = IPAddress.Parse(ConfigurationManager.AppSettings["Address"]);
            var port    = UInt16.Parse(ConfigurationManager.AppSettings["Port"]);

            Packet packet = null;

            long tx = 0, rx = 0;

            while (true)
            {
                if ((packet = pcap.Next()) != null)
                {
                    var eth = new EthernetHeader(packet.Data);
                    if (eth.Protocol == (int)EthernetProtocol.IP)
                    {
                        var ip = new IPHeader(eth);
                        if (ip.Protocol == IPProtocol.Tcp)
                        {
                            var tcp = new TcpHeader(ip);
                            if (ip.SourceIp.Equals(address) && tcp.SourcePort == port)
                            {
                                rx += tcp.Length;
                            }
                            else if (ip.DestinationIp.Equals(address) && tcp.DestinationPort == port)
                            {
                                tx += tcp.Length;
                            }
                        }
                    }
                }

                if (KeyPressed())
                {
                    Console.WriteLine("{0},{1}", tx, rx);
                    tx = 0;
                    rx = 0;
                }
            }
        }
Ejemplo n.º 4
0
                public void run()
                {
                    while (true)
                    {
                        try {
                            Packet         packet     = packetList.take();
                            EthernetPacket packet_eth = (EthernetPacket)packet;
                            EthernetHeader head_eth   = packet_eth.getHeader();

                            IpV4Packet ipV4Packet = null;
                            if (ppp)
                            {
                                ipV4Packet = getIpV4Packet_pppoe(packet_eth);
                            }
                            else
                            {
                                if (packet_eth.getPayload() instanceof IpV4Packet)
                                {
                                    ipV4Packet = (IpV4Packet)packet_eth.getPayload();
                                }
                            }
                            if (ipV4Packet != null)
                            {
                                IpV4Header ipV4Header = ipV4Packet.getHeader();
                                if (ipV4Packet.getPayload() instanceof TcpPacket)
                                {
                                    TcpPacket tcpPacket = (TcpPacket)ipV4Packet.getPayload();
                                    TcpHeader tcpHeader = tcpPacket.getHeader();
                                    if (client)
                                    {
                                        TCPTun conn = tcpManager.getTcpConnection_Client(ipV4Header.getSrcAddr().getHostAddress(), tcpHeader.getSrcPort().value(), tcpHeader.getDstPort().value());
                                        if (conn != null)
                                        {
                                            conn.process_client(capEnv, packet, head_eth, ipV4Header, tcpPacket, false);
                                        }
                                    }
                                    else
                                    {
                                        TCPTun conn = null; conn = tcpManager.getTcpConnection_Server(ipV4Header.getSrcAddr().getHostAddress(), tcpHeader.getSrcPort().value());
                                        if (
                                            tcpHeader.getDstPort().value() == listenPort)
                                        {
                                            if (tcpHeader.getSyn() && !tcpHeader.getAck() && conn == null)
                                            {
                                                conn = new TCPTun(capEnv, ipV4Header.getSrcAddr(), tcpHeader.getSrcPort().value());
                                                tcpManager.addConnection_Server(conn);
                                            }
                                            conn = tcpManager.getTcpConnection_Server(ipV4Header.getSrcAddr().getHostAddress(), tcpHeader.getSrcPort().value());
                                            if (conn != null)
                                            {
                                                conn.process_server(packet, head_eth, ipV4Header, tcpPacket, true);
                                            }
                                        }
                                    }
                                }
                                else if (packet_eth.getPayload() instanceof IllegalPacket)
                                {
                                    MLog.println("IllegalPacket!!!");
                                }
                            }
                        } catch (InterruptedException e) {
Ejemplo n.º 5
0
        public void ParseNetworkPacket(PacketRawInfo args)
        {
            IPHeader           ipHeader          = null;
            IPv6Header         ipv6Header        = null;
            EthernetHeader     ethernetHeader    = null;
            EthernetPacketType ethernetPackeType = EthernetPacketType.IpV4;

            PacketInfo packetInfo = new PacketInfo();

            packetInfo.protocolE = PacketType.UNKNOWN;
            packetInfo.count     = 1;

            if (args.linkLayer == LinkLayers.Ethernet)
            {
                ethernetHeader = new EthernetHeader(args.data, args.size);

                ethernetPackeType             = ethernetHeader.EtherType;
                packetInfo.hardwareSource     = ethernetHeader.SourceMac;
                packetInfo.harwareDestination = ethernetHeader.DestinationMac;
                packetInfo.protocol           = ((Protocol)ethernetHeader.EtherType).ToString();
                if (ethernetHeader.EtherType == EthernetPacketType.IpV4)
                {
                    args.data = ethernetHeader.Payload;
                    args.size = ethernetHeader.Payload.Length;
                }
            }
            else
            {
                packetInfo.protocol = Protocol.Iplt.ToString();
            }
            switch (ethernetPackeType)
            {
            case EthernetPacketType.IpV4:
                ipHeader = new IPHeader(args.data, args.size);
                packetInfo.ipDestination = ipHeader.DestinationAddress.ToString();
                packetInfo.ipSource      = ipHeader.SourceAddress.ToString();
                packetInfo.size          = ipHeader.MessageLength;
                if (packetInfo.ipSource == incomingIP)
                {
                    packetInfo.incoming = true;
                }
                Statistics.AddToIPPacketsStats(packetInfo.size, packetInfo.incoming);
                break;

            case EthernetPacketType.IpV6:
                ipv6Header = new IPv6Header(args.data, args.size);
                packetInfo.ipDestination = ipv6Header.DestinationAddress.ToString();
                packetInfo.ipSource      = ipv6Header.SourceAddress.ToString();
                if (packetInfo.ipSource == incomingIP)
                {
                    packetInfo.incoming = true;
                }
                Statistics.AddToIPPacketsStats(packetInfo.size, packetInfo.incoming);
                break;

            case EthernetPacketType.Arp:
                ARPHeader arpHeader = new ARPHeader(ethernetHeader.Payload, ethernetHeader.Payload.Length);
                packetInfo.ipDestination = arpHeader.TPA;
                packetInfo.ipSource      = arpHeader.SPA;
                packetInfo.desription    = arpHeader.Description;
                if (packetInfo.ipSource == incomingIP)
                {
                    packetInfo.incoming = true;
                }
                packetInfo.size      = arpHeader.Size;
                packetInfo.protocol  = "ARP";
                packetInfo.protocolE = PacketType.ARP;
                Statistics.AddToARPPacketsStats(packetInfo.size, packetInfo.incoming);
                break;

            case EthernetPacketType.WakeOnLan:

                break;

            default:
                packetInfo.desription = "неизвестный Ethernet протокол";
                break;
            }

            if (ipHeader != null)
            {
                switch (ipHeader.ProtocolType)
                {
                case Protocol.Udp:
                    NetworkShow.Network.Packets.UDPHeader udpheader = new UDPHeader(ipHeader.Data, ipHeader.Data.Length);
                    packetInfo.portDestination = udpheader.DestinationPort;
                    packetInfo.portSource      = udpheader.SourcePort;
                    packetInfo.size            = udpheader.Length;
                    packetInfo.protocol        = "UDP";
                    packetInfo.protocolE       = PacketType.UDP;
                    packetInfo.active          = "T";
                    Statistics.AddToUDPPacketsStats(packetInfo.size, packetInfo.incoming);
                    break;

                case Protocol.Tcp:
                    NetworkShow.Network.Packets.TCPHeader tcpheader = new TCPHeader(ipHeader.Data, ipHeader.Data.Length);
                    packetInfo.portDestination = tcpheader.DestinationPort;
                    packetInfo.portSource      = tcpheader.SourcePort;
                    packetInfo.size            = tcpheader.MessageLength + tcpheader.HeaderLength;
                    packetInfo.active          = "T";
                    packetInfo.protocol        = "TCP";
                    packetInfo.protocolE       = PacketType.TCP;
                    Statistics.AddToTCPPacketsStats(packetInfo.size, packetInfo.incoming);
                    break;

                case Protocol.InternetControlMessageProtocol:
                    NetworkShow.Network.Packets.ICMPHeader icmpheader = new ICMPHeader(ipHeader.Data, ipHeader.Data.Length);
                    packetInfo.desription = icmpheader.Type.ToString();
                    packetInfo.size       = icmpheader.Size;
                    packetInfo.protocol   = "ICMP";
                    packetInfo.protocolE  = PacketType.ICMP;
                    Statistics.AddToICMPPacketsStats(packetInfo.size, packetInfo.incoming);
                    break;

                case Protocol.InternetGroupManagementProtocol:
                    NetworkShow.Network.Packets.IGMPHeader igmpheader = new IGMPHeader(ipHeader.Data, ipHeader.Data.Length);
                    packetInfo.desription = igmpheader.GroupAddress + " " + igmpheader.Type + " " + igmpheader.Version;
                    packetInfo.size       = igmpheader.Size;
                    packetInfo.protocol   = "IGMP";
                    packetInfo.protocolE  = PacketType.IGMP;
                    Statistics.AddToIGMPPacketsStats(packetInfo.size, packetInfo.incoming);
                    break;

                default:
                    packetInfo.desription = "неизвестный IP протокол";
                    packetInfo.protocol   = ipHeader.ProtocolType.ToString();
                    packetInfo.protocolE  = PacketType.UNKNOWN;
                    packetInfo.size       = ipHeader.MessageLength;
                    break;
                }
            }
            //PacketsInfo.AddToQueue(packetInfo);
            int pos = -1;

            if ((packetInfo.protocol == "TCP") || (packetInfo.protocol == "UDP"))
            {
                //pos = FindConnection(packetInfo);
                pos = FindConnection(packetInfo);
                if (pos >= 0)
                {
                    packetInfo = UpdateConnection(pos, packetInfo);
                    UpdateInfoEvent(packetInfo.protocol);
                    db.UpdateConnection(packetInfo.pos, packetInfo);
                }
                else
                {
                    packetInfo.pos = db.SaveNewPacket(packetInfo);
                    AddConnection(packetInfo);
                    ChangeRowsCountEvent(packetInfo.protocolE, packetInfo.pos, packetInfo.portSource, packetInfo.portSource);
                }
            }
            else
            {
                int position = db.SaveNewPacket(packetInfo);
                ChangeRowsCountEvent(packetInfo.protocolE, position, packetInfo.portSource, packetInfo.portSource);
            }
        }
Ejemplo n.º 6
0
        public void Execute()
        {
            Packet         packet;
            EthernetHeader eth;
            IPHeader       ip;

            Flow      key = new Flow();
            FlowStats stats;

            try {
                //BinaryReader log = new BinaryReader(new FileStream(@"c:\users\gavin\desktop\20081006.dat", FileMode.Open, FileAccess.Read));
                while (!terminated)
                {
                    try {
                        /*packet = new Packet();
                         * packet.Time = log.ReadInt64();
                         * packet.Length = log.ReadInt32();
                         * packet.Data = log.ReadBytes(log.ReadInt32());*/
                        packet = pcap.Next();
                    } catch (Exception e) {
                        packet = null;
                        throw;
                    }
                    if (packet != null)
                    {
                        if (dump != null)
                        {
                            dump.Write(packet.Time);
                            dump.Write(packet.Length);
                            int i = Math.Min(packet.Data.Length, 64);
                            dump.Write(i);
                            dump.Write(packet.Data, 0, i);
                            dump.Flush();
                        }

                        eth = new EthernetHeader(packet.Data);

                        if (eth.Protocol == (int)EthernetProtocol.IP)
                        {
                            ip = new IPHeader(eth);
                            if (ip.Protocol == IPProtocol.Tcp)
                            {
                                TcpHeader tcp = new TcpHeader(ip);
                                key = new Flow(ip, tcp);

                                stats = tracker.Resolve(key, packet.Time);

                                stats.Last = packet.Time;
                                stats.Packets++;
                                // Bytes at IP, including IP header
                                stats.Bytes += ip.Length;

                                #region debugging

                                /*
                                 * // TODO: Verify sorted order of queue - should be right now
                                 * FlowStats check = queue.Head;
                                 * while (check != null) {
                                 * if (check.Next != null) Debug.Assert(check.Last >= check.Next.Last);
                                 * check = check.Next;
                                 * }
                                 */
                                #endregion
                            }
                            else if (ip.Protocol == IPProtocol.Udp)
                            {
                                try {
                                    UdpHeader udp = new UdpHeader(ip);
                                    key = new Flow(ip, udp);

                                    stats = tracker.Resolve(key, packet.Time);

                                    stats.Last = packet.Time;
                                    stats.Packets++;
                                    // Bytes at IP, including IP header
                                    stats.Bytes += ip.Length;
                                } catch (IndexOutOfRangeException e) {
                                    using (StreamWriter errorLog = new StreamWriter(Path.Combine(LogFolder, "error.log"), true)) {
                                        errorLog.WriteLine(DateTime.Now);
                                        errorLog.WriteLine(e.Message);
                                        errorLog.WriteLine(e.StackTrace);
                                        errorLog.WriteLine();
                                    }

                                    if (dump != null)
                                    {
                                        dump.Write(packet.Time);
                                        dump.Write(packet.Length);
                                        dump.Write(packet.Data.Length);
                                        dump.Write(packet.Data, 0, packet.Data.Length);
                                        dump.Flush();
                                    }
                                } catch (Exception ex) {
                                }
                            }
                            else if (ip.Protocol == IPProtocol.Icmp)
                            {
                                // TODO: Deal with ICMP
                            }
                            else if (ip.Protocol == IPProtocol.Gre)
                            {
                                // TODO: Deal with GRE
                            }
                        }
                        else
                        {
                            // TODO: deal with non-IP
                        }

                        #region Age flows
                        /**/
                        while (tracker.Count > 0 && tracker.Tail.Last < packet.Time - ExpiryInterval)
                        {
                            stats = tracker.Tail;
                            Dump(stats);
                            tracker.Remove(stats);
                        }
                        writer.Flush();
                        /**/
                        #endregion
                    }
                    packets++;
                }
            } catch (EndOfStreamException e) {
                // TODO: nothing
            } catch (Exception e) {
                //debug.WriteLine("ERROR: " + e.Message);
                //debug.Flush();
                throw e;
            }
        }
Ejemplo n.º 7
0
        private int readPacketRecordData(BinaryReader binaryReader, long len, uint tsSec, long curPacket, bool dontList)
        {
            // Begin reading headers
            long packetStartPos = binaryReader.BaseStream.Position;

            EthernetHeader ethernetHeader = EthernetHeader.read(binaryReader);

            // Skip non-IP packets
            if (ethernetHeader.proto != 8)
            {
                binaryReader.BaseStream.Position += len - (binaryReader.BaseStream.Position - packetStartPos);
                return(1);
            }

            IpHeader ipHeader = IpHeader.read(binaryReader);

            // Skip non-UDP packets
            if (ipHeader.proto != 17)
            {
                binaryReader.BaseStream.Position += len - (binaryReader.BaseStream.Position - packetStartPos);
                return(1);
            }

            UdpHeader udpHeader = UdpHeader.read(binaryReader);

            bool isSend = (udpHeader.dPort >= 9000 && udpHeader.dPort <= 9013);
            bool isRecv = (udpHeader.sPort >= 9000 && udpHeader.sPort <= 9013);

            // Skip non-AC-port packets
            if (!isSend && !isRecv)
            {
                binaryReader.BaseStream.Position += len - (binaryReader.BaseStream.Position - packetStartPos);
                return(1);
            }

            long headersSize = binaryReader.BaseStream.Position - packetStartPos;

            // Begin reading non-header packet content
            StringBuilder packetHeadersStr = new StringBuilder();
            StringBuilder packetTypeStr    = new StringBuilder();

            PacketRecord packet = new PacketRecord();

            packet.index     = records.Count;
            packet.isSend    = isSend;
            packet.tsSec     = tsSec;
            packet.netPacket = new NetPacket();
            packet.data      = binaryReader.ReadBytes((int)(len - headersSize));
            packet.extraInfo = "";
            BinaryReader packetReader = new BinaryReader(new MemoryStream(packet.data));

            try {
                ProtoHeader pHeader = ProtoHeader.read(packetReader);

                readOptionalHeaders(packet, pHeader.header_, packetHeadersStr, packetReader);

                if (packetReader.BaseStream.Position == packetReader.BaseStream.Length)
                {
                    packetTypeStr.Append("<Header Only>");
                }

                uint HAS_FRAGS_MASK = 0x4; // See SharedNet::SplitPacketData
                if ((pHeader.header_ & HAS_FRAGS_MASK) != 0)
                {
                    bool first = true;
                    while (packetReader.BaseStream.Position != packetReader.BaseStream.Length)
                    {
                        if (!first)
                        {
                            packetTypeStr.Append(" + ");
                        }
                        readPacket(packet, packetTypeStr, packetReader);
                        first = false;
                    }
                }

                if (packetReader.BaseStream.Position != packetReader.BaseStream.Length)
                {
                    packet.extraInfo = "Didnt read entire packet! " + packet.extraInfo;
                }
            } catch (OutOfMemoryException e) {
                //MessageBox.Show("Out of memory (packet " + curPacket + "), stopping read: " + e);
                return(2);
            } catch (Exception e) {
                packet.extraInfo += "EXCEPTION: " + e.Message + " " + e.StackTrace;
            }
            packet.packetHeadersStr = packetHeadersStr.ToString();
            packet.packetTypeStr    = packetTypeStr.ToString();

            records.Add(packet);

            if (!dontList)
            {
                ListViewItem newItem = new ListViewItem(packet.index.ToString());
                newItem.SubItems.Add(packet.isSend ? "Send" : "Recv");
                newItem.SubItems.Add(packet.tsSec.ToString());
                newItem.SubItems.Add(packet.packetHeadersStr);
                newItem.SubItems.Add(packet.packetTypeStr);
                newItem.SubItems.Add(packet.data.Length.ToString());
                newItem.SubItems.Add(packet.extraInfo);
                listItems.Add(newItem);
            }

            return(0);
        }