Exemplo n.º 1
0
        internal static PacketOrByteArraySegment ParseEncapsulatedBytes(ByteArraySegment Header, IPProtocolType ProtocolType, PosixTimeval Timeval, Packet ParentPacket)
        {
            ByteArraySegment         segment  = Header.EncapsulatedBytes();
            PacketOrByteArraySegment segment2 = new PacketOrByteArraySegment();
            IPProtocolType           type     = ProtocolType;

            if (type == IPProtocolType.ICMP)
            {
                segment2.ThePacket = new ICMPv4Packet(segment.Bytes, segment.Offset, Timeval);
                return(segment2);
            }
            if (type != IPProtocolType.TCP)
            {
                if (type == IPProtocolType.UDP)
                {
                    segment2.ThePacket = new UdpPacket(segment.Bytes, segment.Offset, Timeval, ParentPacket);
                    return(segment2);
                }
                if (type == IPProtocolType.ICMPV6)
                {
                    segment2.ThePacket = new ICMPv6Packet(segment.Bytes, segment.Offset, Timeval);
                    return(segment2);
                }
                segment2.TheByteArraySegment = segment;
                return(segment2);
            }
            segment2.ThePacket = new TcpPacket(segment.Bytes, segment.Offset, Timeval, ParentPacket);
            return(segment2);
        }
Exemplo n.º 2
0
        public L7Conversation(IPEndPoint sourceEndPoint,
                              IPEndPoint destinationEndPoint,
                              IPProtocolType protocolType,
                              L7Flow upL7Flow,
                              L7Flow downL7Flow,
                              Int32 conversationSegmentNum    = 0,
                              Boolean lastConversationSegment = true)
        {
            this.SourceEndPoint      = sourceEndPoint;
            this.DestinationEndPoint = destinationEndPoint;
            this.ProtocolType        = protocolType;

            this.LastConversationSegment = lastConversationSegment;
            this.ConversationSegmentNum  = conversationSegmentNum;

            this.UpPdus   = upL7Flow?.L7Pdus ?? NoPdusPlaceholder;
            this.DownPdus = downL7Flow?.L7Pdus ?? NoPdusPlaceholder;

            this.FirstSeenTicks = Math.Min(upL7Flow?.FirstSeenTicks ?? Int64.MaxValue, downL7Flow?.FirstSeenTicks ?? Int64.MaxValue);
            // Handle case where both timestamps are missing
            if (this.FirstSeenTicks == Int64.MaxValue)
            {
                this.FirstSeenTicks = 0;
            }

            this.LastSeenTicks = Math.Max(upL7Flow?.LastSeenTicks ?? 0, downL7Flow?.LastSeenTicks ?? 0);
        }
Exemplo n.º 3
0
        private static Boolean ParseTransportLayer(ReadOnlySpan <Byte> transportData,
                                                   IPProtocolType ipProtocol,
                                                   out UInt16 sourcePort,
                                                   out UInt16 destinationPort)
        {
            sourcePort      = 0;
            destinationPort = 0;

            if (transportData.Length < 8)
            {
                return(false);
            }

            switch (ipProtocol)
            {
            case IPProtocolType.UDP:
                sourcePort      = BinaryPrimitives.ReadUInt16BigEndian(transportData.Slice(UdpFields.SourcePortPosition, 2));
                destinationPort = BinaryPrimitives.ReadUInt16BigEndian(transportData.Slice(UdpFields.DestinationPortPosition, 2));
                return(true);

            case IPProtocolType.TCP:
                sourcePort      = BinaryPrimitives.ReadUInt16BigEndian(transportData.Slice(TcpFields.SourcePortPosition, 2));
                destinationPort = BinaryPrimitives.ReadUInt16BigEndian(transportData.Slice(TcpFields.DestinationPortPosition, 2));
                return(true);

            default:
                return(false);
            }
        }
Exemplo n.º 4
0
 public IPFragmentKey(IPAddress sourceAddress, IPAddress destinationAddress, IPProtocolType protocol, Int32 ipIdentification)
 {
     this.SourceAddress      = sourceAddress;
     this.DestinationAddress = destinationAddress;
     this.Protocol           = protocol;
     this.IPIdentification   = ipIdentification;
 }
Exemplo n.º 5
0
        public L7Conversation(IPEndPoint sourceEndPoint,
                              IPEndPoint destinationEndPoint,
                              IPProtocolType protocolType,
                              L7Flow upL7Flow,
                              L7Flow downL7Flow)
        {
            this.SourceEndPoint      = sourceEndPoint;
            this.DestinationEndPoint = destinationEndPoint;
            this.ProtocolType        = protocolType;

            this._upPdus   = upL7Flow?.L7Pdus ?? NoPdusPlaceholder;
            this._downPdus = downL7Flow?.L7Pdus ?? NoPdusPlaceholder;
            this._pdus     = new LazilyMergedCollection <L7Pdu>(this._upPdus, this._downPdus);

            this.UpNonDataFrames   = upL7Flow?.NonDataFrames ?? NoFramesPlaceholder;
            this.DownNonDataFrames = downL7Flow?.NonDataFrames ?? NoFramesPlaceholder;
            this.NonDataFrames     = new LazilyMergedCollection <Frame>(this.UpNonDataFrames, this.DownNonDataFrames);

            this.FirstSeenTicks = Math.Min(upL7Flow?.FirstSeenTicks ?? Int64.MaxValue, downL7Flow?.FirstSeenTicks ?? Int64.MaxValue);
            // Handle case where both timestamps are missing
            if (this.FirstSeenTicks == Int64.MaxValue)
            {
                this.FirstSeenTicks = 0;
            }

            this.LastSeenTicks = Math.Max(upL7Flow?.LastSeenTicks ?? 0, downL7Flow?.LastSeenTicks ?? 0);
        }
