Two small security tools in Python
Build a port scanner and a hash cracker, and learn what the real tools do.
Before you start: Only scan systems you own or have written permission to test. Pointing a scanner at the wrong host can count as unauthorized access. If you are not sure, the answer is no.
Most security tools are normal programs. nmap opens network connections. hashcat hashes guesses. Writing a small version yourself is a good way to learn what the real tool does.
We will build two tools: a port scanner and a hash cracker.
You need Python 3.10 or newer and a terminal. Save each code block to the filename in its label, in the same folder, then run it with python3.
Tool 1: a port scanner
A port is a numbered door on a computer. A port scanner tries each door and reports which ones open.
The simple version opens one connection at a time. That is slow. We will use threads to try many ports at once.
"""portscanner.py — a tiny concurrent TCP port scanner for authorized use."""
import argparse
import socket
from concurrent.futures import ThreadPoolExecutor, as_completed
def probe(host: str, port: int, timeout: float = 1.0) -> bool:
"""Try a TCP connect to (host, port)."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
# connect_ex returns 0 on success, an error code otherwise.
return s.connect_ex((host, port)) == 0
def scan(host: str, ports: range, workers: int = 100) -> list[int]:
open_ports: list[int] = []
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(probe, host, p): p for p in ports}
for future in as_completed(futures):
if future.result():
open_ports.append(futures[future])
return sorted(open_ports)
def main() -> None:
parser = argparse.ArgumentParser(description="Tiny TCP port scanner.")
parser.add_argument("host", help="target host (only scan what you own)")
parser.add_argument("--start", type=int, default=1)
parser.add_argument("--end", type=int, default=1024)
parser.add_argument("--workers", type=int, default=100)
args = parser.parse_args()
try:
host_ip = socket.gethostbyname(args.host)
except socket.gaierror:
raise SystemExit(f"Could not resolve {args.host}.")
if not (0 <= args.start <= args.end <= 65535):
raise SystemExit("Port range must be between 0 and 65535.")
print(f"Scanning {args.host} ports {args.start}-{args.end} "
f"with {args.workers} workers...")
for port in scan(host_ip, range(args.start, args.end + 1), args.workers):
print(f" {port:>5}/tcp open")
if __name__ == "__main__":
main()
What the code does:
connect_extries to connect and returns an error code instead of crashing. A refused connection is normal when you scan many ports.withcloses the socket when it is done, so you do not run out of file handles.- Threads work well here because the program spends most of its time waiting for answers. For work that uses the CPU heavily, use processes.
- 100 workers is a safe default. More can trigger an intrusion detection system (IDS) or use up your own ports.
Run it on your own machine:
# Scan localhost ports 1-1024 with 100 workers.
python3 portscanner.py 127.0.0.1
# Scan a wider range with more workers.
python3 portscanner.py 127.0.0.1 --start 1 --end 65535 --workers 200
If something is listening on localhost, you will see its port. If nothing is, the command prints only the "Scanning..." line. Both are normal.
This scanner does not fingerprint services, use SYN scanning, or rate-limit itself. Those are good next steps. A real scanner like nmap, masscan, or zmap does much more.
Tool 2: a hash cracker
A hash is a fingerprint of some data. The same input always makes the same fingerprint. You cannot turn the fingerprint back into the input. That is why cracking is guessing: hash a guess, compare, repeat.
This tool tries every word in a wordlist against one hash. The hash has no salt, meaning no extra random value was mixed in.
"""hashcracker.py — dictionary attack against a single unsalted hash.
For learning only. Real tools like hashcat and john are much faster
because they use GPUs.
"""
import argparse
import hashlib
import sys
from concurrent.futures import ProcessPoolExecutor
from functools import partial
def hash_word(word: str, algorithm: str) -> str:
"""Return the hex digest of `word` using `algorithm`."""
h = hashlib.new(algorithm)
h.update(word.encode("utf-8"))
return h.hexdigest()
def crack(target: str, wordlist: str, algorithm: str = "sha256") -> str | None:
"""Return the first word whose hash matches `target`, or None."""
target = target.strip().lower()
with open(wordlist, "r", encoding="utf-8", errors="ignore") as f:
words = [line.rstrip("\r\n") for line in f]
hasher = partial(hash_word, algorithm=algorithm)
with ProcessPoolExecutor() as pool:
for word, digest in zip(words, pool.map(hasher, words, chunksize=500)):
if digest == target:
return word
return None
def main() -> None:
parser = argparse.ArgumentParser(description="Dictionary hash cracker.")
parser.add_argument("hash", help="target hash (hex)")
parser.add_argument("wordlist", help="path to a wordlist")
parser.add_argument("--algo", default="sha256", help="hashlib algorithm name")
args = parser.parse_args()
print(f"Cracking {args.algo} hash with {args.wordlist}...")
result = crack(args.hash, args.wordlist, args.algo)
if result is None:
print("No match found.")
sys.exit(1)
print(f"Match: {result}")
if __name__ == "__main__":
main()
Make a small wordlist, create a hash, and run it:
# A small wordlist for testing.
printf 'password\nletmein\nhunter2\n' > words.txt
# Generate the SHA-256 of "letmein".
# On Linux:
printf 'letmein' | sha256sum
# On macOS:
printf 'letmein' | shasum -a 256
# 1c8bfe8f801d79745c4631d09fff36c82aa37fc4cce4fc946683d7b336b63032
# Try to crack it.
python3 hashcracker.py \
1c8bfe8f801d79745c4631d09fff36c82aa37fc4cce4fc946683d7b336b63032 \
words.txt
What to notice:
- The cracker uses processes, not threads, because hashing is CPU-heavy. Python has a lock called the GIL that stops two threads from running Python code at the same time.
chunksize=500sends words in groups. Without it, Python sends one task per word, and the overhead can make it slower than a simple loop.- The hash comparison is case-insensitive because some tools print uppercase and some print lowercase.
- There is no salt handling. If the hash used a salt, you would need to know it and add it to
hash_word. A salt does not stop guessing, but it blocks precomputed lists of common hashes and makes each guess cost more. - The script loads the whole wordlist into memory. That is fine for a small list. For something like
rockyou.txt, process it in batches or usehashcat.
What to build next
- A folder brute-forcer for HTTP, like
gobuster. Same idea: target, wordlist, worker pool, check. - A log parser that flags strange user agents, 4xx spikes, or one IP scanning many paths.
- A small IDS that watches a packet capture and alerts on SYN scans.
The Python concurrency guide on Real Python is a good next read. The hashlib and socket docs are short and worth reading.