Forensics & Inheritance — Putting It Together
20 min In ProgressLearning Objectives
- Parse log files with regex to find suspicious IPs
- Use Counter to rank threats by frequency
- Build a scanner hierarchy with inheritance
Log Analysis — Finding Brute Force Attacks
Most forensic work is log analysis — reading, filtering, flagging. Python's re module and collections.Counter turn raw auth logs into a ranked threat list in under 10 lines.
import re
from collections import Counter
# Simulated auth.log snippet
log_data = """
Failed password for root from 10.0.0.5 port 22
Failed password for root from 10.0.0.5 port 22
Failed password for admin from 192.168.1.99 port 22
Failed password for root from 10.0.0.5 port 22
Accepted password for user from 10.0.0.10 port 22
"""
pattern = re.compile(r"Failed password.*from (\d+\.\d+\.\d+\.\d+)")
failed_ips = pattern.findall(log_data)
counts = Counter(failed_ips)
print("Top brute-force sources:")
for ip, n in counts.most_common():
print(f" {ip:>15} {n} attempts")
Inheritance — Building a Scanner Suite
Inheritance means a child class gets everything from the parent. Build a base Scanner once, then extend it for port scanning, web scanning, vuln scanning — all sharing the same core log() and report(). class Child(Parent): — that's all inheritance is.
class Scanner:
"""Base class shared by all scanner types."""
def __init__(self, target):
self.target = target
self.findings = []
def log(self, message):
self.findings.append(message)
print(f"[{self.target}] {message}")
def report(self):
print(f"\n=== {self.target} ===")
for f in self.findings:
print(f" • {f}")
class WebScanner(Scanner):
"""Inherits Scanner, adds HTTP header checks."""
def check_headers(self, headers):
if "X-Frame-Options" not in headers:
self.log("Missing X-Frame-Options")
if "Strict-Transport-Security" not in headers:
self.log("Missing HSTS header")
ws = WebScanner("example.com")
ws.check_headers({"Content-Type": "text/html"})
ws.report()
📝 Exercise: Build a VulnScanner
Extend the Scanner base class to create a VulnScanner. Add a method check_ports(open_ports) that logs a warning if port 23 (Telnet) or 21 (FTP) is in the list — both are insecure protocols.
code.py
Output