Automation
Objectives: By the end of this topic, you will be able to…
- Create Python scripts, and Unix pipelines, to automate security tasks
- Integrate Kali tools into functional scripts
- Read, process, and filter results from other tools
- Use scripting to support reconnaissance, analysis, and defense
Scripting as a force multiplier
Security professionals who script gain a qualitative advantage as well as a quantitative one: the ability to reason at a higher level of abstraction. A penetration tester who can script can test 10,000 hosts in the time it takes to test 10 manually, but more importantly, they can iterate on hypotheses rapidly: “Are there any hosts on this subnet responding to port 8080 with this specific HTTP header?” becomes a ten-line script rather than a morning’s work.
The security tool ecosystem is built on composability. Most command-line security tools follow the Unix philosophy: do one thing well, read from stdin, write to stdout. Your scripts are the glue that turns individual tools into multi-stage pipelines: nmap → grep → python enrichment → report, workflows that would take hours to replicate manually. The simplest form of that glue needs no Python at all: a shell pipeline such as grep 'Failed password' /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head counts failed SSH logins per source address, and you move to a script once the logic needs state, branching, or error handling that a pipeline cannot express.
Example
The pipeline above works because the IP address is always the fourth field from the end of a
Failed passwordline. Run it on a system’s sshd log (/var/log/auth.logon Debian-based systems) and predict the output format before you do: each line should be a count followed by an address. Then think of one case where this extraction breaks, and what that tells you about when a script is safer than a pipeline.
How network scanners actually work
Before writing scripts that wrap nmap, it is worth understanding what nmap is doing at the socket level. This knowledge helps you interpret results correctly, write better wrappers, and understand why certain scans require root privileges.
TCP connection mechanics
A TCP connection follows a three-way handshake: the client sends a SYN, the server replies with SYN-ACK if the port is open, and the client completes with ACK. A closed port responds with RST immediately. A filtered port (blocked by a firewall) does not respond; the scanner infers this from timeout.
Client Server
|--- SYN ------->| Port open: server replies SYN-ACK
|<-- SYN-ACK ----|
|--- ACK ------->|
|--- SYN ------->| Port closed: server replies RST immediately
|<-- RST --------|
|--- SYN ------->| Port filtered: no response, scanner times out
(timeout)
nmap’s SYN scan (-sS) exploits this by sending a SYN, reading the response, and then resetting the connection instead of completing the handshake. nmap uses it by default only when it has raw-socket privileges, because crafting raw packets bypasses the operating system’s socket API and requires root or the CAP_NET_RAW capability (the Linux capability that permits raw sockets without full root); without them nmap falls back to a TCP connect scan (-sT), which asks the OS to complete the handshake through connect(). Because the handshake never completes, the application listening on the port normally never sees a connection and its own logs stay empty. The packets are still visible to anything watching the network, such as stateful firewalls, intrusion detection systems, flow records and packet captures, so a half-open scan is quieter at the application layer but not invisible. NULL (-sN), FIN (-sF) and Xmas (-sX) scans vary the TCP flags instead of the handshake and rely on the target following RFC 793; class 12 uses them against firewall rules. The scan flags you met in class 03 (-sS, -A) and those used in class 12 are the variants described here.
| Flag | What it does |
|---|---|
-sS | SYN (half-open) scan; needs raw-socket privileges |
-sT | TCP connect scan; works without privileges because the OS performs the handshake |
-sV | Version detection: sends probes from the nmap-service-probes database to each open port and matches the replies to identify product and version |
--open | Lists only ports that are open or possibly open |
--top-ports N | Scans the N ports nmap’s frequency data ranks as most commonly open, instead of a numeric range |
-oX file | Writes results as XML; -oX - writes the XML to stdout |
Probing 1,024 ports one at a time with a 1-second timeout takes up to 17 minutes in the worst case, which is why scanners are concurrent.
Question
A scan reports nothing at all for port 8443 on a host. Using the three responses in the diagram above (SYN-ACK, RST, silence), say which of them each possible explanation would produce, and explain why silence alone cannot distinguish a firewall that drops packets from a host that is switched off. If you cannot, re-read the handshake paragraph.
Concurrency: from slow to fast, and how it fails
The single biggest performance gain in network scripting comes from concurrency. Network I/O is dominated by waiting: while your script waits for a TCP response, it could be sending dozens of other probes simultaneously. There are two practical concurrency models in Python for this use case.
Threading for I/O-bound scanning
Python’s threading module is appropriate for I/O-bound tasks. The Global Interpreter Lock (GIL) prevents true CPU parallelism, but since network scanning spends most time waiting for responses (not computing), threading provides dramatic speedups. The concurrent.futures.ThreadPoolExecutor makes this ergonomic:
from concurrent.futures import ThreadPoolExecutor
import socket
def scan_port(args: tuple[str, int]) -> int | None:
host, port = args
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.5)
try:
s.connect((host, port))
return port
except (socket.timeout, ConnectionRefusedError, OSError):
return None
host = "192.168.1.1"
with ThreadPoolExecutor(max_workers=500) as executor:
results = executor.map(scan_port, [(host, p) for p in range(1, 10001)])
open_ports = sorted(p for p in results if p is not None)
print(f"Open ports: {open_ports}")500 workers cut the wall-clock time of a 10,000-port scan by roughly the same factor, as long as the operating system lets you keep that many sockets open.
When concurrency lies to you
Concurrency has a cost that raw speedups hide: every probe in flight is an open socket, and every socket is a file descriptor. Linux limits the descriptors a process may hold (the soft limit is commonly 1024; ulimit -n shows yours), and once a scanner opens more sockets than that, socket() or connect() raises OSError with “Too many open files”. The pool of local ports used for outgoing connections is also finite, and the target and the path to it add losses of their own: a service whose SYN backlog is full drops new SYNs, and firewalls that rate-limit new connections stop answering. In every case the probe ends in an exception or a timeout, not in a refused connection. The scanner above catches OSError and returns None, which turns “I could not ask” into “the answer is no”, and the result is a false negative. The defensible design classifies outcomes instead of collapsing them:
try:
s.connect((host, port))
return "open"
except ConnectionRefusedError:
return "closed" # a RST came back
except socket.timeout:
return "filtered" # silence: dropped, filtered or lost
except OSError as e:
return f"error:{e.errno}" # e.g. EMFILE: result unknown, never "closed"Count the error outcomes and report them next to the open ports, and re-scan the unknown ports at lower concurrency. The principle holds for every scanner, nmap included: “not detected” is not the same claim as “closed”, and a result set is only as complete as its error count says it is.
asyncio for high-concurrency scanning
asyncio is more efficient than threading at very high concurrency because it uses a single thread with a cooperative event loop rather than OS threads, each of which carries memory and scheduling overhead. This matters when scanning thousands of hosts. The coroutine that probes one port appears in the next block, together with the rate limiting it needs.
Rate limiting: stealth and target health
Blasting thousands of simultaneous connections is fast but noisy. A burst of SYNs from one source to many ports is a classic intrusion detection signature, and aggressive scanning can crash fragile devices such as printers and industrial controllers. An asyncio.Semaphore limits how many probes are in flight at once; it limits concurrency, not probes per second, so add a short randomized delay inside the semaphore if you also need to bound the rate. Perfectly regular timing is itself a mark of automation, and jitter breaks that regularity.
import asyncio
import random
async def scan_port(host: str, port: int) -> int | None:
try:
_, writer = await asyncio.wait_for(
asyncio.open_connection(host, port), timeout=0.5
)
writer.close()
await writer.wait_closed()
return port
except (asyncio.TimeoutError, ConnectionRefusedError, OSError):
return None
async def scan_host_limited(host: str, ports: range, max_concurrent: int = 100) -> list[int]:
semaphore = asyncio.Semaphore(max_concurrent)
async def limited_scan(port: int) -> int | None:
async with semaphore:
await asyncio.sleep(random.uniform(0, 0.05)) # jitter: spreads probes out in time
return await scan_port(host, port)
results = await asyncio.gather(*[limited_scan(p) for p in ports])
return sorted(p for p in results if p is not None)Question
A scan of 1,000 ports at 2,000 concurrent connections reports 40 open ports. The same scan at 100 concurrent connections reports 47. Which result do you trust, which exception types in the scanner would you count first to explain the gap, and what does
ulimit -nin your own shell tell you about where the ceiling is?
What reconnaissance output reveals
Banners and version strings. A service banner is what a service says about itself when you connect, and nmap’s version detection (-sV) extends that by sending protocol probes and matching the replies against a signature database. The resulting product and version string is valuable to an attacker because it replaces guesswork with a lookup: Samba 3.0.20 leads directly to the public record for CVE-2007-2447, a command injection flaw in Samba’s username map script, and from there to its severity score and available exploits. Defenders therefore remove or generalize version strings where the software allows it. Hiding a version reduces what an attacker learns but does not remove the vulnerability, since the service can often still be fingerprinted by its behaviour; and distributions frequently backport security patches without changing the upstream version number, so a version string can also overstate the exposure.
SSH host keys. Every SSH server presents a host key so that clients can verify they are reaching the same machine on later visits; clients store it in known_hosts on first contact and warn if it changes. ssh-keyscan retrieves those public host keys by performing only the opening of the SSH handshake, without authenticating, and prints one line per key containing the host, the key type and the base64-encoded key. The key type is intelligence: ssh-ed25519 and ecdsa-sha2-nistp256 are current choices, while the legacy DSA type (ssh-dss, disabled by default since OpenSSH 7.0) or short RSA keys point to old or unmaintained systems.
HTTP security headers. A web server’s response headers state which protections it asks browsers to enforce, so a missing header is a finding in itself, and Server or X-Powered-By headers that are present disclose software and versions as described above. curl -I fetches only the headers.
| Header | What it asks the browser to do | What its absence allows |
|---|---|---|
Strict-Transport-Security | Use HTTPS only for this site for a stated period | A first plaintext visit can be downgraded or intercepted |
Content-Security-Policy | Load scripts and other content only from approved sources | Injected script runs with no browser-side restriction |
X-Frame-Options | Refuse to render the page inside a frame (CSP frame-ancestors supersedes it) | The page can be framed by another site for clickjacking |
Active versus passive visibility. As class 01 defined it, active reconnaissance sends packets to the target and so can appear in its firewall, intrusion detection and host logs, whereas passive reconnaissance uses data someone else already collected. Shodan continuously scans the internet and indexes what it finds, so a query returns open ports, banners and associated CVEs without a single packet reaching the target; the only trace on the target is Shodan’s earlier indexing probe, which looks like ordinary background scanning. Free API keys for such services are rate limited, and the limits change over time, so check current terms and cache results rather than repeating lookups.
Question
A scan returns
Server: nginx/1.18.0. Name the lookups you would make (which database, which identifier, what you hope to find) to decide whether this host is exploitable, then explain to a defender why removing the string helps and why it does not fix anything. Before continuing: can you also say why the opposite case, a host that reports no version, is not proof that it is patched?
Parsing structured security data
Security tools produce output in many formats. Reading it with your eyes is the lowest-leverage approach. Parsing it programmatically turns raw output into data you can filter, sort, join with other sources, and feed into reports.
nmap XML output
nmap’s -oX flag produces structured XML that is far easier to parse than its human-readable output format. An nmap XML file is a tree: each host element contains address elements (one with addrtype="ipv4", and another for the MAC address when the target is on the local network), an optional hostnames element with hostname children, and a ports element holding one port per probed port. Each port has a state element and, after version detection, a service element whose name, product and version attributes carry what the probes identified. Select addresses by addrtype rather than taking the first address element. The -oX - variant writes XML to stdout, which you capture directly:
import subprocess
import xml.etree.ElementTree as ET
def nmap_scan(target: str) -> dict[str, list[int]]:
result = subprocess.run(
["nmap", "-p-", "--open", "-oX", "-", target],
capture_output=True, text=True, check=True
)
root = ET.fromstring(result.stdout)
hosts = {}
for host in root.findall("host"):
addr = host.find("address[@addrtype='ipv4']").get("addr")
ports = [
int(p.get("portid"))
for p in host.findall(".//port")
if p.find("state").get("state") == "open"
]
if ports:
hosts[addr] = ports
return hostsThe same pattern, driving a tool through subprocess and parsing a structured output format, applies to any scanner that offers XML or JSON output; check the tool’s manual for the flag.
Log mining with regular expressions
Web server and authentication logs follow predictable formats. Regular expressions extract structured fields from lines of plain text, turning log files into queryable datasets:
import re
from collections import Counter
from pathlib import Path
from urllib.parse import unquote
LOG_PATTERN = re.compile(
r'(?P<ip>\S+) \S+ \S+ \[.+?\] "(?P<method>\w+) (?P<path>\S+) \S+" '
r'(?P<status>\d+) (?P<size>\S+)'
)
ATTACK_PATTERNS = re.compile(
r"(union.*select|insert.*into|drop\s+table" # SQL injection
r"|\.\./|\.\.\\" # path traversal
r"|<script" # XSS
r"|cmd=|exec=|shell=)", # command injection
re.IGNORECASE,
)
def analyze_access_log(path: str) -> dict:
ip_counts = Counter()
status_counts = Counter()
suspicious = []
for line in Path(path).open():
m = LOG_PATTERN.match(line)
if not m:
continue
ip, status, req_path = m.group("ip"), m.group("status"), m.group("path")
ip_counts[ip] += 1
status_counts[status] += 1
if ATTACK_PATTERNS.search(unquote(req_path)):
suspicious.append({"ip": ip, "path": req_path, "status": status})
return {
"top_ips": ip_counts.most_common(10),
"status_distribution": dict(status_counts),
"suspicious_requests": suspicious,
}The for line in Path(path).open() pattern streams the file line by line; it processes multi-gigabyte logs without loading them into memory.
Real clients percent-encode special characters, so a space arrives as %20, a quote as %27 and ../ as %2e%2e%2f, and attackers add further encodings to evade naive filters; decode the path with urllib.parse.unquote before matching. A pattern match is triage, not a verdict: a legitimate search for the words “union select” matches the SQL rule, so every hit needs a human or a second signal. Classes 08 and 14 explain the attacks themselves.
Detecting brute-force in authentication logs
A syslog authentication line has a fixed shape: timestamp, host name, process[pid], then the message. The same /var/log/auth.log lines are what you inspected by hand in class 13; here you extract them automatically. For SSH failures the message is Failed password for root from 203.0.113.9 port 51234 ssh2, and when the account does not exist sshd inserts invalid user before the name. A pattern that omits that optional phrase silently ignores exactly the attempts that guess nonexistent accounts. Counting failures per source address finds noisy guessing; counting distinct usernames per address distinguishes a wordlist (admin, test, oracle) from a targeted attack on one account; and a successful login from an address that just produced a run of failures is the highest-value finding, because it may mean the guessing worked.
from collections import defaultdict
AUTH_FAIL = re.compile(
r"Failed password for (?:invalid user )?(?P<user>\S+) from (?P<ip>\d+\.\d+\.\d+\.\d+)"
)
def detect_brute_force(log_path: str, threshold: int = 10) -> list[str]:
attempts: dict[str, int] = defaultdict(int)
for line in Path(log_path).open():
if m := AUTH_FAIL.search(line):
attempts[m.group("ip")] += 1
return [ip for ip, count in attempts.items() if count >= threshold]This is the core idea behind fail2ban, a Python tool that adds time windows and automatic firewall bans on top of it.
Example
Here are two lines from an sshd log:
Mar 3 10:15:02 web1 sshd[2211]: Failed password for root from 203.0.113.9 port 51234 ssh2Mar 3 10:15:05 web1 sshd[2213]: Failed password for invalid user admin from 203.0.113.9 port 51240 ssh2Predict which of them the patternFailed password for \S+ from (\d+\.\d+\.\d+\.\d+)matches and whichAUTH_FAILabove matches, then trace the\S+against the second line to see why they differ.
Statistical anomaly detection
Beyond signature-based detection (looking for known-bad patterns), statistical anomaly detection identifies deviations from a baseline without knowing in advance what “malicious” looks like. Statistical baselines are a common building block in monitoring and SIEM products, alongside signature rules.
The 3-sigma rule (empirical rule) states that for normally distributed data, ~99.7% of observations fall within three standard deviations of the mean. Anything outside that window is statistically unusual and warrants investigation:
import re
import statistics
from collections import Counter
from pathlib import Path
def detect_traffic_spikes(log_path: str) -> list[str]:
hourly = Counter()
for line in Path(log_path).open():
if m := re.search(r'\[(\d{2}/\w+/\d{4}):(\d{2}):', line):
hourly[f"{m.group(1)}-{m.group(2)}"] += 1
counts = list(hourly.values())
if len(counts) < 2:
return []
mean = statistics.mean(counts)
stdev = statistics.stdev(counts)
threshold = mean + 3 * stdev
return [
f"{hour}: {count} requests ({(count - mean) / stdev:.1f}σ above mean)"
for hour, count in hourly.items()
if count > threshold
]The interesting property of this approach is that it adapts to the baseline: a server that normally gets 10,000 requests per hour will not alert on 10,500; a server that normally gets 100 will. The threshold is relative, not absolute. The telemetry framing from class 11 applies here, with the baseline taking the place of a fixed signature.
The 3-sigma rule has three limits you must know before trusting it. First, an outlier contaminates the baseline it is judged against: the spike raises the mean and inflates the standard deviation, which shrinks its own z-score. With n samples and a single outlier, the largest attainable z-score using the sample standard deviation is (n-1)/√n, so a series of ten or fewer counts can never exceed three sigma however large the spike, and 24 hourly counts cap at about 4.7. A robust baseline uses the median and the median absolute deviation. Second, traffic has seasonality: a count that is normal at noon is anomalous at 3 a.m., yet a single global baseline averages the two together and flags neither correctly. Comparing each hour against the same hour of previous days, or against a rolling window, removes the daily cycle from the baseline. Third, the 99.7% figure applies only to approximately normal data, and request counts are usually heavy-tailed, so expect false positives and tune the threshold against history.
Question
Why can a series of only eight hourly counts never trigger a 3-sigma alert, however large the final count is? Work from the fact that the spike itself raises both the mean and the standard deviation it is compared against.
OPSEC for scripts
Scripts that interact with sensitive systems have operational security requirements that general-purpose programming often ignores.
Credential management
Never hardcode credentials, in the script or in a config file under version control. Load them from environment variables (os.environ["KEY"] fails loudly if the variable is missing) or a secrets store, never from the repository. Treat any secret that has ever reached a public repository as compromised even after you delete the commit, because history and forks persist and automated scrapers monitor new commits; rotate it.
Audit logging
Security scripts should log what they do, not just what they find. In a penetration test engagement, you may need to prove what your script did if a system becomes unavailable during the test. Timestamped logs are your defense:
import logging
from datetime import datetime
target = "203.0.113.10" # illustrative documentation address
engagement_id = "ENG-2026-014" # illustrative identifier
open_ports = [22, 80]
logging.basicConfig(
filename=f"scan_{datetime.now():%Y%m%d_%H%M%S}.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
logging.info("Starting scan of %s (authorized by: %s)", target, engagement_id)
# ... perform scan ...
logging.info("Scan complete: %d open ports found on %s", len(open_ports), target)An audit log records each action and its result, not only the findings, so it can show later exactly what the script sent and when. Logging is also essential for debugging: a script that runs for 30 minutes and produces no output gives you nothing to work with when it fails.
Question
You committed an API key to a public repository and removed it in the next commit thirty seconds later. What must you do now, and why does the removal commit not fix the problem?
Best practices
Scope and authorization first. A script that scans networks you do not have permission to scan is illegal, regardless of intent. Verify that your target is within the authorized scope before executing any automated tool. Many pentest agreements specify exactly which IP ranges and time windows are authorized.
Fail loudly. Scripts that swallow errors silently are dangerous in security contexts. An error during scanning means your results may be incomplete or wrong, and incomplete results reported as complete is worse than no results. Use check=True with subprocess, re-raise exceptions you cannot handle, and exit with a non-zero code on failure. This includes the classified-outcome design from the concurrency section: an error count that is hidden from the report makes incomplete results look complete.
Parameterize everything. Hardcoded IPs, port ranges, and file paths make scripts single-use and brittle. Use argparse from the start.
Minimal privilege. A TCP connect scan works without root and a SYN scan does not; understand which privileges your script actually needs and run with the minimum, and never tell users to sudo your script unless the specific operation requires it.
Idempotency. Design scripts to be safe to re-run. Write output files with timestamped names.
Question
A colleague’s scanner wraps every probe in
except Exception: passand prints “scan complete”. Which two of the practices above does this violate, and what would you change first?
Hands-on lab
Requirements: Kali Linux, Python 3.10+ (standard library only),
nmap,ssh-keyscan,whois,dig,curl,git
nmap discovers hosts and open ports and, with -sV, identifies the services behind them; ssh-keyscan retrieves a server’s public SSH host keys without logging in; whois queries domain and address registration records; dig queries DNS records (A, MX, NS, TXT) and, with -x, reverse DNS; curl -I fetches only a web server’s response headers; python3 -m http.server <port> starts a simple web server that gives the scanner something to find; systemctl starts and stops system services such as the SSH daemon; sudo runs a command with administrator privileges; git records and publishes your work.
The lab is done in two roles. Each role builds part of a reconnaissance and analysis toolkit, and files crossing between you are what makes each half testable. By the end you will have a complete, multi-stage reconnaissance and analysis tool that neither of you could have finished alone.
Part 0: Agree scope, prepare the target and plant the logs
Decide which of you is the scanner engineer and which is the log analyst. Everything you scan in this lab is the analyst’s own Kali machine, and nothing else, because scanning a host you are not authorized to scan is illegal regardless of intent.
Analyst: write a short file scope.txt containing your machine’s IP address, the date and time window in which scanning is allowed, and the sentence “Only this address may be scanned.” Start three listeners with sudo python3 -m http.server <port> (a standard-library module that serves files over HTTP, which gives the scanner something to find) in separate terminals, each started from an empty directory, on ports between 100 and 1024 that are not already in use (ports below 1024 are privileged, which is why sudo is needed), and make sure the SSH service is running (sudo systemctl start ssh starts it on Kali). Write the open ports in a note and do not show it to the engineer: it is the answer key for the scanner.
Handoff 1, analyst to engineer: send
scope.txt. The engineer scans only the address in that file and only inside the stated window.
Engineer: download base-auth.log and base-access.log from Moodle. They describe one ordinary day on a small server: scattered failed logins that never reach ten per address, benign traffic with a mild daily cycle, and no attack payloads. Plant your own findings into copies of them with the script in Part 3, changing the marked parameters: choose two attacker IPs and a number of failures for each, include some Failed password for invalid user lines, make one attacker finish with an Accepted password login, choose the hour of the traffic spike, and include at least one of each attack family (SQL injection, path traversal, XSS, command injection) written percent-encoded. The four template payloads are textbook strings, so also write at least two payloads of your own that are not in the template and that you expect a first-draft pattern to miss: for example double encoding (%252e%252e%252f), mixed case (UnIoN SeLeCt), a SQL comment splitting a keyword (UN/**/ION), or + for a space. Each must still be a request a real attacker could send and a vulnerable server would interpret as an attack. List the custom payloads in planted.json and mark them as custom. Write what you planted to planted.json (attacker IPs, spike hour, attack paths, count of invalid user lines you added, the address that logged in successfully) and keep it to yourself.
Handoff 2, engineer to analyst: send the planted
auth.logandaccess.log, and nothing else. From here on the analyst has only these two files. The analyst does not download the base logs and does not compare against them: the exercise is to find the planted activity with an analyzer that works on logs you have never seen.
After Part 0 the engineer works Parts 1 and 2 while the analyst works Part 3 in parallel; the pair then meets twice to exchange and score results, and finally builds Part 4 together.
Part 1: From sequential to concurrent scanner
Engineer. Start with this working sequential scanner:
import socket
import time
def scan_port(host: str, port: int, timeout: float = 1.0) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
try:
s.connect((host, port))
return True
except (socket.timeout, ConnectionRefusedError, OSError):
return False
if __name__ == "__main__":
host = "127.0.0.1" # replace with the address from scope.txt
start = time.perf_counter()
open_ports = [p for p in range(1, 1025) if scan_port(host, p)]
elapsed = time.perf_counter() - start
print(f"Open ports: {open_ports} ({elapsed:.1f}s)")A. Run this against the address in scope.txt and record the elapsed time. Closed ports answer with an immediate RST on a local network, so expect modest differences between sequential, threaded and asyncio versions; the figure that matters is how many of the analyst’s known open ports each version finds at each rate. Then rewrite it using ThreadPoolExecutor. Test max_workers values of 50, 200, and 500 and record the elapsed time for each. Plot or tabulate the results.
B. Rewrite again using asyncio + asyncio.Semaphore to cap concurrency at a configurable limit. Measure its performance at the same concurrency levels and compare against the threaded version.
C. Add a proper CLI to whichever version you prefer, using argparse:
| Flag | Description | Default |
|---|---|---|
target | IP address to scan | (required) |
--ports | Port range, e.g. 1-1024 or 22,80,443 | 1-1024 |
--rate | Max concurrent connections | 200 |
--timeout | Per-port timeout in seconds | 0.5 |
--output | JSON output file | stdout |
Parse the --ports argument to support both comma-separated lists (22,80,443) and ranges (1-1024).
D. Output results as JSON to the path given by --output:
{
"target": "127.0.0.1",
"scan_time_seconds": 2.3,
"timestamp": "2026-05-04T14:32:00",
"open_ports": [22, 80, 443]
}After Part 1 D, produce scan_rate200.json (--rate 200) and scan_rate2000.json (--rate 2000) with the scanner’s --output flag.
Handoff 3, engineer to analyst: send both JSON files. The analyst compares the
open_portsof each against the answer key and tells the engineer which ports were missed at each rate. The Part 1 question is answered by the engineer using that comparison, and the analyst adds one sentence confirming the missed ports.
Question
At very high concurrency (e.g.
--rate 2000), you may observe false negatives (open ports reported as closed). Explain the mechanism behind this. Why does this mean “the scanner did not detect it” is not the same claim as “the port is closed”? What does this imply about how you should interpret scan results from any tool, including nmap?
Part 2: Structured output and enrichment
Engineer.
A. Run nmap with service version detection and XML output against the single address in scope.txt:
nmap -sV --open -oX scan.xml <analyst-ip>The placeholder is the address from scope.txt. Before writing any code, open scan.xml and read through the structure. Identify how hosts, ports, states, service names, and version strings are organized in the XML hierarchy.
B. Write parse_scan.py that reads scan.xml and produces a structured Python object (dict) for each live host:
{
"ip": "192.168.1.10",
"hostname": "gateway.local",
"open_ports": [
{"port": 22, "service": "ssh", "version": "OpenSSH 8.9"},
{"port": 80, "service": "http", "version": "Apache httpd 2.4.54"}
]
}Use xml.etree.ElementTree — do not use a third-party nmap library.
C. For each host with port 22 open, run ssh-keyscan via subprocess and parse the output to extract the key type (e.g. ecdsa-sha2-nistp256, ssh-ed25519). Add a "ssh_host_key_type" field to that host’s dict. Handle the case where ssh-keyscan times out or the host does not respond.
D. Write the enriched list of hosts to hosts.json. Your script should accept --input (XML file) and --output (JSON file) arguments.
Question
Service version detection (
-sV) works by sending probe packets and matching responses against a signature database (nmap-service-probes). This makes the scan significantly slower and generates more network traffic than a plain port scan. From a defender’s perspective: why is the version string in a service banner valuable intelligence for an attacker? What is the security-relevant difference betweenApache httpd 2.4.54and a server that returns no version string at all?
Part 3: Log analysis and anomaly detection
This part uses log files for analysis. The analyst works on the auth.log and access.log received in Handoff 2, in parallel with the engineer’s Parts 1 and 2. A real log from your Kali system can serve as an extra input (/var/log/auth.log, if your system writes it; current Kali installations may log to the systemd journal by default, in which case use only the planted files).
Plant findings in the baseline logs (the engineer changes the marked parameters in Part 0). The script reads the two base files, appends your planted lines, sorts each file by time (every line of a file falls on the same day, so a plain text sort orders them) and writes auth.log and access.log:
python3 - <<'EOF'
import random
# --- engineer: change everything marked below ---
ATTACKERS = {"185.220.101.5": 60, "45.33.32.156": 35} # attacker IP -> number of failed logins
INVALID_SHARE = 0.4 # share of failures that target nonexistent accounts
BREACHED = "185.220.101.5" # this attacker finishes with a successful password login
SPIKE_HOUR = 3 # hour of the traffic spike (0-23)
SPIKE_SIZE = 900 # extra requests in that hour
SPIKE_IP = "198.51.100.99" # source of the spike
ATTACKS = [ # include each family, percent-encoded
"/?id=1'%20UNION%20SELECT%201,2,3--",
"/admin/..%2f..%2f..%2fetc/passwd",
"/search?q=%3Cscript%3Ealert(1)%3C/script%3E",
"/cgi-bin/test.cgi?cmd=id%3Bcat%20/etc/passwd",
# engineer: add at least two payloads of your own here (double-encoded, mixed-case, ...)
]
# --- end of parameters ---
def stamp():
return f"{random.randint(0, 23):02d}:{random.randint(0, 59):02d}:{random.randint(0, 59):02d}"
auth = open("base-auth.log").read().splitlines()
for ip, n in ATTACKERS.items():
for _ in range(n):
if random.random() < INVALID_SHARE:
who = f"invalid user {random.choice(['test', 'oracle', 'admin1'])}"
else:
who = "root"
auth.append(f"Mar 15 {stamp()} kali sshd[2200]: Failed password for {who} from {ip} port {random.randint(40000, 60000)} ssh2")
auth.append(f"Mar 15 23:50:00 kali sshd[2201]: Accepted password for root from {BREACHED} port 51000 ssh2")
open("auth.log", "w").write("\n".join(sorted(auth)) + "\n")
web = open("base-access.log").read().splitlines()
for _ in range(SPIKE_SIZE):
t = f"{SPIKE_HOUR:02d}:{random.randint(0, 59):02d}:{random.randint(0, 59):02d}"
web.append(f'{SPIKE_IP} - - [15/Mar/2025:{t} +0000] "GET / HTTP/1.1" 200 {random.randint(200, 5000)}')
for path in ATTACKS:
for ip in ATTACKERS:
web.append(f'{ip} - - [15/Mar/2025:{stamp()} +0000] "GET {path} HTTP/1.1" {random.choice([200, 403, 500])} {random.randint(200, 900)}')
open("access.log", "w").write("\n".join(sorted(web)) + "\n")
EOFAnalyst.
A. Write auth_analysis.py that reads auth.log and produces:
- A list of IPs that have more than 10 failed login attempts, sorted descending by attempt count
- The list of user accounts being targeted (which usernames are attackers guessing?). sshd writes
Failed password for invalid user <name> from ...when the account does not exist, so your pattern must treat the words “invalid user” as optional; the real/var/log/auth.logand the logs the engineer plants contain both forms. - The ratio of failed to successful logins overall
- Every address with a successful login after a run of failures (the highest-value finding, because the guessing may have worked)
B. The web access log is the second planted file, access.log. Each line is ip - - [timestamp] "GET path HTTP/1.1" status bytes. Baseline traffic includes harmless percent-encoded requests such as /search?q=network%20security, so a rule that flags every % produces false positives; decode the request path before you match attack patterns.
C. Write log_analysis.py that reads access.log and produces:
- All requests matching SQL injection, path traversal, XSS, or command injection patterns (use the regex from the theory section as a starting point, but extend it)
- Top 5 IPs by request volume
- HTTP status code distribution
D. Implement the 3-sigma anomaly detector on hourly request counts. Your output should identify anomalous hours and report their z-score:
[ANOMALY] 03:00 — 950 requests (z≈4.7σ, threshold=3.0σ)
Your exact value depends on the random counts in your log, but with one spike hour among 24 it will be close to 4.7.
E. Combine the outputs of A–D into a single report.md file with sections for each finding category.
Handoff 4, analyst to engineer: send
report.md.
Engineer: score the analyst. Compare report.md with planted.json. Write findings_score.md listing, for every planted item, whether it was detected, and for every report item, whether it was planted (false positive). Return the list of misses to the analyst.
Together: the custom payloads are the likeliest misses. For each miss, decide whether the cause is a weak pattern (for example a pattern that ignores invalid user, a regex that stops at a space, an unencoded payload) or a limit of the 3-sigma method, and fix the analyzer. Record each fix in one line in findings_score.md.
Question
The 3-sigma rule assumes data is approximately normally distributed. Web server traffic often has strong daily periodicity (high during business hours, low overnight). How does this periodicity affect the validity of a single global baseline? Describe a modified approach that would produce fewer false positives on a server with predictable daily traffic cycles.
The analyst answers this question and the engineer reviews the answer against the scoring.
Part 4: Integrated reconnaissance tool
Build recon.py — a single-file command-line tool that performs multi-stage reconnaissance on a domain or IP address and produces a structured report.
Before writing code, agree on the shape of results.json and write it in the README: one top-level key per tool (whois, dig, curl, nmap), each holding the structured fields listed in the requirements. The engineer implements requirements 1, 3 and 4 (the stages that run whois, dig, curl -I and nmap); the analyst implements requirements 2, 5 and 6 (audit log, results.json assembly and report.md).
Handoff 5, analyst to engineer: early in Part 4, send a function
run_logged(cmd)that runs a command withsubprocess, writes the command, its outcome and a timestamp toaudit.log, and returns the output. The engineer’s stages call it instead of callingsubprocess.rundirectly, which is what makes the audit log complete.
Handoff 6, engineer to analyst: when the stages work, send a run of the stages as a
results.jsonproduced against the target inscope.txt(IP mode). The analyst builds the report from that file.
Requirements:
-
CLI interface via
argparse:target: domain name or IP address (required)--mode:domainorip, auto-detected if omitted--output: directory for output files (default:./recon_<target>_<timestamp>/)--verbose: print progress to stderr as the tool runs
-
Audit log — every action the tool takes must be logged to
audit.loginside the output directory with a timestamp. This includes: what command was run, what it returned (success/error), and the timestamp. This is non-negotiable. -
Domain mode — when
targetis a domain name:whois: extract registrar, registration date, expiry date, registrant organizationdig: query and save A, MX, NS, and TXT recordscurl -I: extract HTTP response headers (server, X-Powered-By, Content-Security-Policy, Strict-Transport-Security)- Each step runs independently; a failure in one must not stop the others
-
IP mode — when
targetis an IP address:nmap -sV --open -oX: scan common ports (use the--top-ports 100flag to keep it fast), parse the XML output as in Part 2- Reverse DNS lookup via
dig -x whoison the IP to extract the owning organization and country
-
Structured output — write
results.jsonwith all findings in a single dict keyed by tool name. -
Markdown report — generate
report.mdfromresults.json. The report must include: a summary table of findings, open ports (if IP mode), DNS records (if domain mode), and any notable security headers that are missing (CSP, HSTS, X-Frame-Options).
Together: merge both halves into the single file recon.py, run it once in each mode, and have the engineer check that every command in audit.log corresponds to a command that actually ran and that no stage ran without being logged. The engineer reports any gap to the analyst.
Grading criteria:
| Criterion | Weight |
|---|---|
| Audit log present and accurate | 20% |
| Each step fails independently without crashing | 20% |
results.json contains structured data (not raw text) | 25% |
report.md is readable and complete | 20% |
| Argparse works correctly for both modes | 15% |
Question
Your tool performs active reconnaissance: it sends packets to the target. Shodan performs passive reconnaissance: it has already scanned the internet, and you query its database without touching the target at all. From the perspective of an attacker, what are the operational differences between these two approaches? From the perspective of a defender with network monitoring in place, which approach is harder to detect, and why? In what scenarios would each be more appropriate?
The question is answered by whichever of you was not the author of the final merge, and the other reviews it.
Submission
A link to a public GitHub repository with the following structure:
├── scanner.py # Part 1: concurrent port scanner
├── parse_scan.py # Part 2: nmap XML parser and enricher
├── auth_analysis.py # Part 3: auth log analysis
├── log_analysis.py # Part 3: web log analysis + anomaly detection
├── recon.py # Part 4: integrated tool
├── scope.txt # Part 0: authorized target and time window
├── planted.json # Part 0: what the engineer planted in the logs
├── findings_score.md # Part 3: planted items versus report, misses and fixes
├── scan_rate200.json # Part 1: scan at --rate 200
├── scan_rate2000.json # Part 1: scan at --rate 2000
├── sample_output/ # One run of recon.py in IP mode against the address in scope.txt, and one in domain mode against a domain you own or example.com (reserved for documentation, RFC 2606)
│ ├── results.json
│ ├── report.md
│ └── audit.log
└── README.md # Setup instructions, per-script explanation and a "Who did what" section
The README.md must include: Python version and dependencies (state explicitly that none beyond the standard library are needed, or give the pip install command for any you added), how to run each script with an example command, a brief explanation of what each script does and why the design choices you made are appropriate, and a “Who did what” section listing which role wrote each script and which handoff files crossed between you.
Key concepts
| Term | Definition |
|---|---|
| SYN scan | Port scan that sends SYN and reads the response without completing the TCP handshake; requires root privileges |
| TCP three-way handshake | SYN → SYN-ACK → ACK sequence that establishes a TCP connection; the basis of port state detection |
| Concurrency | Executing multiple tasks that overlap in time; essential for performant network scanning |
asyncio | Python’s built-in async I/O framework; uses a single-threaded event loop for high-concurrency network tasks |
ThreadPoolExecutor | Python’s managed thread pool for I/O-bound parallel tasks |
| Rate limiting | Capping the speed of automated requests to avoid detection and avoid harming target systems |
| IDS | Intrusion Detection System; network monitoring tool that flags anomalous traffic patterns like port scans |
| Threat intelligence | Structured data about known malicious actors, IPs, domains, and file hashes from external sources |
| Shodan | Search engine for internet-exposed services; provides passive reconnaissance without touching the target |
| VirusTotal | Multi-engine malware analysis service accessible via API for file hash and URL reputation checks |
| 3-sigma rule | Statistical rule stating ~99.7% of normal data falls within 3 standard deviations; used to detect anomalies |
| Audit log | Timestamped record of actions a script performed; required in professional penetration testing engagements |
subprocess | Python module for spawning and interacting with external processes and capturing their output |
argparse | Python module for building CLI argument parsers; makes scripts configurable and reusable |
| OPSEC | Operational Security; practices that protect sensitive information and avoid exposing credentials or methods |