Build a Python Firewall Log Analyzer That Spots Attacks in Your UFW Logs


Your Linux firewall is quietly doing its job — blocking scans, dropping connection attempts, logging every one of them. The problem is that the log grows by thousands of lines a day, and nobody reads thousands of lines. So let's build a Python script that reads your UFW firewall log, counts who is hitting you hardest, spots port scans, and prints a clear summary. It's a real defensive tool, and it takes about 60 lines.

What the Log Looks Like

UFW (Uncomplicated Firewall) logs blocked packets to /var/log/ufw.log or /var/log/syslog. Each blocked packet leaves a line like this:

Nov 23 10:14:22 server kernel: [UFW BLOCK] IN=eth0 OUT= SRC=203.0.113.45 DST=192.0.2.10 LEN=60 TOS=0x00 PROTO=TCP SPT=51234 DPT=22 WINDOW=64240 SYN

The useful fields: SRC (attacker IP), DPT (destination port they wanted), PROTO (TCP or UDP), and the SYN flag (a connection attempt). Our script will pull these out with a regular expression and count them.

The Code

import re
from collections import Counter, defaultdict

LOG_FILE = "/var/log/ufw.log"
TOP_N = 10

# Match UFW BLOCK lines and pull out source IP, dest port, protocol
PATTERN = re.compile(
    r"\[UFW BLOCK\].*?SRC=(\S+) DST=\S+.*?PROTO=(\S+).*?DPT=(\d+)"
)

def parse_log(path):
    blocked = Counter()          # IP -> total blocked packets
    ports = Counter()            # port -> total attempts
    per_ip_ports = defaultdict(set)  # IP -> set of ports probed
    total = 0
    with open(path, errors="ignore") as f:
        for line in f:
            m = PATTERN.search(line)
            if not m:
                continue
            src, proto, dpt = m.group(1), m.group(2), int(m.group(3))
            blocked[src] += 1
            ports[dpt] += 1
            per_ip_ports[src].add(dpt)
            total += 1
    return total, blocked, ports, per_ip_ports

def main():
    total, blocked, ports, per_ip_ports = parse_log(LOG_FILE)
    print(f"Total blocked packets: {total}\n")

    print(f"Top {TOP_N} most aggressive IPs:")
    for ip, count in blocked.most_common(TOP_N):
        print(f"  {ip:<16} {count} blocked packets")

    print("\nMost targeted ports:")
    for port, count in ports.most_common(TOP_N):
        print(f"  {port:<6} {count} attempts")

    print("\nPossible port scans (one IP probing 10+ different ports):")
    found = False
    for ip, probed in per_ip_ports.items():
        if len(probed) >= 10:
            print(f"  {ip} probed {len(probed)} ports: "
                  f"{sorted(probed)[:15]}...")
            found = True
    if not found:
        print("  None detected.")

if __name__ == "__main__":
    main()

How It Works

  1. Parsing — the regex matches only [UFW BLOCK] lines and extracts the source IP, protocol and destination port. Everything else in the log is skipped.
  2. Counting — Counter objects tally blocked packets per IP and attempts per port. The top 10 of each tells you who is hammering you and what they're after (port 22 means SSH brute-forcing, port 445 means SMB scanning).
  3. Scan detection — a normal attacker tries one or two ports. An IP that probes 10 or more different ports is doing a port scan, mapping your server before attacking. The script flags those automatically.

Try It

Save the file as fw_analyze.py and run it against your own log. On a typical internet-facing server you'll see SSH (port 22) at the top within minutes of going online — that alone is a lesson in why password logins should be disabled.

sudo python3 fw_analyze.py

You need sudo because UFW logs are readable only by root. If your system logs to /var/log/syslog instead, change LOG_FILE at the top of the script.

Level Up

  • Add timestamps to see when the attacks spike — many brute-force campaigns run on a schedule.
  • Auto-block the worst IPs by feeding the top offenders into ufw deny from <ip> — but only after checking they're not a service you use.
  • Email yourself a daily summary with smtplib, or write the results to a file and check it with your morning coffee.

Your firewall was already collecting this intelligence. Now you're finally reading it — and that is exactly how defense works: not by buying more tools, but by using the data you already have.

Remember: only run this on systems you own or have written permission to monitor. Reading your own server's logs is defense. Reading someone else's is not.

Comments

Popular Posts