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); } }
/// <summary> /// Construct a new ethernet packet from source and destination mac addresses /// </summary> public EthernetPacket(PhysicalAddress SourceHwAddress, PhysicalAddress DestinationHwAddress, EthernetPacketType ethernetPacketType, byte[] EthernetPayload) { int ethernetPayloadLength = 0; if (EthernetPayload != null) { ethernetPayloadLength = EthernetPayload.Length; } _bytes = new byte[EthernetFields_Fields.ETH_HEADER_LEN + ethernetPayloadLength]; _ethernetHeaderLength = EthernetFields_Fields.ETH_HEADER_LEN; _ethPayloadOffset = _ethernetHeaderLength; // if we have a payload, copy it into the byte array if (EthernetPayload != null) { Array.Copy(EthernetPayload, 0, _bytes, EthernetFields_Fields.ETH_HEADER_LEN, EthernetPayload.Length); } // set the instance values this.SourceHwAddress = SourceHwAddress; this.DestinationHwAddress = DestinationHwAddress; this.EthernetProtocol = ethernetPacketType; }
internal static PacketOrByteArraySegment ParseEncapsulatedBytes(ByteArraySegment Header, EthernetPacketType Type, PosixTimeval Timeval) { ByteArraySegment segment = Header.EncapsulatedBytes(); PacketOrByteArraySegment segment2 = new PacketOrByteArraySegment(); EthernetPacketType type = Type; if (type != EthernetPacketType.IpV4) { if (type == EthernetPacketType.Arp) { segment2.ThePacket = new ARPPacket(segment.Bytes, segment.Offset, Timeval); return(segment2); } if (type == EthernetPacketType.IpV6) { segment2.ThePacket = new IPv6Packet(segment.Bytes, segment.Offset, Timeval); return(segment2); } if (type == EthernetPacketType.PointToPointProtocolOverEthernetSessionStage) { segment2.ThePacket = new PPPoEPacket(segment.Bytes, segment.Offset, Timeval); return(segment2); } if (type == EthernetPacketType.LLDP) { segment2.ThePacket = new LLDPPacket(segment.Bytes, segment.Offset, Timeval); return(segment2); } segment2.TheByteArraySegment = segment; return(segment2); } segment2.ThePacket = new IPv4Packet(segment.Bytes, segment.Offset, Timeval); return(segment2); }
public static string GetEtherTypeDescription(EthernetPacketType etherType) { if (ethernetTypes.ContainsKey(etherType)) { return(ethernetTypes[etherType].ToString()); } else { return("unknown"); } }
public EthernetPacket(PhysicalAddress SourceHwAddress, PhysicalAddress DestinationHwAddress, EthernetPacketType ethernetPacketType) : base(new PosixTimeval()) { int offset = 0; int headerLength = EthernetFields.HeaderLength; byte[] bytes = new byte[headerLength]; base.header = new ByteArraySegment(bytes, offset, headerLength); this.SourceHwAddress = SourceHwAddress; this.DestinationHwAddress = DestinationHwAddress; this.Type = ethernetPacketType; }
public void SetComboBoxSelectedIndex(EthernetPacketType ethernetType) { for (int i = 0; i < comboBoxEthernetProtocols.Items.Count; i++) { object item = comboBoxEthernetProtocols.Items[i]; if ((EthernetPacketType)((DictionaryEntry)item).Key == ethernetType) { comboBoxEthernetProtocols.SelectedIndex = i; break; } } }
/// <summary> /// Used by the EthernetPacket constructor. Located here because the LinuxSLL constructor /// also needs to perform the same operations as it contains an ethernet type /// </summary> /// <param name="Header"> /// A <see cref="ByteArraySegment"/> /// </param> /// <param name="Type"> /// A <see cref="EthernetPacketType"/> /// </param> /// <returns> /// A <see cref="PacketOrByteArraySegment"/> /// </returns> internal static PacketOrByteArraySegment ParseEncapsulatedBytes(ByteArraySegment Header, EthernetPacketType Type) { // slice off the payload var payload = Header.EncapsulatedBytes(); log.DebugFormat("payload {0}", payload.ToString()); var payloadPacketOrData = new PacketOrByteArraySegment(); // parse the encapsulated bytes switch (Type) { case EthernetPacketType.IpV4: payloadPacketOrData.ThePacket = new IPv4Packet(payload); break; case EthernetPacketType.IpV6: payloadPacketOrData.ThePacket = new IPv6Packet(payload); break; case EthernetPacketType.Arp: payloadPacketOrData.ThePacket = new ARPPacket(payload); break; case EthernetPacketType.LLDP: payloadPacketOrData.ThePacket = new LLDPPacket(payload); break; case EthernetPacketType.PointToPointProtocolOverEthernetSessionStage: payloadPacketOrData.ThePacket = new PPPoEPacket(payload); break; case EthernetPacketType.WakeOnLan: payloadPacketOrData.ThePacket = new WakeOnLanPacket(payload); break; case EthernetPacketType.VLanTaggedFrame: payloadPacketOrData.ThePacket = new Ieee8021QPacket(payload); break; default: // consider the sub-packet to be a byte array payloadPacketOrData.TheByteArraySegment = payload; break; } return(payloadPacketOrData); }
/// <summary> /// Construct a new ethernet packet from source and destination mac addresses /// </summary> public EthernetPacket(PhysicalAddress SourceHwAddress, PhysicalAddress DestinationHwAddress, EthernetPacketType ethernetPacketType) { // allocate memory for this packet int offset = 0; int length = EthernetFields.HeaderLength; var headerBytes = new byte[length]; header = new ByteArraySegment(headerBytes, offset, length); // set the instance values this.SourceHwAddress = SourceHwAddress; this.DestinationHwAddress = DestinationHwAddress; this.Type = ethernetPacketType; }
private static Boolean ParseLinkLayer(ReadOnlySpan <Byte> linkData, LinkLayers linkType, out ReadOnlySpan <Byte> networkData, out EthernetPacketType ethernetProtocol) { networkData = ArraySegment <Byte> .Empty; ethernetProtocol = EthernetPacketType.None; switch (linkType) { case LinkLayers.Ethernet: var ethernetTypePosition = EthernetFields.TypePosition; ethernetProtocol = (EthernetPacketType)((linkData[ethernetTypePosition] << 8) | linkData[ethernetTypePosition + 1]); networkData = linkData.Slice(EthernetFields.HeaderLength, linkData.Length - EthernetFields.HeaderLength); // 4B Ethernet trailer (CRC) return(true); default: return(false); } }
/// <summary> /// Used by the EthernetPacket constructor. Located here because the LinuxSLL constructor /// also needs to perform the same operations as it contains an ethernet type /// </summary> /// <param name="Header"> /// A <see cref="ByteArraySegment"/> /// </param> /// <param name="Type"> /// A <see cref="EthernetPacketType"/> /// </param> /// <returns> /// A <see cref="PacketOrByteArraySegment"/> /// </returns> internal static PacketOrByteArraySegment ParseEncapsulatedBytes(ByteArraySegment Header, EthernetPacketType Type) { // slice off the payload var payload = Header.EncapsulatedBytes(); var payloadPacketOrData = new PacketOrByteArraySegment(); // parse the encapsulated bytes switch (Type) { case EthernetPacketType.IpV4: payloadPacketOrData.ThePacket = new IPv4Packet(payload); break; case EthernetPacketType.IpV6: payloadPacketOrData.ThePacket = new IPv6Packet(payload); break; case EthernetPacketType.Arp: payloadPacketOrData.ThePacket = new ARPPacket(payload); break; case EthernetPacketType.LLDP: payloadPacketOrData.ThePacket = new LLDPPacket(payload); break; case EthernetPacketType.PointToPointProtocolOverEthernetSessionStage: payloadPacketOrData.ThePacket = new PPPoEPacket(payload); break; default: // consider the sub-packet to be a byte array payloadPacketOrData.TheByteArraySegment = payload; break; } return(payloadPacketOrData); }
public void injectRemotePacket(ref byte[] data, PhysicalAddress dstMAC, PhysicalAddress srcMAC, ref xbs_node sending_node) { Packet p = null; ARPPacket p_arp = null; IPv4Packet p_ipv4 = null; ICMPv4Packet p_icmp = null; UdpPacket p_udp = null; TcpPacket p_tcp = null; IPAddress source_IP = null; int srcMac_hash = srcMAC.GetHashCode(); // collect all injected source MACs. sniffer needs this to filter packets out lock (injected_macs_hash) { if (!injected_macs_hash.Contains(srcMac_hash)) { injected_macs_hash.Add(srcMac_hash); addMacToKnownMacListFromRemoteNodes(srcMAC); } } if (sending_node != null) { if (sending_node.addXbox(srcMAC)) { node_list.listHasJustChanged(); } } try { p = Packet.ParsePacket(LinkLayers.Ethernet, data); } catch (PcapException pcex) { #if DEBUG xbs_messages.addDebugMessage("!! ERROR! parse packet failed in injectRemotePacket (1): " + pcex.ToString(), xbs_message_sender.SNIFFER, xbs_message_type.ERROR); #endif return; } catch (NotImplementedException niex) { #if DEBUG xbs_messages.addDebugMessage("!! ERROR! parse packet failed in injectRemotePacket (2): " + niex.ToString(), xbs_message_sender.SNIFFER, xbs_message_type.ERROR); #endif return; } // DETERMINE PACKET TYPE if (p.PayloadPacket is IPv4Packet) { p_ipv4 = p.PayloadPacket as IPv4Packet; source_IP = p_ipv4.SourceAddress; if (p_ipv4.PayloadPacket is UdpPacket) { p_udp = p_ipv4.PayloadPacket as UdpPacket; } else if (p_ipv4.PayloadPacket is TcpPacket) { p_tcp = p_ipv4.PayloadPacket as TcpPacket; } } else if (p.PayloadPacket is ARPPacket) { p_arp = p.PayloadPacket as ARPPacket; source_IP = p_arp.SenderProtocolAddress; } else if (p.PayloadPacket is ICMPv4Packet) { p_icmp = p.PayloadPacket as ICMPv4Packet; } else { // UNKNOWN OR UNSUPPORTED PACKET TYPE #if DEBUG //xbs_messages.addDebugMessage("?? WARNING! unknown incoming packet type: " + p.ToString(), xbs_message_sender.SNIFFER, xbs_message_type.WARNING); #endif return; } // filter packet if needed if (is_injected_packet_to_be_filtered(ref p_arp, ref p_ipv4, ref p_udp, ref p_tcp)) { #if DEBUG xbs_messages.addDebugMessage("i> filtered packet: " + p, xbs_message_sender.SNIFFER); #endif return; } // add IP to device from node if (sending_node != null && source_IP != null) { if (sending_node.addIPtoXbox(srcMAC, source_IP)) { #if DEBUG xbs_messages.addDebugMessage("i> added new IP " + source_IP + " to xbox " + srcMAC + " for node " + sending_node, xbs_message_sender.SNIFFER); #endif node_list.listHasJustChanged(); } } #if DEBUG xbs_messages.addDebugMessage("i> " + p, xbs_message_sender.SNIFFER); #endif if (NAT.NAT_enabled) { #if DEBUG System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); #endif EthernetPacketType p_type = NAT.NAT_incoming_packet_PacketDotNet(ref data, dstMAC, srcMAC, ref p, ref p_ipv4, ref p_arp); #if DEBUG stopWatch.Stop(); if (p_type == EthernetPacketType.IpV4) { xbs_sniffer_statistics.NAT_callCount++; if (xbs_sniffer_statistics.NAT_callCount > 1) { xbs_sniffer_statistics.NAT_timeInCode += (UInt64)stopWatch.ElapsedTicks; UInt32 average = (UInt32)(xbs_sniffer_statistics.NAT_timeInCode / (xbs_sniffer_statistics.NAT_callCount - 1)); double average_ms = new TimeSpan(average).TotalMilliseconds; xbs_messages.addDebugMessage("- NAT time: " + stopWatch.ElapsedTicks + "t/" + stopWatch.ElapsedMilliseconds + "ms | NAT count: " + (xbs_sniffer_statistics.NAT_callCount - 1) + " Total Time: " + xbs_sniffer_statistics.NAT_timeInCode + "t=> Average " + average + "t / " + average_ms + "ms", xbs_message_sender.SNIFFER); } } p = Packet.ParsePacket(LinkLayers.Ethernet, data); xbs_messages.addDebugMessage("i> " + p, xbs_message_sender.SNIFFER); #endif } // inject the packet try { pdev.SendPacket(data, data.Length); } catch (PcapException pex) { xbs_messages.addInfoMessage("!! error while injecting packet from " + srcMAC + " to " + dstMAC + " (" + data.Length + ") : " + pex.Message, xbs_message_sender.SNIFFER, xbs_message_type.FATAL_ERROR); } catch (ArgumentException aex) { xbs_messages.addInfoMessage("!! error while injecting packet from " + srcMAC + " to " + dstMAC + " (" + data.Length + ") : " + aex.Message, xbs_message_sender.SNIFFER, xbs_message_type.FATAL_ERROR); } }
public void dispatch_packet(ref RawCapture rawPacket) { byte[] src_mac = new byte[6]; byte[] dst_mac = new byte[6]; byte[] packet_data = rawPacket.Data; // copy source and destination MAC addresses from sniffed packet Buffer.BlockCopy(rawPacket.Data, 0, dst_mac, 0, 6); PhysicalAddress dstMAC = new PhysicalAddress(dst_mac); Buffer.BlockCopy(rawPacket.Data, 6, src_mac, 0, 6); PhysicalAddress srcMAC = new PhysicalAddress(src_mac); #if DEBUG xbs_messages.addDebugMessage("s> " + srcMAC + "=>" + dstMAC + "Len:" + rawPacket.Data.Length, xbs_message_sender.SNIFFER); Packet p = Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); xbs_messages.addDebugMessage("s> " + p, xbs_message_sender.SNIFFER); #endif // if sniffed packet has MAC of packet we injected, discard bool is_injected_packet = false; lock (injected_macs_hash) is_injected_packet = injected_macs_hash.Contains(srcMAC.GetHashCode()); if (is_injected_packet) { return; } if (NAT.NAT_enabled) { #if DEBUG System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); #endif EthernetPacketType p_type = NAT.deNAT_outgoing_packet_PacketDotNet(ref packet_data, dstMAC, srcMAC); #if DEBUG stopWatch.Stop(); if (p_type == EthernetPacketType.IpV4) { xbs_sniffer_statistics.deNAT_callCount++; if (xbs_sniffer_statistics.deNAT_callCount > 1) { xbs_sniffer_statistics.deNAT_timeInCode += (UInt64)stopWatch.ElapsedTicks; UInt32 average = (UInt32)(xbs_sniffer_statistics.deNAT_timeInCode / (xbs_sniffer_statistics.deNAT_callCount - 1)); double average_ms = new TimeSpan(average).TotalMilliseconds; xbs_messages.addDebugMessage("- deNAT time: " + stopWatch.ElapsedTicks + " deNAT count: " + (xbs_sniffer_statistics.deNAT_callCount - 1) + " Total Time: " + xbs_sniffer_statistics.deNAT_timeInCode + "=> " + average + " / " + average_ms + "ms", xbs_message_sender.SNIFFER); } } p = Packet.ParsePacket(rawPacket.LinkLayerType, packet_data); xbs_messages.addDebugMessage("s> " + p, xbs_message_sender.SNIFFER); #endif } // count the sniffed packets from local xboxs xbs_sniffer_statistics.packet_count++; // find node with destination MAC Address in network and send packet xbs_node node = node_list.distributeDataPacket(dstMAC, packet_data); int srcMac_hash = srcMAC.GetHashCode(); bool pdevfilter_needs_change = false; lock (sniffed_macs_hash) { if (!sniffed_macs_hash.Contains(srcMac_hash)) { sniffed_macs_hash.Add(srcMac_hash); lock (sniffed_macs) sniffed_macs.Add(srcMAC); pdevfilter_needs_change = true; } } if (pdevfilter_needs_change) { setPdevFilter(); } }
private void replaceDestinationIP(ref byte[] data, EthernetPacketType ethernet_packet_type, ref byte[] new_destinationIP) { int offset = (ethernet_packet_type == EthernetPacketType.Arp) ? ARP_HEADER_DESTINATION_OFFSET : IP_HEADER_DESTINATION_OFFSET; Buffer.BlockCopy(new_destinationIP, 0, data, offset, 4); }
private void replaceDestinationIpWithOriginalIP(ref byte[] data, EthernetPacketType ethernet_packet_type, ref xbs_nat_entry nat_entry) { replaceDestinationIP(ref data, ethernet_packet_type, ref nat_entry.original_source_ip_bytes); }
private bool isIpOrArpPacket(EthernetPacketType ethernet_packet_type) { return(ethernet_packet_type == EthernetPacketType.IpV4 || ethernet_packet_type == EthernetPacketType.Arp); }
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); } }
internal static PacketOrByteArraySegment ParseEncapsulatedBytes(ByteArraySegment Header, EthernetPacketType Type, PosixTimeval Timeval) { ByteArraySegment segment = Header.EncapsulatedBytes(); PacketOrByteArraySegment segment2 = new PacketOrByteArraySegment(); EthernetPacketType type = Type; if (type != EthernetPacketType.IpV4) { if (type == EthernetPacketType.Arp) { segment2.ThePacket = new ARPPacket(segment.Bytes, segment.Offset, Timeval); return segment2; } if (type == EthernetPacketType.IpV6) { segment2.ThePacket = new IPv6Packet(segment.Bytes, segment.Offset, Timeval); return segment2; } if (type == EthernetPacketType.PointToPointProtocolOverEthernetSessionStage) { segment2.ThePacket = new PPPoEPacket(segment.Bytes, segment.Offset, Timeval); return segment2; } if (type == EthernetPacketType.LLDP) { segment2.ThePacket = new LLDPPacket(segment.Bytes, segment.Offset, Timeval); return segment2; } segment2.TheByteArraySegment = segment; return segment2; } segment2.ThePacket = new IPv4Packet(segment.Bytes, segment.Offset, Timeval); return segment2; }
private void replaceSourceIpWithNATSourceIP(ref byte[] data, EthernetPacketType ethernet_packet_type, ref xbs_nat_entry nat_entry) { int offset = (ethernet_packet_type == EthernetPacketType.Arp) ? ARP_HEADER_SOURCE_OFFSET : IP_HEADER_SOURCE_OFFSET; Buffer.BlockCopy(nat_entry.natted_source_ip_bytes, 0, data, offset, 4); }
/* * public EthernetPacketType NAT_incoming_packet(ref byte[] data, PhysicalAddress dstMAC, PhysicalAddress srcMAC) * { * EthernetPacketType ethernet_packet_type = getEthernetPacketType(ref data); * if (!isIpOrArpPacket(ethernet_packet_type)) * return ethernet_packet_type; * xbs_nat_entry nat_entry; * lock (NAT_list) * { * if (!NAT_list.TryGetValue(srcMAC, out nat_entry)) * { * IPAddress sourceIP = getSourceIPFromRawPacketData(ref data, ethernet_packet_type); * if (sourceIP.Equals(ip_zero)) * return ethernet_packet_type; * IPAddress destinationIP = getDestinationIPFromRawPacketData(ref data, ethernet_packet_type); * nat_entry = ip_pool.requestIP( sourceIP, srcMAC ); * if (nat_entry == null) * { * xbs_messages.addInfoMessage("!! % out of NAT IPs. Could not nat incoming packet"); * return ethernet_packet_type; * } * NAT_list.Add(srcMAC, nat_entry); #if DEBUG * xbs_messages.addDebugMessage("% new device in NAT list: " + srcMAC + " " + nat_entry.original_source_ip + "=>" + nat_entry.natted_source_ip); #endif * } * else * { #if DEBUG * xbs_messages.addDebugMessage("% found device in NAT list: " + srcMAC + " " + nat_entry.original_source_ip + "=>" + nat_entry.natted_source_ip); #endif * } * } * replaceSourceIpWithNATSourceIP(ref data, ethernet_packet_type, ref nat_entry); * if (ethernet_packet_type == EthernetPacketType.IpV4) * { * if (dstMAC.Equals(broadcast_mac) && nat_entry.natted_broadcast!=null) * replaceBroadcastIPAddress(ref data, ref nat_entry.natted_broadcast_bytes); * updateIPChecksums(ref data); * } * return ethernet_packet_type; * } */ public EthernetPacketType NAT_incoming_packet_PacketDotNet(ref byte[] data, PhysicalAddress dstMAC, PhysicalAddress srcMAC, ref Packet p, ref IPv4Packet p_IPV4, ref ARPPacket p_ARP) { xbs_nat_entry nat_entry; EthernetPacketType p_type = ((EthernetPacket)p).Type; if (p_type != EthernetPacketType.IpV4 && p_type != EthernetPacketType.Arp) { return(p_type); } lock (NAT_list) { if (!NAT_list.TryGetValue(srcMAC, out nat_entry)) { IPAddress sourceIP = (p_IPV4 != null) ? p_IPV4.SourceAddress : p_ARP.SenderProtocolAddress; if (sourceIP.Equals(ip_zero)) { return(p_type); } IPAddress destinationIP = (p_IPV4 != null) ? p_IPV4.DestinationAddress : p_ARP.TargetProtocolAddress; nat_entry = ip_pool.requestIP(sourceIP, srcMAC); if (nat_entry == null) { if (!natIPpoolOverflow_warning_shown) { natIPpoolOverflow_warning_shown = true; xbs_messages.addInfoMessage("!! % out of NAT IPs. Could not NAT incoming packet", xbs_message_sender.NAT, xbs_message_type.WARNING); } return(p_type); } else { natIPpoolOverflow_warning_shown = false; NAT_list.Add(srcMAC, nat_entry); #if DEBUG xbs_messages.addDebugMessage("% new device in NAT list: " + srcMAC + " " + nat_entry.original_source_ip + "=>" + nat_entry.natted_source_ip, xbs_message_sender.NAT); #endif } } else { #if DEBUG xbs_messages.addDebugMessage("% found device in NAT list: " + srcMAC + " " + nat_entry.original_source_ip + "=>" + nat_entry.natted_source_ip, xbs_message_sender.NAT); #endif } } if (p_IPV4 != null) { p_IPV4.SourceAddress = nat_entry.natted_source_ip; if (dstMAC.Equals(broadcast_mac) && nat_entry.natted_broadcast != null) { p_IPV4.DestinationAddress = nat_entry.natted_broadcast; } p_IPV4.UpdateIPChecksum(); if (p_IPV4.Protocol == IPProtocolType.UDP) { UdpPacket p_UDP = (UdpPacket)p_IPV4.PayloadPacket; if (NAT_enablePS3mode) { bool ret = PS3_replaceInfoResponse_hostAddr(dstMAC, ref p_UDP, nat_entry.natted_source_ip); if (!ret) { ret = PS3_replaceClientAnswer_hostAddr(dstMAC, ref p_UDP, nat_entry.natted_source_ip, nat_entry.original_source_ip); } } p_UDP.UpdateUDPChecksum(); } else if (p_IPV4.Protocol == IPProtocolType.TCP) { ((TcpPacket)p_IPV4.PayloadPacket).UpdateTCPChecksum(); } } else { p_ARP.SenderProtocolAddress = nat_entry.natted_source_ip; } data = p.BytesHighPerformance.ActualBytes(); return(p_type); }
/* * public EthernetPacketType deNAT_outgoing_packet(ref byte[] data, PhysicalAddress dstMAC, PhysicalAddress srcMAC) * { * EthernetPacketType ethernet_packet_type = getEthernetPacketType(ref data); * if (!isIpOrArpPacket(ethernet_packet_type)) * return ethernet_packet_type; * xbs_nat_entry nat_entry = null; * lock (NAT_list) * { * if (NAT_list.ContainsKey(dstMAC)) * nat_entry = NAT_list[dstMAC]; * } * * if (nat_entry != null) * { * replaceDestinationIpWithOriginalIP(ref data, ethernet_packet_type, ref nat_entry); * updateIPChecksums(ref data); * } * return ethernet_packet_type; * } */ public EthernetPacketType deNAT_outgoing_packet_PacketDotNet(ref byte[] data, PhysicalAddress dstMAC, PhysicalAddress srcMAC) { EthernetPacket p = (EthernetPacket)EthernetPacket.ParsePacket(LinkLayers.Ethernet, data); EthernetPacketType ethernet_packet_type = getEthernetPacketType(ref data); IPv4Packet p_IPV4 = null; ARPPacket p_ARP = null; bool packet_changed = false; if (ethernet_packet_type == EthernetPacketType.IpV4) { p_IPV4 = (IPv4Packet)p.PayloadPacket; } else if (ethernet_packet_type == EthernetPacketType.Arp) { p_ARP = (ARPPacket)p.PayloadPacket; } else { return(ethernet_packet_type); } xbs_nat_entry nat_entry = null; lock (NAT_list) { if (dstMAC.Equals(broadcast_mac)) { if (p_ARP != null) { foreach (xbs_nat_entry ne in NAT_list.Values) { if (ne.natted_source_ip.Equals(p_ARP.TargetProtocolAddress)) { nat_entry = ne; break; } } } } else if (NAT_list.ContainsKey(dstMAC)) { nat_entry = NAT_list[dstMAC]; } } #if DEBUG if (nat_entry != null) { xbs_messages.addDebugMessage("% found device in deNAT list: " + dstMAC + " " + nat_entry.natted_source_ip + "=>" + nat_entry.original_source_ip, xbs_message_sender.NAT); } #endif if (nat_entry != null) { if (p_IPV4 != null) { p_IPV4.DestinationAddress = nat_entry.original_source_ip; p_IPV4.UpdateIPChecksum(); if (p_IPV4.Protocol == IPProtocolType.UDP) { UdpPacket p_UDP = (UdpPacket)p_IPV4.PayloadPacket; if (NAT_enablePS3mode) { bool ret = PS3_replaceClientAnswer_hostAddr(dstMAC, ref p_UDP, nat_entry.original_source_ip, nat_entry.natted_source_ip); } p_UDP.UpdateUDPChecksum(); packet_changed = true; } else if (p_IPV4.Protocol == IPProtocolType.TCP) { ((TcpPacket)p_IPV4.PayloadPacket).UpdateTCPChecksum(); packet_changed = true; } } else if (p_ARP != null) { p_ARP.TargetProtocolAddress = nat_entry.original_source_ip; packet_changed = true; } } if (packet_changed) { data = p.BytesHighPerformance.ActualBytes(); } return((packet_changed) ? ethernet_packet_type : EthernetPacketType.None); }
public static EthernetPacket Packet(string ipsrc, string ipdes, int portsrc, int portdes, string macsrc, string macdes, EthernetPacketType packetType) { TcpPacket tcpPacket = new TcpPacket(ushort.Parse(portsrc.ToString()), ushort.Parse(portdes.ToString())); // ports # TCP Packet IPAddress IpSourceAddress = IPAddress.Parse(ipsrc); IPAddress IpDestinationAddress = IPAddress.Parse(ipdes); IPv4Packet ipPacket = new IPv4Packet(IpSourceAddress, IpDestinationAddress);// IP addresses # IP Packets string SourceMacAddress = macsrc; string DestinationMacAddress = macdes; //convert above value to a Physical Address PhysicalAddress MACsource = PhysicalAddress.Parse(SourceMacAddress); PhysicalAddress MACdestination = PhysicalAddress.Parse(DestinationMacAddress); EthernetPacket eth0Packet = new EthernetPacket(MACsource, MACdestination, packetType); // MAC address # Eth0 Packet // this below does Packet construction Encapsulation ipPacket.PayloadPacket = tcpPacket; eth0Packet.PayloadPacket = ipPacket; Console.WriteLine(eth0Packet.ToString()); // allows us to retrieve bytes from the packets byte[] packetBytes = eth0Packet.Bytes; return(eth0Packet); }
private IPAddress getDestinationIPFromRawPacketData(ref byte[] data, EthernetPacketType ethernet_packet_type) { int offset = (ethernet_packet_type == EthernetPacketType.Arp) ? ARP_HEADER_DESTINATION_OFFSET : IP_HEADER_DESTINATION_OFFSET; return(IpPacket.GetIPAddress(System.Net.Sockets.AddressFamily.InterNetwork, offset, data)); }
public static string GetEtherTypeDescription(EthernetPacketType etherType) { if (ethernetTypes.ContainsKey(etherType)) { return ethernetTypes[etherType].ToString(); } else { return "unknown"; } }
private void replaceSourceIpWithNATSourceIP( ref byte[] data, EthernetPacketType ethernet_packet_type, ref xbs_nat_entry nat_entry) { int offset = (ethernet_packet_type == EthernetPacketType.Arp) ? ARP_HEADER_SOURCE_OFFSET : IP_HEADER_SOURCE_OFFSET; Buffer.BlockCopy(nat_entry.natted_source_ip_bytes, 0, data, offset, 4); }
private IPAddress getDestinationIPFromRawPacketData(ref byte[] data, EthernetPacketType ethernet_packet_type) { int offset = (ethernet_packet_type == EthernetPacketType.Arp) ? ARP_HEADER_DESTINATION_OFFSET : IP_HEADER_DESTINATION_OFFSET; return IpPacket.GetIPAddress(System.Net.Sockets.AddressFamily.InterNetwork, offset, data); }
private bool isIpOrArpPacket(EthernetPacketType ethernet_packet_type) { return (ethernet_packet_type == EthernetPacketType.IpV4 || ethernet_packet_type == EthernetPacketType.Arp); }
//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); } }