Exemplo n.º 6
0
        private static Boolean ParseNetworkLayer(ReadOnlySpan <Byte> networkData,
                                                 EthernetPacketType ethernetProtocol,
                                                 out ReadOnlySpan <Byte> transportData,
                                                 out IPProtocolType ipProtocol,
                                                 out IPAddress sourceIpAddress,
                                                 out IPAddress destinationIpAddress,
                                                 out IPFragmentSignature ipv4FragmentSignature)
        {
            transportData         = ReadOnlySpan <Byte> .Empty;
            ipProtocol            = IPProtocolType.NONE;
            sourceIpAddress       = IPAddress.None;
            destinationIpAddress  = IPAddress.None;
            ipv4FragmentSignature = null;

            switch (ethernetProtocol)
            {
            case EthernetPacketType.IPv4:
                return(ParseNetworkIpv4Layer(networkData, ref transportData, ref ipProtocol, ref sourceIpAddress, ref destinationIpAddress, ref ipv4FragmentSignature));

            case EthernetPacketType.IPv6:
                return(ParseNetworkIpv6Layer(networkData, ref transportData, ref ipProtocol, ref sourceIpAddress, ref destinationIpAddress));

            default:
                return(false);
            }
        }
Exemplo n.º 7
0
        public void AddData(IPProtocolType protocolType, int _PkSize)
        {
            //若是后续到达数据包,SrcIP到DstIP已经存在了,只要增加相应数据即可,不过要判断一下协议
            //if (protocolPkInfos.Keys.Contains(protocolType)) //本协议数据存在
            if (protocolPkInfos.ContainsKey(protocolType)) //本协议数据存在
            {
                if (_PkSize != 0)
                {
                    protocolPkInfos[protocolType][0]++;
                    protocolPkInfos[protocolType][1] += _PkSize;

                    totalSendPkNum++;
                    totalSendPkSize += _PkSize;
                }
            }
            else //本协议数据不存在,建立这个协议的值
            {
                if (_PkSize != 0)
                {
                    protocolPkInfos.Add(protocolType, new int[] { 1, _PkSize });

                    totalSendPkNum++;
                    totalSendPkSize += _PkSize;
                }
                else
                {
                    protocolPkInfos.Add(protocolType, new int[] { 0, _PkSize });
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Called by IPv4 and IPv6 packets to parse their packet payload
        /// </summary>
        /// <param name="payload">
        /// A <see cref="ByteArraySegment"/>
        /// </param>
        /// <param name="ProtocolType">
        /// A <see cref="IPProtocolType"/>
        /// </param>
        /// <param name="ParentPacket">
        /// A <see cref="Packet"/>
        /// </param>
        /// <returns>
        /// A <see cref="PacketOrByteArraySegment"/>
        /// </returns>
        internal static PacketOrByteArraySegment ParseEncapsulatedBytes(ByteArraySegment payload,
                                                                        IPProtocolType ProtocolType,
                                                                        Packet ParentPacket)
        {
            log.DebugFormat("payload: {0}, ParentPacket.GetType() {1}",
                            payload,
                            ParentPacket.GetType());

            var payloadPacketOrData = new PacketOrByteArraySegment();

            // if we are an ipv4 packet with a non-zero FragementOffset we shouldn't attempt
            // to decode the content, it is a continuation of a previous packet so it won't
            // have the proper headers for its type, that was in the first packet fragment
            var ipv4Packet = ParentPacket.Extract(typeof(IPv4Packet)) as IPv4Packet;

            if (ipv4Packet != null)
            {
                if (ipv4Packet.FragmentOffset > 0)
                {
                    payloadPacketOrData.TheByteArraySegment = payload;
                    return(payloadPacketOrData);
                }
            }

            switch (ProtocolType)
            {
            case IPProtocolType.TCP:
                payloadPacketOrData.ThePacket = new TcpPacket(payload,
                                                              ParentPacket);
                break;

            case IPProtocolType.UDP:
                payloadPacketOrData.ThePacket = new UdpPacket(payload,
                                                              ParentPacket);
                break;

            case IPProtocolType.ICMP:
                payloadPacketOrData.ThePacket = new ICMPv4Packet(payload,
                                                                 ParentPacket);
                break;

            case IPProtocolType.ICMPV6:
                payloadPacketOrData.ThePacket = new ICMPv6Packet(payload,
                                                                 ParentPacket);
                break;

            case IPProtocolType.IGMP:
                payloadPacketOrData.ThePacket = new IGMPv2Packet(payload,
                                                                 ParentPacket);
                break;

            // NOTE: new payload parsing entries go here
            default:
                payloadPacketOrData.TheByteArraySegment = payload;
                break;
            }

            return(payloadPacketOrData);
        }
Exemplo n.º 9
0
 public Package(IpPacket ipPacket)
 {
     this.CreatedTime    = DateTime.Now.ToString("HH:mm:ss");
     _sourceAdress       = ipPacket.SourceAddress.ToString();
     _destinationAddress = ipPacket.DestinationAddress.ToString();
     _nextHeader         = ipPacket.NextHeader.ToString();
     _protocol           = ipPacket.Protocol;
 }
Exemplo n.º 10
0
 public L3L4ConversationKey(IPAddress sourceIpAddress,
                            IPAddress destinationIpAddress,
                            UInt16 sourcePort,
                            UInt16 destinationPort,
                            IPProtocolType ipProtocolType)
 {
     this._l3Key = new L3ConversationKeyStruct(sourceIpAddress, destinationIpAddress);
     this._l4Key = new L4ConversationKeyStruct(sourcePort, destinationPort, ipProtocolType);
 }
Exemplo n.º 11
0
 public ReassembledL7ConversationTests(ITestOutputHelper output)
 {
     this._output              = output;
     this._sourceEndPoint      = new IPEndPoint(1, 1);
     this._destinationEndPoint = new IPEndPoint(2, 2);
     this._ipProtocolType      = IPProtocolType.TCP;
     this._upL7Flow            = new L7Flow();
     this._downL7Flow          = new L7Flow();
     this._l7PDUComparer       = new L7PDUComparer();
 }
Exemplo n.º 12
0
 /// <summary> Fetch a protocol description.</summary>
 /// <param name="code">the code associated with the message.
 /// </param>
 /// <returns> a message describing the significance of the IP protocol.
 /// </returns>
 public static string getDescription(IPProtocolType protocolType)
 {
     if (messages.ContainsKey(protocolType))
     {
         return(messages[protocolType].ToString());
     }
     else
     {
         return("unknown");
     }
 }
Exemplo n.º 13
0
        /*
         * void Receive()
         * {
         *  //byte[] header = new byte[BufferLength];
         *  //_socket.BeginReceive(header, 0, header.Length, SocketFlags.None, OnReceive, header);
         * }
         * void OnReceive(IAsyncResult ar)
         * {
         *  try
         *  {
         *      //int received = _socket.EndReceive(ar);
         *      //rec((byte[])ar.AsyncState, received);
         *  }
         *  catch
         *  {
         *
         *  }
         * }
         * void rec(byte[] data, int length)
         * {
         *  IPHeader ipHeader = new IPHeader(data, length);
         *  IPacket packet = ipHeader.ParseData();
         *
         *  if (OnPacket != null)
         *      OnPacket(ipHeader.ProtocolType, packet);
         *
         *  if (OnTcpStream != null && ipHeader.ProtocolType == ProtocolType.Tcp)
         *  {
         *      TcpHeader tcp = (TcpHeader)packet;
         *
         *      if (AllowTcpPacket(tcp))
         *      {
         *          TcpStream stream = TcpStream.GetStream(_TcpStreams, tcp);
         *          if (stream != null)
         *          {
         *              if (stream.IsClossed)
         *                  _TcpStreams.Remove(stream);
         *              OnTcpStream(stream);
         *          }
         *      }
         *  }
         *
         *  Receive();
         * }*/
        bool IsAllowedPacket(IPEndPoint source, IPEndPoint dest, IPProtocolType protocol)
        {
            //if (_HasFilters)
            foreach (IIpPacketFilter filter in _Filters)
            {
                if (!filter.IsAllowed(source, dest, protocol))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 14
0
        public bool IsAllowed(IPEndPoint source, IPEndPoint dest, IPProtocolType protocol)
        {
            if (IsAllowed(source.Address))
            {
                return(true);
            }
            if (IsAllowed(dest.Address))
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 15
0
        public static L7ConversationTrackerBase Create(IPEndPoint sourceEndPoint,
                                                       IPEndPoint destinationEndPoint,
                                                       IPProtocolType protocolType)
        {
            switch (protocolType)
            {
            case IPProtocolType.TCP: return(new TcpConversationTracker(sourceEndPoint, destinationEndPoint));

            case IPProtocolType.UDP: return(new UdpConversationTracker(sourceEndPoint, destinationEndPoint));

            default:
                // TODO set frame for exception
                throw new ReassemblingException(null, $"Unsupported IP protocol: {protocolType}");
            }
        }
Exemplo n.º 16
0
        private static Boolean ParseNetworkIpv6Layer(ReadOnlySpan <Byte> networkData,
                                                     ref ReadOnlySpan <Byte> transportData,
                                                     ref IPProtocolType ipProtocol,
                                                     ref IPAddress sourceIpAddress,
                                                     ref IPAddress destinationIpAddress)
        {
            ipProtocol = (IPProtocolType)networkData[IPv6Fields.NextHeaderPosition];

            sourceIpAddress      = new IPAddress(networkData.Slice(IPv6Fields.SourceAddressPosition, 16));
            destinationIpAddress = new IPAddress(networkData.Slice(IPv6Fields.DestinationAddressPosition, 16));

            transportData = networkData.Slice(IPv6Fields.HeaderLength);

            return(true);
        }
Exemplo n.º 17
0
        public bool IsAllowed(IPEndPoint source, IPEndPoint dest, IPProtocolType protocol)
        {
            TorHelper.UpdateTorExitNodeList(true);

            if (TorHelper.IsTorExitNode(source.Address))
            {
                return(true);
            }
            if (TorHelper.IsTorExitNode(dest.Address))
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 18
0
        public override void ComputeFeatureForProtocolModel(IFeatureCollectionWrapper <FeatureBase> featureValues)
        {
            var firstSample = featureValues.FirstOrDefault() as TransportProtocolType;

            foreach (var featureValue in featureValues)
            {
                if (((TransportProtocolType)featureValue).L4ProtocolType != firstSample.L4ProtocolType)
                {
                    throw new InvalidOperationException($"Mandatory condition have not been met: {this.GetType().Name}");
                }
            }
            this.L4ProtocolType = firstSample.L4ProtocolType;
            this.FeatureValue   = (double)this.L4ProtocolType;
            this.Weight         = 1;
        }
Exemplo n.º 19
0
        public L4Conversation(IWindsorContainer container, IPProtocolType ipProtocol, L3Conversation l3Conversation, IPEndPoint sourceEndPoint, IPEndPoint destinationEndPoint, long l4FlowMTU)
        {
            this.InvestigationWindsorContainer = container;
            this.L4ProtocolType      = ipProtocol;
            this.L3Conversation      = l3Conversation;
            this.SourceEndPoint      = sourceEndPoint;
            this.DestinationEndPoint = destinationEndPoint;
            this.L4FlowMTU           = l4FlowMTU;
            this.Frames = new WeakConccurentCollection <PmFrameBase>();

            this.Captures                   = new WeakConccurentCollection <PmCaptureBase>();
            this.L7Conversations            = new WeakConccurentCollection <L7Conversation>();
            this.ConversationFlowStatistics = new WeakConccurentCollection <L4ConversationStatistics>();

            this.UpConversationStatistic   = new L4ConversationStatistics(DaRFlowDirection.up, this);
            this.DownConversationStatistic = new L4ConversationStatistics(DaRFlowDirection.down, this);
        }
Exemplo n.º 20
0
        //       int[] 数组中为 每对节点对中 的每一个协议的单向数据包数量和总大小,totalPkNum和totalSize为每一对节点中间的单向数据包数量和总大小

        public PeerToPeer(IPAddress _SrcIP, IPAddress _DstIP, IPProtocolType protocolType, int _PkSize)
        {
            //当数据包到达时,若判断是第一个从_SrcIP到_DstIP的数据包,则生成此结构,并初始化,后续到来的包执行AddData函数
            protocolPkInfos = new Dictionary <IPProtocolType, int[]>();
            srcIP           = _SrcIP;
            dstIP           = _DstIP;
            if (_PkSize != 0)
            {
                protocolPkInfos.Add(protocolType, new int[] { 1, _PkSize });
                totalSendPkNum++;
                totalSendPkSize += _PkSize;
            }
            else
            {
                protocolPkInfos.Add(protocolType, new int[] { 0, _PkSize });
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Get the packet Information from <see cref="RawCapture"/>
 /// </summary>
 /// <param name="rawCapture">The raw captured packet</param>
 /// <param name="len">Get the length of bytes of the packet</param>
 /// <param name="protocol">Get the tansport protocol of the packet</param>
 /// <returns>The Addresses of the packet. Null if the packet has error, or it's not IP packet, or It's IPV6.</returns>
 public static PacketAddress GetPacketAddressFromRowPacket(RawCapture rawCapture, ref int len, ref TCPUDP protocol)
 {
     try
     {
         Packet   p        = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
         IpPacket ipPacket = (IpPacket)p.Extract(typeof(IpPacket));
         if (ipPacket != null)
         {
             len = ipPacket.PayloadLength;
             IPAddress sourceAddress, destinationAddress;
             sourceAddress      = ipPacket.SourceAddress;
             destinationAddress = ipPacket.DestinationAddress;
             if (sourceAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork &&
                 destinationAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
             {
                 IPProtocolType type = ipPacket.NextHeader;
                 if (type == IPProtocolType.TCP)
                 {
                     TcpPacket tcpPacket = (TcpPacket)ipPacket.Extract(typeof(TcpPacket));
                     if (tcpPacket != null)
                     {
                         protocol = TCPUDP.TCP;
                         return(new PacketAddress(sourceAddress, tcpPacket.SourcePort, destinationAddress, tcpPacket.DestinationPort));
                     }
                 }
                 else if (type == IPProtocolType.UDP)
                 {
                     UdpPacket udpPacket = (UdpPacket)ipPacket.Extract(typeof(UdpPacket));
                     if (udpPacket != null)
                     {
                         protocol = TCPUDP.UDP;
                         return(new PacketAddress(sourceAddress, udpPacket.SourcePort, destinationAddress, udpPacket.DestinationPort));
                     }
                 }
             }
         }
         return(null);
     }
     catch (Exception)
     {
         Console.WriteLine("Packet Error");
         //Console.WriteLine(e.Message + "\n" + e.StackTrace);
         return(null);
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// Called by IPv4 and IPv6 packets to parse their packet payload
        /// </summary>
        /// <param name="payload">
        /// A <see cref="ByteArraySegment"/>
        /// </param>
        /// <param name="ProtocolType">
        /// A <see cref="IPProtocolType"/>
        /// </param>
        /// <param name="ParentPacket">
        /// A <see cref="Packet"/>
        /// </param>
        /// <returns>
        /// A <see cref="PacketOrByteArraySegment"/>
        /// </returns>
        internal static PacketOrByteArraySegment ParseEncapsulatedBytes(ByteArraySegment payload,
                                                                        IPProtocolType ProtocolType,
                                                                        Packet ParentPacket)
        {
            //log.DEBUGFormat("payload: {0}, ParentPacket.GetType() {1}",
            //payload,
            //ParentPacket.GetType());

            var payloadPacketOrData = new PacketOrByteArraySegment();

            switch (ProtocolType)
            {
            case IPProtocolType.TCP:
                payloadPacketOrData.ThePacket = new TcpPacket(payload,
                                                              ParentPacket);
                break;

            case IPProtocolType.UDP:
                payloadPacketOrData.ThePacket = new UdpPacket(payload,
                                                              ParentPacket);
                break;

            case IPProtocolType.ICMP:
                payloadPacketOrData.ThePacket = new ICMPv4Packet(payload,
                                                                 ParentPacket);
                break;

            case IPProtocolType.ICMPV6:
                payloadPacketOrData.ThePacket = new ICMPv6Packet(payload,
                                                                 ParentPacket);
                break;

            case IPProtocolType.IGMP:
                payloadPacketOrData.ThePacket = new IGMPv2Packet(payload,
                                                                 ParentPacket);
                break;

            // NOTE: new payload parsing entries go here
            default:
                payloadPacketOrData.TheByteArraySegment = payload;
                break;
            }

            return(payloadPacketOrData);
        }
Exemplo n.º 23
0
        public ReassembledL7Conversation(IPEndPoint sourceEndPoint,
                                         IPEndPoint destinationEndPoint,
                                         IPProtocolType protocolType,
                                         IL7Flow upL7Flow,
                                         IL7Flow downL7Flow,
                                         Int32 conversationSegmentNum    = 0,
                                         Boolean lastConversationSegment = true)
        {
            this.SourceEndPoint      = sourceEndPoint;
            this.DestinationEndPoint = destinationEndPoint;
            this.ProtocolType        = protocolType;

            this.LastConversationSegment = lastConversationSegment;
            this.ConversationSegmentNum  = conversationSegmentNum;

            this.UpPdus   = upL7Flow?.L7Pdus ?? NoPdusPlaceholder;
            this.DownPdus = downL7Flow?.L7Pdus ?? NoPdusPlaceholder;

            this._firstSeenTicks = Math.Max(upL7Flow?.FirstSeenTicks ?? 0, downL7Flow?.FirstSeenTicks ?? 0);
        }
Exemplo n.º 24
0
        public void PkFromHere(IPAddress dstIP, IPProtocolType protocolType, int pkSize)
        {
//             if (dstIP.ToString().Equals("192.168.2.1"))
//             {
//             }
            //当到dstIP的数据包是第一个时
            if (!peerToPeers.ContainsKey(dstIP))
            {
                peerToPeers.Add(dstIP, new PeerToPeer(localIP, dstIP, protocolType, pkSize));
                linkedIPs.Add(dstIP);
            }
            else   //当到dstIP的数据包是后续的时
            {
                peerToPeers[dstIP].AddData(protocolType, pkSize);
            }
            if (pkSize != 0)
            {
                allSendPkNum++;
                allSendPkSize += pkSize;
            }
        }
Exemplo n.º 25
0
        private static Boolean ParseNetworkIpv4Layer(ReadOnlySpan <Byte> networkData,
                                                     ref ReadOnlySpan <Byte> transportData,
                                                     ref IPProtocolType ipProtocol,
                                                     ref IPAddress sourceIpAddress,
                                                     ref IPAddress destinationIpAddress,
                                                     ref IPFragmentSignature ipv4FragmentSignature)
        {
            // Min ipv4 header size
            if (networkData.Length < 20)
            {
                return(false);
            }

            ipProtocol = (IPProtocolType)networkData[IPv4Fields.ProtocolPosition];

            sourceIpAddress      = new IPAddress(networkData.Slice(IPv4Fields.SourcePosition, 4));
            destinationIpAddress = new IPAddress(networkData.Slice(IPv4Fields.DestinationPosition, 4));

            var headerLen = (networkData[0] & 0x0F) * 4;
            var totalLen  =
                BinaryPrimitives.ReadUInt16BigEndian(networkData.Slice(IPv4Fields.TotalLengthPosition, IPv4Fields.TotalLengthLength));

            transportData = networkData.Slice(headerLen, totalLen - headerLen);


            var moreFragments  = (networkData[IPv4Fields.FragmentOffsetAndFlagsPosition] & 0b00100000) != 0;
            var fragmentOffset = ((networkData[IPv4Fields.FragmentOffsetAndFlagsPosition] & 0b00011111) << 8) |
                                 networkData[IPv4Fields.FragmentOffsetAndFlagsPosition + 1];
            var identification     = BinaryPrimitives.ReadUInt16BigEndian(networkData.Slice(IPv4Fields.IdPosition, 2));
            var packetIsFragmented = moreFragments || fragmentOffset > 0;

            if (packetIsFragmented)
            {
                ipv4FragmentSignature = new IPFragmentSignature(sourceIpAddress, destinationIpAddress, ipProtocol, identification, moreFragments, fragmentOffset);
            }

            return(true);
        }
Exemplo n.º 26
0
        public static Boolean ExtractRawPacketSignature(RawPacket rawPacket,
                                                        out IPAddress sourceIpAddress,
                                                        out IPAddress destinationIpAddress,
                                                        out UInt16 sourcePort,
                                                        out UInt16 destinationPort,
                                                        out IPProtocolType ipProtocol,
                                                        out IPFragmentSignature ipv4FragmentSignature)
        {
            sourceIpAddress       = destinationIpAddress = IPAddress.None;
            sourcePort            = destinationPort = 0;
            ipProtocol            = IPProtocolType.NONE;
            ipv4FragmentSignature = null;

            if (!ParseLinkLayer(rawPacket.RawPacketData, rawPacket.LinkType, out var networkData, out var ethernetProtocol))
            {
                return(false);
            }

            if (!ParseNetworkLayer(networkData, ethernetProtocol, out var transportData,
                                   out ipProtocol, out sourceIpAddress, out destinationIpAddress, out ipv4FragmentSignature))
            {
                return(false);
            }

            // Don't continue with parsing of a transport layer, if the current packet is fragmented and this fragment is not the initial one (containing transport header)
            if (ipv4FragmentSignature != null && ipv4FragmentSignature.FragmentOffset > 0)
            {
                return(true);
            }

            if (!ParseTransportLayer(transportData, ipProtocol, out sourcePort, out destinationPort))
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 27
0
        public L4ConversationExtended(IWindsorContainer container, IL7ConversationTrackerFactory conversationTrackerFactory, IPProtocolType ipProtocol, L3Conversation l3Conversation, IPEndPoint sourceEndPoint, IPEndPoint destinationEndPoint, long l4FlowMTU)
            : base(container, ipProtocol, l3Conversation, sourceEndPoint, destinationEndPoint, l4FlowMTU)
        {
            switch (this.L4ProtocolType)
            {
            case IPProtocolType.TCP: this.L7ConversationTracker = conversationTrackerFactory.CreateTCPTracker(this); break;

            case IPProtocolType.UDP: this.L7ConversationTracker = conversationTrackerFactory.CreateUDPTracker(this); break;

            default:
                Debugger.Break();
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 28
0
    //constructor, reads in the args
    public Param(string[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            string curStr = args[i];

            try
            {
                if (String.Compare(curStr, "-adapter", true) == 0)
                {
                    string nextStr = args[++i];
                    adapter = nextStr;
                    Console.WriteLine("Read in adapter as: " + adapter);
                }
                else if (String.Compare(curStr, "-v6EH", true) == 0)
                {
                    string nextStr = args[++i];
                    string[] tempEHArray = nextStr.Split(',');
                    //ExtentionHeader =

                    int[] tempInt = Array.ConvertAll(tempEHArray, int.Parse);
                    foreach (int curInt in tempInt)
                    {
                        ExtentionHeader.Add((IPProtocolType)curInt);
                    }
                    packetType = PacketType.IP;
                    IPProtocol = IPProtocolType.IPV6;

                    Console.WriteLine("Read in -v6EH as: " + string.Join(",", tempEHArray));
                    Console.WriteLine("Setting packetType as: " + packetType.ToString());
                    Console.WriteLine("Setting IPProtocol as: " + IPProtocol.ToString());
                }
                else if (String.Compare(curStr, "-dMAC", true) == 0)
                {
                    string nextStr = args[++i];
                    nextStr = nextStr.Replace(':', '-').ToUpper();
                    dMAC = PhysicalAddress.Parse(nextStr);
                    Console.WriteLine("Read in dMAC as: " + dMAC.ToString());
                }
                else if (String.Compare(curStr, "-sMAC", true) == 0)
                {
                    string nextStr = args[++i];
                    nextStr = nextStr.Replace(':', '-').ToUpper();
                    sMAC = PhysicalAddress.Parse(nextStr);
                    Console.WriteLine("Read in sMAC as: " + sMAC.ToString());
                }
                else if (String.Compare(curStr, "-dIP", true) == 0)
                {
                    string nextStr = args[++i];
                    dIP = IPAddress.Parse(nextStr);
                    Console.WriteLine("Read in dIP as: " + dIP.ToString());
                }
                else if (String.Compare(curStr, "-sIP", true) == 0)
                {
                    string nextStr = args[++i];
                    sIP = IPAddress.Parse(nextStr);
                    Console.WriteLine("Read in sIP as: " + sIP.ToString());
                }
                else if (String.Compare(curStr, "-IP", true) == 0)
                {
                    string nextStr = args[++i];
                    packetType = PacketType.IP;
                    if (nextStr.StartsWith("0x"))
                    {
                        IPProtocol = (IPProtocolType)Convert.ToInt32(nextStr, 16);
                    }
                    else
                    {
                        IPProtocol = (IPProtocolType)Convert.ToInt32(nextStr);
                    }
                    Console.WriteLine("Read in IP as: " + IPProtocol.ToString());
                }
                else if (String.Compare(curStr, "-EtherType", true) == 0)
                {
                    string nextStr = args[++i];
                    packetType = PacketType.EtherType;
                    if (nextStr.StartsWith("0x"))
                    {
                        EtherTypeProtocol = (EthernetPacketType)Convert.ToInt32(nextStr, 16);
                    }
                    else
                    {
                        EtherTypeProtocol = (EthernetPacketType)Convert.ToInt32(nextStr);
                    }
                    Console.WriteLine("Read in EtherType as: " + EtherTypeProtocol.ToString());
                }
                else if (String.Compare(curStr, "-sPort", true) == 0)
                {
                    string nextStr = args[++i];
                    sPort = (ushort)Int16.Parse(nextStr);
                    Console.WriteLine("Read in sPort as: " + sPort.ToString());
                }
                else if (String.Compare(curStr, "-dPort", true) == 0)
                {
                    string nextStr = args[++i];
                    dPort = (ushort)Int16.Parse(nextStr);
                    Console.WriteLine("Read in dPort as: " + dPort.ToString());
                }
                else if (String.Compare(curStr, "-type", true) == 0)
                {
                    string nextStr = args[++i];
                    type = (ushort)Int16.Parse(nextStr);
                    Console.WriteLine("Read in type as: " + type.ToString());
                }
                else if (String.Compare(curStr, "-tcpFlag", true) == 0)
                {
                    string nextStr = args[++i];
                    tcpFlag = (byte)Byte.Parse(nextStr);
                    Console.WriteLine("Read in tcpFlag as: " + tcpFlag.ToString());
                }
                else if (String.Compare(curStr, "-code", true) == 0)
                {
                    string nextStr = args[++i];
                    code = (ushort)Int16.Parse(nextStr);
                    Console.WriteLine("Read in code as: " + code.ToString());
                }
                else if (String.Compare(curStr, "-payload", true) == 0)
                {
                    string nextStr = args[++i];
                    if (nextStr.StartsWith("0x"))
                    {
                        payload = Utility.ParseHex(nextStr);
                        Console.WriteLine("Read in -payload as: 0x" + BitConverter.ToString(payload));
                    }
                    else
                    {
                        payload = Encoding.ASCII.GetBytes(nextStr);
                        Console.WriteLine("Read in -payload as: " + System.Text.Encoding.Default.GetString(payload));
                    }
                }
                else if (String.Compare(curStr, "-adapter", true) == 0)
                {
                    string nextStr = args[++i];
                    adapter = nextStr;
                    Console.WriteLine("Read in -adapter as: " + adapter);
                }
                else if (String.Compare(curStr, "-IPv4Frag", true) == 0)
                {
                    IPv4Frag = true;
                    Console.WriteLine("Read in -ipv4frag as: " + IPv4Frag);
                }
                else if (String.Compare(curStr, "-ICMP", true) == 0)
                {
                    packetType = PacketType.ICMP;
                }
                else if (String.Compare(curStr, "-tcp", true) == 0)
                {
                    packetType = PacketType.TCP;
                }
                else if (String.Compare(curStr, "-udp", true) == 0)
                {
                    packetType = PacketType.UDP;
                }
                else if (String.Compare(curStr, "-ICMPv6", true) == 0)
                {
                    packetType = PacketType.ICMPv6;
                }
                else if (String.Compare(curStr, "-h", true) == 0)
                {
                    Utility.PrintHelp();
                    Environment.Exit(0);
                }
                else
                {
                    Console.WriteLine("Unrecognized param: " + curStr);
                    Utility.PrintHelp();
                    Environment.Exit(1);
                }
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("Another arg was expected after " + curStr);
                Environment.Exit(1);
            }
            catch (FormatException)
            {
                Console.WriteLine("The address specified for " + curStr + " was not in the correct format.");
                Environment.Exit(1);
            }
            catch (DllNotFoundException e)
            {
                Console.WriteLine("A required DLL was not found, is WinPcap and .NET framework installed?");
                Console.WriteLine("Exception Message: " + e.Message);
                Console.WriteLine("StackTrace: " + e.StackTrace);
                Environment.Exit(1);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught while handling commandline.");
                Console.WriteLine("Exception Message: " + e.Message);
                Console.WriteLine("StackTrace: " + e.StackTrace);
                Environment.Exit(1);
            }
        }

        // do some checks to make sure this param combination is valid

        if (dIP == null && dMAC == null)
        {
            Console.WriteLine("-dIP or -dMAC has to be set to send a packet.");
            Environment.Exit(1);
        }

        if (dIP == null &&
            (packetType == PacketType.ICMP ||
            packetType == PacketType.ICMPv6 ||
            packetType == PacketType.IP ||
            packetType == PacketType.TCP ||
            packetType == PacketType.UDP))
        {
            Console.WriteLine("dIP needs to be defined for IP based packets.");
            Environment.Exit(1);
        }

        if (packetType == PacketType.ICMPv6 && (dIP == null || !dIP.ToString().Contains(":")))
        {
            Console.WriteLine("dIP needs to be IPv6 for ICMPv6 packets.");
            Environment.Exit(1);
        }
        else if ((packetType == PacketType.ICMP && (dIP == null || !dIP.ToString().Contains("."))))
        {
            Console.WriteLine("dIP needs to be IPv4 for ICMP packets.");
            Environment.Exit(1);
        }

        if (ExtentionHeader.Count != 0 && (dIP == null || !dIP.ToString().Contains(":")))
        {
            Console.WriteLine("dIP needs to be IPv6 for ExtensionHeader packets.");
            Environment.Exit(1);
        }

        if (ExtentionHeader.Count == 1)
        {
            Console.WriteLine("There needs to be at least 2 extension headers.");
            Environment.Exit(1);
        }

        if (dMAC == null && packetType == PacketType.EtherType)
        {
            Console.WriteLine("dMAC needs to be defined for EtherType based packets.");
            Environment.Exit(1);
        }
    }
Exemplo n.º 29
0
 /// <summary> Fetch a protocol description.</summary>
 /// <param name="code">the code associated with the message.
 /// </param>
 /// <returns> a message describing the significance of the IP protocol.
 /// </returns>
 public static string getDescription(IPProtocolType protocolType)
 {
     if (messages.ContainsKey(protocolType))
     {
         return messages[protocolType].ToString();
     }
     else
     {
         return "unknown";
     }
 }
Exemplo n.º 30
0
        static void Ns_OnPacket(object sender, IPProtocolType protocolType, EthernetPacket packet)
        {
            NetworkSniffer ns = (NetworkSniffer)sender;
            IPv4Packet     ip = (IPv4Packet)packet.PayloadPacket;
            TcpPacket      t  = (TcpPacket)ip.PayloadPacket;

            // Si el paquete recibido es el de respuesta OK del mysql
            if (t.PayloadData.SequenceEqual(ResponseOk))
            {
                Parent = packet;

                // Replicamos el paquete, enviando el payload de la fila, si, antes de recibir el SELECT
                LastSequenceId = (uint)(t.SequenceNumber + t.PayloadData.Length);
                ip.Id++;
                t.SequenceNumber = LastSequenceId;
                t.OptionsCollection.Clear();

                t.PayloadData = Payload;
                t.Ack         = true;
                t.Psh         = true;

                ip.UpdateCalculatedValues();
                t.UpdateCalculatedValues();

                ip.UpdateIPChecksum();
                t.UpdateTCPChecksum();

                ns.Send(packet);

                LastSequenceId = (uint)(t.SequenceNumber + t.PayloadData.Length);
                Console.WriteLine(t.ToString(StringOutputType.Verbose));
            }
            else
            {
                // Si el paquete contiene el valor SELECT
                string ascii = Encoding.ASCII.GetString(t.PayloadData);
                if (Parent != null && ascii.Contains("SELECT"))
                {
                    // Ya no actuamos mas
                    ns.OnPacket -= Ns_OnPacket;

                    ip = (IPv4Packet)Parent.PayloadPacket;
                    t  = (TcpPacket)ip.PayloadPacket;

                    // Enviamos un ACK del paquete recibido, para darle por bueno
                    t.SequenceNumber       = LastSequenceId;
                    t.AcknowledgmentNumber = t.AcknowledgmentNumber;
                    t.PayloadData          = new byte[] { };
                    ip.Id++;
                    t.Ack = true;
                    t.Psh = false;

                    ip.UpdateCalculatedValues();
                    t.UpdateCalculatedValues();

                    ip.UpdateIPChecksum();
                    t.UpdateTCPChecksum();

                    ns.Send(packet);
                    Console.WriteLine(t.ToString(StringOutputType.Verbose));
                }
            }
        }
Exemplo n.º 31
0
 public void OnPacket(object sender, IPProtocolType protocolType, EthernetPacket packet)
 {
 }
Exemplo n.º 32
0
 public override double ComputeFeature(L7Conversation l7Conversation, DaRFlowDirection flowDirection)
 {
     this.L4ProtocolType = l7Conversation.L4ProtocolType;
     return((double)this.L4ProtocolType);
 }
Exemplo n.º 33
-1
 public void FillWithChecksums(EtherType[] supportedEtherTypes, IPProtocolType[] supportedIpProtocolTypes)
 {
     var packetNetIpProtocols = supportedIpProtocolTypes.Select(x => (PacketDotNet.IPProtocolType)x).ToArray();
     var packetNetEtherTypes = supportedEtherTypes.Select(x => (EthernetPacketType)x).ToArray();
     packet.RecursivelyUpdateCalculatedValues(packetNetEtherTypes, packetNetIpProtocols);
 }