public static void MakeValid(TCPPacket tcp, IPVersions ipver) { tcp.IPVersion = ipver; tcp.IPProtocol = Packets.IPProtocol.IPProtocolType.TCP; tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN; //Set the correct TCP header length if (ipver == IPVersions.IPv4) { // the total length of the ip packet is the size of all of the bytes in the packet // represented by tcp.Bytes, minus the link layer bytes // NOTE: this includes the ip header bytes, which is how the IPv4 total bytes // works tcp.IPTotalLength = tcp.Bytes.Length - LinkLayer.ProtocolOffset(LinkLayers.Ethernet10Mb); //Set the correct IP length tcp.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN; } else if (ipver == IPVersions.IPv6) { tcp.IPPayloadLength = tcp.Bytes.Length - EthernetFields_Fields.ETH_HEADER_LEN - IPv6Fields_Fields.IPv6_HEADER_LEN; } else { throw new System.InvalidOperationException("unknown ipver of " + ipver); } //Calculate checksums tcp.ComputeIPChecksum(); tcp.ComputeTCPChecksum(); }
public static TCPPacket RandomPacket(int size, IPVersions ipver) { if (size < 54) { throw new Exception("Size should be at least 54 (Eth + IP + TCP)"); } if (ipver == IPVersions.IPv6 && size < 74) { throw new Exception("Size should be at least 74 (Eth + IPv6 + TCP)"); } byte[] bytes = new byte[size]; SharpPcap.Util.Rand.Instance.GetBytes(bytes); TCPPacket tcp = new TCPPacket(14, bytes, true); MakeValid(tcp, ipver); return(tcp); }
public static TCPPacket RandomPacket(int size, IPVersions ipver) { if (size < MinimumIPv4Bytes) { throw new Exception("Size should be at least " + MinimumIPv4Bytes + " (Eth + IP + TCP)"); } if ((ipver == IPVersions.IPv6) && (size < MinimumIPv6Bytes)) { throw new Exception("Size should be at least " + MinimumIPv6Bytes + " (Eth + IPv6 + TCP)"); } byte[] bytes = new byte[size]; SharpPcap.Util.Rand.Instance.GetBytes(bytes); TCPPacket tcp = new TCPPacket(LinkLayer.ProtocolOffset(LinkLayers.Ethernet10Mb), bytes, true); MakeValid(tcp, ipver); return(tcp); }
public TCPPacket CreateTcpPacket(IPv4Packet ipv4Packet) { TCPPacket tcpPacket = new TCPPacket( EthernetFields_Fields.ETH_HEADER_LEN, ipv4Packet.Bytes); // TCP fields tcpPacket.SourcePort = Int32.Parse(textBoxSourcePort.Text); tcpPacket.DestinationPort = Int32.Parse(textBoxDestinationPort.Text); tcpPacket.SequenceNumber = Int64.Parse(textBoxSeqNumber.Text); tcpPacket.AcknowledgmentNumber = Int64.Parse(textBoxAckNumber.Text); // AllFlags field includes TCPHeaderLength field, so it must be set first tcpPacket.AllFlags = Int32.Parse(textBoxFlags.Text); tcpPacket.TCPHeaderLength = Int32.Parse(textBoxHeaderLength.Text); tcpPacket.WindowSize = Int32.Parse(textBoxWindowSize.Text); tcpPacket.UrgentPointer = Int32.Parse(textBoxUrgentPointer.Text); // Calculate checksum tcpPacket.ComputeTCPChecksum(true); return tcpPacket; }
public static void MakeValid(TCPPacket tcp, IPVersions ipver) { tcp.IPVersion = ipver; tcp.IPProtocol = Packets.IPProtocol.IPProtocolType.TCP; tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN; //Set the correct TCP header length if (ipver == IPVersions.IPv4) { tcp.IPTotalLength = tcp.Bytes.Length - 14; //Set the correct IP length tcp.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN; } else if (ipver == IPVersions.IPv6) { tcp.IPPayloadLength = tcp.Bytes.Length - EthernetFields_Fields.ETH_HEADER_LEN - IPv6Fields_Fields.IPv6_HEADER_LEN; } else { } //Calculate checksums tcp.ComputeIPChecksum(); tcp.ComputeTCPChecksum(); }
public static TCPPacket RandomPacket(int size, IPVersions ipver) { if(size<54) throw new Exception("Size should be at least 54 (Eth + IP + TCP)"); if(ipver == IPVersions.IPv6 && size < 74) throw new Exception("Size should be at least 74 (Eth + IPv6 + TCP)"); byte[] bytes = new byte[size]; SharpPcap.Util.Rand.Instance.GetBytes(bytes); TCPPacket tcp = new TCPPacket(14, bytes, true); MakeValid(tcp, ipver); return tcp; }
private void ProcessTCPPacket(TCPPacket pTCPPacket, ref uint pSequence, SortedDictionary<uint, byte[]> pBuffer, RiftStream pStream) { if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.TCPData; if (pTCPPacket.SequenceNumber < pSequence) { int difference = (int)(pSequence - pTCPPacket.SequenceNumber); byte[] data = pTCPPacket.TCPData; if (data.Length > difference) { pStream.Append(data, difference, data.Length - difference); pSequence += (uint)(data.Length - difference); } } else if (pTCPPacket.SequenceNumber == pSequence) { byte[] data = pTCPPacket.TCPData; pStream.Append(data); pSequence += (uint)data.Length; bool found; do { SortedDictionary<uint, byte[]>.Enumerator enumerator = pBuffer.GetEnumerator(); if ((found = (enumerator.MoveNext() && enumerator.Current.Key <= pSequence))) { int difference = (int)(pSequence - enumerator.Current.Key); if (enumerator.Current.Value.Length > difference) { pStream.Append(enumerator.Current.Value, difference, enumerator.Current.Value.Length - difference); pSequence += (uint)(enumerator.Current.Value.Length - difference); } pBuffer.Remove(enumerator.Current.Key); } } while (found); } RiftPacket packet; while ((packet = pStream.Read(pTCPPacket.Timeval.Date)) != null) { AddPacket(packet); if (packet.Opcode == 0x01B7) mIsCharacterSession = true; else if (packet.Opcode == 0x040B) { RiftPacketField fieldServerPublicKey; if (packet.GetFieldByIndex(out fieldServerPublicKey, 1) && fieldServerPublicKey.Type == ERiftPacketFieldType.ByteArray && fieldServerPublicKey.Value.Bytes.Length == 128) { if (mClientPrivateKeys != null && mClientPrivateKeys.ContainsKey(mIsCharacterSession)) mClientPrivateKey = BigNumber.FromArray(mClientPrivateKeys[mIsCharacterSession]); if (mClientPrivateKey == null) { // Scan for rift.exe, read memory to pointers, get client private key } mServerPublicKey = BigNumber.FromArray(fieldServerPublicKey.Value.Bytes); DH dh = new DH(mModulus, mGenerator, BigNumber.One, mClientPrivateKey); mSharedSecretKey = dh.ComputeKey(mServerPublicKey); } } else if (packet.Opcode == 0x19) { pStream.EnableInflater(); if (packet.Outbound) { mInboundStream.EnableEncryption(mSharedSecretKey); mOutboundStream.EnableEncryption(mSharedSecretKey); } } } }
internal bool MatchTCPPacket(TCPPacket pTCPPacket) { if (mTerminated) return false; if (pTCPPacket.SourcePort == mLocalPort && pTCPPacket.DestinationPort == mRemotePort) return true; if (pTCPPacket.SourcePort == mRemotePort && pTCPPacket.DestinationPort == mLocalPort) return true; return false; }
internal void BufferTCPPacket(TCPPacket pTCPPacket) { if (pTCPPacket.Fin || pTCPPacket.Rst) { mTerminated = true; return; } if (mOutboundSequence == 0) { mLocalPort = (ushort)pTCPPacket.SourcePort; mRemotePort = (ushort)pTCPPacket.DestinationPort; mOutboundSequence = (uint)pTCPPacket.SequenceNumber + 1; Text = "Port " + mLocalPort.ToString(); } if (mInboundSequence == 0 && pTCPPacket.SourcePort == mRemotePort) mInboundSequence = (uint)pTCPPacket.SequenceNumber + 1; if (pTCPPacket.PayloadDataLength == 0) return; if (pTCPPacket.SourcePort == mLocalPort) ProcessTCPPacket(pTCPPacket, ref mOutboundSequence, mOutboundBuffer, mOutboundStream); else ProcessTCPPacket(pTCPPacket, ref mInboundSequence, mInboundBuffer, mInboundStream); }
public ScanMessage Connect(IPEndPoint ipEndPoint) { // SYN packet creation //MAC address of gateway is provided by arp protocol ARP arper = new ARP(device.Name); arper.LocalIP = device.Interface.Addresses[0].Addr.ipAddress; arper.LocalMAC = device.Interface.MacAddress; PhysicalAddress gatewayHwAddress = arper.Resolve(gatewayAddress); EthernetPacket ethernetHeader = new EthernetPacket( device.Interface.MacAddress, gatewayHwAddress, EthernetPacketType.IPv4, null); byte[] content = new byte[ EthernetFields_Fields.ETH_HEADER_LEN + IPv4Fields_Fields.IP_HEADER_LEN + TCPFields_Fields.TCP_HEADER_LEN]; IPv4Packet ipv4Packet = new IPv4Packet( EthernetFields_Fields.ETH_HEADER_LEN, content); // Ethernet header ipv4Packet.EthernetHeader = ethernetHeader.Bytes; // IP fields ipv4Packet.Version = 4; ipv4Packet.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN; ipv4Packet.IPTotalLength = content.Length - EthernetFields_Fields.ETH_HEADER_LEN; ipv4Packet.Id = 100; ipv4Packet.TimeToLive = 20; ipv4Packet.IPProtocol = IPProtocol.IPProtocolType.TCP; ipv4Packet.SourceAddress = device.Interface.Addresses[0].Addr.ipAddress; ipv4Packet.DestinationAddress = ipEndPoint.Address; ipv4Packet.ComputeIPChecksum(true); TCPPacket tcpPacket = new TCPPacket( EthernetFields_Fields.ETH_HEADER_LEN, content); // TCP fields tcpPacket.SourcePort = 2222; tcpPacket.DestinationPort = ipEndPoint.Port; tcpPacket.SequenceNumber = 1000; tcpPacket.AcknowledgmentNumber = 1000; tcpPacket.Syn = true; tcpPacket.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN; tcpPacket.WindowSize = 555; // Calculate checksum tcpPacket.ComputeTCPChecksum(true); try { device.Open(false, 20); device.SetFilter(String.Format("ip src {0} and tcp src port {1} and tcp dst port {2}", tcpPacket.DestinationAddress, tcpPacket.DestinationPort, tcpPacket.SourcePort)); // Send the packet device.SendPacket(tcpPacket); TCPPacket replyPacket = null; bool replyReceived = false; Stopwatch watch = new Stopwatch(); watch.Start(); // Condition including timeout check. while (watch.ElapsedMilliseconds < timeout && replyReceived != true) { if ((replyPacket = (TCPPacket)device.GetNextPacket()) != null) { replyReceived = true; } } if (!replyReceived) // A reply hasn't been received { return ScanMessage.Timeout; } else if (replyPacket.Rst) // Remote host reset the connection { return ScanMessage.PortClosed; } else if (replyPacket.Ack) // Remote host replied with a TCP packet { tcpPacket.Syn = false; tcpPacket.Rst = true; tcpPacket.WindowSize = 0; tcpPacket.ComputeTCPChecksum(true); device.SendPacket(tcpPacket); return ScanMessage.PortOpened; } else { return ScanMessage.Unknown; } } catch (Exception) { return ScanMessage.Unknown; } finally { device.Close(); } }
private void ProcessTCPPacket(TCPPacket pTCPPacket, ref uint pSequence, SortedDictionary<uint, byte[]> pBuffer, RiftStream pStream) { if (pTCPPacket.SequenceNumber > pSequence) pBuffer[(uint)pTCPPacket.SequenceNumber] = pTCPPacket.TCPData; if (pTCPPacket.SequenceNumber < pSequence) { int difference = (int)(pSequence - pTCPPacket.SequenceNumber); byte[] data = pTCPPacket.TCPData; if (data.Length > difference) { pStream.Append(data, difference, data.Length - difference); pSequence += (uint)(data.Length - difference); } } else if (pTCPPacket.SequenceNumber == pSequence) { byte[] data = pTCPPacket.TCPData; pStream.Append(data); pSequence += (uint)data.Length; bool found; do { SortedDictionary<uint, byte[]>.Enumerator enumerator = pBuffer.GetEnumerator(); if ((found = (enumerator.MoveNext() && enumerator.Current.Key <= pSequence))) { int difference = (int)(pSequence - enumerator.Current.Key); if (enumerator.Current.Value.Length > difference) { pStream.Append(enumerator.Current.Value, difference, enumerator.Current.Value.Length - difference); pSequence += (uint)(enumerator.Current.Value.Length - difference); } pBuffer.Remove(enumerator.Current.Key); } } while (found); } RiftPacket packet; while ((packet = pStream.Read(pTCPPacket.Timeval.Date)) != null) { AddPacket(packet); if (packet.Opcode == 0x01B7) { mIsCharacterSession = true; } else if (packet.Opcode == 0x040B) { RiftPacketField fieldServerPublicKey; if (packet.GetFieldByIndex(out fieldServerPublicKey, 1) && fieldServerPublicKey.Type == ERiftPacketFieldType.ByteArray && fieldServerPublicKey.Value.Bytes.Length == 128) { if (mClientPrivateKeys == null) { DateTime started = DateTime.Now; while (!Program.LiveKeys.ContainsKey(mIsCharacterSession) && DateTime.Now.Subtract(started).TotalSeconds < 10) Thread.Sleep(1); if (Program.LiveKeys.ContainsKey(mIsCharacterSession)) mClientPrivateKeys = Program.LiveKeys; else { MessageBox.Show(this, "The required key was unable to be found for some reason, let the developers know this happened.", "Key Grab Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); mTerminated = true; return; } } mClientPrivateKey = BigNumber.FromArray(mClientPrivateKeys[mIsCharacterSession]); mServerPublicKey = BigNumber.FromArray(fieldServerPublicKey.Value.Bytes); DH dh = new DH(mModulus, mGenerator, BigNumber.One, mClientPrivateKey); mSharedSecretKey = dh.ComputeKey(mServerPublicKey); } } else if (packet.Opcode == 0x19) { pStream.EnableInflater(); if (packet.Outbound) { mInboundStream.EnableEncryption(mSharedSecretKey); mOutboundStream.EnableEncryption(mSharedSecretKey); } } } }
public static TCPPacket RandomPacket(int size, IPVersions ipver) { if (size < MinimumIPv4Bytes) throw new Exception("Size should be at least " + MinimumIPv4Bytes + " (Eth + IP + TCP)"); if ((ipver == IPVersions.IPv6) && (size < MinimumIPv6Bytes)) throw new Exception("Size should be at least " + MinimumIPv6Bytes + " (Eth + IPv6 + TCP)"); byte[] bytes = new byte[size]; SharpPcap.Util.Rand.Instance.GetBytes(bytes); TCPPacket tcp = new TCPPacket(LinkLayer.ProtocolOffset(LinkLayers.Ethernet10Mb), bytes, true); MakeValid(tcp, ipver); return tcp; }
/// <summary> Convert captured packet data into an object.</summary> public static Packet dataToPacket(LinkLayers linkType, byte[] bytes, Timeval tv) { EthernetPacketType ethProtocol; // retrieve the length of the headers associated with this link layer type. // this length is the offset to the header embedded in the packet. int byteOffsetToEthernetPayload = LinkLayer.LinkLayerLength(linkType); // extract the protocol code for the type of header embedded in the // link-layer of the packet int offset = LinkLayer.ProtocolOffset(linkType); if (offset == -1) { // if there is no embedded protocol, assume IpV4 ethProtocol = EthernetPacketType.IPv4; } else { ethProtocol = (EthernetPacketType)ArrayHelper.extractInteger(bytes, offset, EthernetFields_Fields.ETH_CODE_LEN); } string errorString; Packet parsedPacket = null; try { // try to recognize the ethernet type.. switch (ethProtocol) { // arp case EthernetPacketType.ARP: parsedPacket = new ARPPacket(byteOffsetToEthernetPayload, bytes, tv); break; case EthernetPacketType.IPv6: case EthernetPacketType.IPv4: try { // ethernet level code is recognized as IP, figure out what kind.. int ipProtocol = IPProtocol.extractProtocol(byteOffsetToEthernetPayload, bytes); switch (ipProtocol) { case (int)IPProtocol.IPProtocolType.ICMP: parsedPacket = new ICMPPacket(byteOffsetToEthernetPayload, bytes, tv); break; case (int)IPProtocol.IPProtocolType.IGMP: parsedPacket = new IGMPPacket(byteOffsetToEthernetPayload, bytes, tv); break; case (int)IPProtocol.IPProtocolType.TCP: parsedPacket = new TCPPacket(byteOffsetToEthernetPayload, bytes, tv); break; case (int)IPProtocol.IPProtocolType.UDP: parsedPacket = new UDPPacket(byteOffsetToEthernetPayload, bytes, tv); break; // unidentified ip.. default: parsedPacket = new IPPacket(byteOffsetToEthernetPayload, bytes, tv); break; } // check that the parsed packet is valid if (!parsedPacket.IsValid(out errorString)) { throw new PcapException(errorString); } else { return(parsedPacket); } } catch { // error parsing the specific ip packet type, parse as a generic IPPacket parsedPacket = new IPPacket(byteOffsetToEthernetPayload, bytes, tv); // check that the parsed packet is valid if (!parsedPacket.IsValid(out errorString)) { throw new PcapException(errorString); } else { return(parsedPacket); } } // ethernet level code not recognized, default to anonymous packet.. default: parsedPacket = new EthernetPacket(byteOffsetToEthernetPayload, bytes, tv); break; } return(parsedPacket); } catch { // we know we have at least an ethernet packet, so return that return(new EthernetPacket(byteOffsetToEthernetPayload, bytes, tv)); } }
public bool connect(IPEndPoint ipEnd, int port) { int lLen = EthernetFields_Fields.ETH_HEADER_LEN; //SYN packet creation #region Various Initializations ARP arper = new ARP(); var bytes = new byte[54]; var tcp = new TCPPacket(lLen, bytes, true) { IPVersion = IPPacket.IPVersions.IPv4 }; #endregion #region Ethernet Fields tcp.SourceHwAddress = _dev.Interface.MacAddress; arper.DeviceName = _dev.Name; arper.LocalIP = _dev.Interface.Addresses[1].Addr.ipAddress; arper.LocalMAC = _dev.Interface.MacAddress; //MAC address of gateway is provided by arp protocol tcp.DestinationHwAddress = arper.Resolve(_gatewayAddr,_dev.Name); tcp.EthernetProtocol = EthernetPacket.EtherType.IP; #endregion #region IP Fields tcp.DestinationAddress = ipEnd.Address; tcp.SourceAddress = _dev.Interface.Addresses[1].Addr.ipAddress; tcp.IPProtocol = IPProtocol.IPProtocolType.TCP; tcp.TimeToLive = 20; tcp.ipv4.Id = 100; tcp.ipv4.IPTotalLength = bytes.Length - lLen; tcp.ipv4.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN; #endregion #region TCP Fields tcp.SourcePort = 2222; tcp.DestinationPort = port; tcp.Syn = true; tcp.WindowSize = 555; tcp.SequenceNumber = 0; tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN; #endregion //Headers checksum calculations tcp.ipv4.ComputeIPChecksum(); tcp.ComputeTCPChecksum(); _dev.Open(false, 20); _dev.SetFilter("ip src " + tcp.DestinationAddress + " and tcp src port " + tcp.DestinationPort + " and tcp dst port " + tcp.SourcePort); //Send the packet Console.Write("Sending SYN packet: " + tcp + "..."); _dev.SendPacket(tcp); Console.WriteLine("SYN Packet sent."); TCPPacket reply = null; var watch = new Stopwatch(); bool received = false; watch.Start(); //Condition including timeout check. while (watch.ElapsedMilliseconds < _timeout && received != true) { if ((reply = (TCPPacket) _dev.GetNextPacket()) != null) { Console.WriteLine("SYN ACK Reply received: " + reply); received = true; } } //A reply hasn't returned if (!received) { _dev.Close(); throw new Exception("TIME_OUT"); } //Remote host reported closed connection if (reply.Rst) { _dev.Close(); throw new Exception("CLOSED"); } //Remote host reported opened connection if (reply.Ack) { tcp.Syn = false; tcp.Rst = true; tcp.WindowSize = 0; tcp.ipv4.ComputeIPChecksum(); tcp.ComputeTCPChecksum(); Console.Write("Sending RST packet: " + tcp + "..."); _dev.SendPacket(tcp); Console.WriteLine("RST Packet sent."); _dev.Close(); } return true; }
internal void BufferTCPPacket(TCPPacket pTCPPacket) { if (pTCPPacket.Fin || pTCPPacket.Rst) { mTerminated = true; Text += " (Terminated)"; return; } if (pTCPPacket.Syn && !pTCPPacket.Ack) { mLocalPort = (ushort)pTCPPacket.SourcePort; mRemotePort = (ushort)pTCPPacket.DestinationPort; mOutboundSequence = (uint)(pTCPPacket.SequenceNumber + 1); Text = "Port " + mLocalPort.ToString(); return; } if (pTCPPacket.Syn && pTCPPacket.Ack) { mInboundSequence = (uint)(pTCPPacket.SequenceNumber + 1); return; } if (pTCPPacket.PayloadDataLength == 0) return; if (!gotKey) { byte[] tcpData = pTCPPacket.TCPData; if (BitConverter.ToUInt16(tcpData, 1) != 0x0807) { this.Close(); mInboundSequence += (uint)tcpData.Length; //not valid xorkey return; } ushort xorKey = BitConverter.ToUInt16(tcpData, 3); mOutboundStream = new FiestaStream(true, xorKey); mInboundStream = new FiestaStream(false, 0); gotKey = true; mInboundSequence += (uint)tcpData.Length; return; } if (pTCPPacket.SourcePort == mLocalPort) ProcessTCPPacket(pTCPPacket, ref mOutboundSequence, mOutboundBuffer, mOutboundStream); //process fromclient else ProcessTCPPacket(pTCPPacket, ref mInboundSequence, mInboundBuffer, mInboundStream); //process fromserver }
internal static void UpdateTcpNode(TreeView treeView, TCPPacket tcpPacket) { TreeNode tcpNode = treeView.Nodes["TCP"]; if (tcpNode == null) { tcpNode = AddTcpNode(treeView); } tcpNode.Text = String.Format("Transmission Control Protocol, Src port: {0}, Dst port: {1}", tcpPacket.SourcePort, tcpPacket.DestinationPort); tcpNode.Nodes["SrcPort"].Text = String.Format("Source port: {0}", tcpPacket.SourcePort); tcpNode.Nodes["DstPort"].Text = String.Format("Destination port: {0}", tcpPacket.DestinationPort); // If the SYN flag is set, then this is the initial sequence number - ISN tcpNode.Nodes["SeqNumber"].Text = String.Format("Sequence number: {0}{1}", tcpPacket.SequenceNumber, tcpPacket.Syn ? " (ISN)" : String.Empty); // If the ACK flag is set, only then we have a valid value in // the acknowlegement field if (tcpPacket.Ack) { if (tcpNode.Nodes["AckNumber"] == null) { int seqNumberIndex = tcpNode.Nodes["SeqNumber"].Index; tcpNode.Nodes.Insert(seqNumberIndex + 1, "AckNumber", String.Empty); } tcpNode.Nodes["AckNumber"].Text = String.Format("Acknowledgment number: {0}", tcpPacket.AcknowledgmentNumber); } else if (tcpNode.Nodes["AckNumber"] != null) { tcpNode.Nodes["AckNumber"].Remove(); } tcpNode.Nodes["HeaderLength"].Text = String.Format("Header length: {0} bytes", tcpPacket.HeaderLength); TreeNode flagsNode = tcpNode.Nodes["Flags"]; flagsNode.Text = String.Format("Flags: 0x{0:X2}", tcpPacket.AllFlags & 0xff); flagsNode.Nodes["CWR"].Text = String.Format("{0} . . . . . . . = Congestion Window Reduced: {1}", tcpPacket.CWR ? "1" : "0", tcpPacket.CWR ? "Set" : "Not set"); flagsNode.Nodes["ECN"].Text = String.Format(". {0} . . . . . . = ECN-Echo: {1}", tcpPacket.ECN ? "1" : "0", tcpPacket.ECN ? "Set" : "Not set"); flagsNode.Nodes["Urg"].Text = String.Format(". . {0} . . . . . = Urgent: {1}", tcpPacket.Urg ? "1" : "0", tcpPacket.Urg ? "Set" : "Not set"); flagsNode.Nodes["Ack"].Text = String.Format(". . . {0} . . . . = Acknowledgement: {1}", tcpPacket.Ack ? "1" : "0", tcpPacket.Ack ? "Set" : "Not set"); flagsNode.Nodes["Psh"].Text = String.Format(". . . . {0} . . . = Push: {1}", tcpPacket.Psh ? "1" : "0", tcpPacket.Psh ? "Set" : "Not set"); flagsNode.Nodes["Rst"].Text = String.Format(". . . . . {0} . . = Reset: {1}", tcpPacket.Rst ? "1" : "0", tcpPacket.Rst ? "Set" : "Not set"); flagsNode.Nodes["Syn"].Text = String.Format(". . . . . . {0} . = Syn: {1}", tcpPacket.Syn ? "1" : "0", tcpPacket.Syn ? "Set" : "Not set"); flagsNode.Nodes["Fin"].Text = String.Format(". . . . . . . {0} = Fin: {1}", tcpPacket.Fin ? "1" : "0", tcpPacket.Fin ? "Set" : "Not set"); tcpNode.Nodes["WindowSize"].Text = String.Format("Window size: {0} bytes", tcpPacket.WindowSize); tcpNode.Nodes["Checksum"].Text = String.Format("Checksum: 0x{0:X4} ({1})", tcpPacket.TCPChecksum, tcpPacket.ValidTCPChecksum ? "correct" : "incorrect"); // If the URG flag is set, only then we have a valid // value in the urgent pointer field if (tcpPacket.Urg) { if (tcpNode.Nodes["UrgPtr"] == null) { tcpNode.Nodes.Add("UrgPtr", String.Empty); } tcpNode.Nodes["UrgPtr"].Text = String.Format("Urgent pointer: {0}", tcpPacket.getUrgentPointer()); } else if (tcpNode.Nodes["UrgPtr"] != null) { tcpNode.Nodes["UrgPtr"].Remove(); } }
private void ProcessTCPPacket(TCPPacket pTCPPacket, ref uint pSequence, Dictionary<uint, byte[]> pBuffer, FiestaStream pStream) { 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.TCPData; } if (pTCPPacket.SequenceNumber < pSequence) { int difference = (int)(pSequence - pTCPPacket.SequenceNumber); if (difference > 0) { byte[] data = pTCPPacket.TCPData; if (data.Length > difference) { pStream.Append(data, difference, data.Length - difference); pSequence += (uint)(data.Length - difference); } } } else if (pTCPPacket.SequenceNumber == pSequence) { byte[] data = pTCPPacket.TCPData; pStream.Append(data); pSequence += (uint)data.Length; } FiestaPacket packet; try { while ((packet = pStream.Read(pTCPPacket.Timeval.Date)) != null) { mPackets.Add(packet); Definition definition = Config.Instance.Definitions.Find(d => d.Build == 1 && d.Outbound == packet.Outbound && d.Opcode == packet.Opcode); if (!mOpcodes.Exists(kv => kv.Item1 == packet.Outbound && kv.Item2 == packet.Opcode)) { mOpcodes.Add(new Tuple<bool, ushort>(packet.Outbound, packet.Opcode)); } if (definition != null && definition.Ignore) continue; if (!FilterOut(packet)) { mPacketList.Items.Add(packet); } if (mPacketList.SelectedItems.Count == 0) packet.EnsureVisible(); } } catch (Exception exc) { OutputForm output = new OutputForm("Packet Error"); output.Append(exc.ToString()); output.Show(DockPanel, new Rectangle(MainForm.Location, new Size(400, 400))); mTerminated = true; Text += " (Terminated)"; } }
/// <summary> Convert captured packet data into an object.</summary> public static Packet dataToPacket(LinkLayers linkType, byte[] bytes, Timeval tv) { EthernetPacketType ethProtocol; // retrieve the length of the headers associated with this link layer type. // this length is the offset to the header embedded in the packet. int byteOffsetToEthernetPayload = LinkLayer.LinkLayerLength(linkType); // extract the protocol code for the type of header embedded in the // link-layer of the packet int offset = LinkLayer.ProtocolOffset(linkType); if (offset == -1) { // if there is no embedded protocol, assume IpV4 ethProtocol = EthernetPacketType.IPv4; } else { ethProtocol = (EthernetPacketType)ArrayHelper.extractInteger(bytes, offset, EthernetFields_Fields.ETH_CODE_LEN); } string errorString; Packet parsedPacket = null; try { // try to recognize the ethernet type.. switch (ethProtocol) { // arp case EthernetPacketType.ARP: parsedPacket = new ARPPacket(byteOffsetToEthernetPayload, bytes, tv); break; case EthernetPacketType.IPv6: case EthernetPacketType.IPv4: try { // ethernet level code is recognized as IP, figure out what kind.. int ipProtocol = IPProtocol.extractProtocol(byteOffsetToEthernetPayload, bytes); switch (ipProtocol) { case (int)IPProtocol.IPProtocolType.ICMP: parsedPacket = new ICMPPacket(byteOffsetToEthernetPayload, bytes, tv); break; case (int)IPProtocol.IPProtocolType.IGMP: parsedPacket = new IGMPPacket(byteOffsetToEthernetPayload, bytes, tv); break; case (int)IPProtocol.IPProtocolType.TCP: parsedPacket = new TCPPacket(byteOffsetToEthernetPayload, bytes, tv); break; case (int)IPProtocol.IPProtocolType.UDP: parsedPacket = new UDPPacket(byteOffsetToEthernetPayload, bytes, tv); break; // unidentified ip.. default: parsedPacket = new IPPacket(byteOffsetToEthernetPayload, bytes, tv); break; } // check that the parsed packet is valid if (!parsedPacket.IsValid(out errorString)) { throw new PcapException(errorString); } else { return parsedPacket; } } catch { // error parsing the specific ip packet type, parse as a generic IPPacket parsedPacket = new IPPacket(byteOffsetToEthernetPayload, bytes, tv); // check that the parsed packet is valid if (!parsedPacket.IsValid(out errorString)) { throw new PcapException(errorString); } else { return parsedPacket; } } // ethernet level code not recognized, default to anonymous packet.. default: parsedPacket = new EthernetPacket(byteOffsetToEthernetPayload, bytes, tv); break; } return parsedPacket; } catch { // we know we have at least an ethernet packet, so return that return new EthernetPacket(byteOffsetToEthernetPayload, bytes, tv); } }