Welcome to another edition of Saturday Scripting! This week, we’re diving into the world of network monitoring and automation with Python and Scapy. This post is tailored for experienced sysadmins who are looking to automate network tasks and gain deeper insights into network traffic. So, grab your favorite beverage, and let’s get scripting!

What is Scapy?

Scapy is a powerful Python library used for network packet manipulation. It allows you to send, sniff, dissect, and forge network packets, making it an invaluable tool for network analysis and security testing. Whether you’re troubleshooting network issues, performing security assessments, or automating routine tasks, Scapy has you covered.

Why Use Scapy for Network Monitoring?

1. Flexibility and Power

Scapy provides unparalleled control over network packets, allowing you to create customized scripts for specific tasks. Its flexibility enables you to handle complex scenarios that might be challenging with other tools.

2. Comprehensive Protocol Support

Scapy supports a wide range of network protocols, including Ethernet, IP, TCP, UDP, and many more. This extensive protocol support makes it suitable for various network monitoring and testing needs.

3. Automation and Integration

With Python and Scapy, you can automate repetitive network tasks, integrate with other systems, and create robust monitoring solutions that fit your unique requirements.

Getting Started with Scapy

Before we dive into scripting, let’s ensure you have Scapy installed. You can install it using pip:

pip install scapy

Basic Scapy Usage

Here’s a quick example to get you familiar with Scapy. We’ll create and send a simple ICMP (ping) packet:

from scapy.all import *

# Create an ICMP packet
packet = IP(dst="8.8.8.8")/ICMP()

# Send the packet
response = sr1(packet)

# Display the response
response.show()

This script sends a ping to 8.8.8.8 (Google’s DNS server) and displays the response.

Automating Network Monitoring with Scapy

Now, let’s create a more advanced script that monitors network traffic and alerts you when specific conditions are met. We’ll create a script that captures DNS queries and logs suspicious activity.

Step 1: Capture DNS Queries

First, we’ll write a script to capture DNS queries on your network:

from scapy.all import *

def monitor_dns(pkt):
if pkt.haslayer(DNS) and pkt.getlayer(DNS).qr == 0:  # DNS request
print(f"DNS Query: {pkt[DNS].qd.qname.decode()}")

sniff(filter="udp port 53", prn=monitor_dns)

This script captures DNS queries by filtering UDP packets on port 53 and prints the queried domain names.

Step 2: Log Suspicious Activity

Next, we’ll enhance the script to log DNS queries that match a predefined list of suspicious domains:

import logging
from scapy.all import *

# Configure logging
logging.basicConfig(filename="suspicious_dns.log", level=logging.INFO, format="%(asctime)s - %(message)s")

# List of suspicious domains
suspicious_domains = ["malicious.com", "badactor.org"]

def monitor_dns(pkt):
if pkt.haslayer(DNS) and pkt.getlayer(DNS).qr == 0:  # DNS request
domain = pkt[DNS].qd.qname.decode()
print(f"DNS Query: {domain}")
if domain in suspicious_domains:
logging.info(f"Suspicious DNS Query: {domain}")

sniff(filter="udp port 53", prn=monitor_dns)

This enhanced script logs any DNS queries for domains in the suspicious_domains list.

Step 3: Send Alerts

Finally, we’ll add functionality to send email alerts when a suspicious DNS query is detected:

import smtplib
from email.mime.text import MIMEText
from scapy.all import *

# Configure logging
logging.basicConfig(filename="suspicious_dns.log", level=logging.INFO, format="%(asctime)s - %(message)s")

# List of suspicious domains
suspicious_domains = ["malicious.com", "badactor.org"]

# Email configuration
SMTP_SERVER = "smtp.example.com"
SMTP_PORT = 587
SMTP_USER = "you@example.com"
SMTP_PASS = "yourpassword"
ALERT_EMAIL = "alert@example.com"

def send_email_alert(domain):
msg = MIMEText(f"Suspicious DNS Query: {domain}")
msg["Subject"] = "Suspicious DNS Query Alert"
msg["From"] = SMTP_USER
msg["To"] = ALERT_EMAIL

    with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
        server.starttls()
        server.login(SMTP_USER, SMTP_PASS)
        server.sendmail(SMTP_USER, ALERT_EMAIL, msg.as_string())

def monitor_dns(pkt):
if pkt.haslayer(DNS) and pkt.getlayer(DNS).qr == 0:  # DNS request
domain = pkt[DNS].qd.qname.decode()
print(f"DNS Query: {domain}")
if domain in suspicious_domains:
logging.info(f"Suspicious DNS Query: {domain}")
send_email_alert(domain)

sniff(filter="udp port 53", prn=monitor_dns)

This script sends an email alert whenever a suspicious DNS query is detected, in addition to logging it.

Conclusion

With Scapy and Python, you can automate network monitoring tasks and gain deeper insights into network traffic. This week’s script provides a robust foundation for capturing, logging, and alerting on DNS queries, making it easier to detect and respond to suspicious activity on your network. Happy scripting, and stay secure!