Skip to content

Latest commit

 

History

History
155 lines (115 loc) · 8.25 KB

File metadata and controls

155 lines (115 loc) · 8.25 KB

Security Tool Development

Build professional, maintainable security tools in Python — from raw sockets and scanners to packaged, tested, plugin-driven CLIs.

Part of the [[Readme|Python for Security Professionals]] course.

Overview

This module takes you from writing one-off scripts to engineering real security tooling. The first notes cover the networking and cryptography building blocks (sockets, HTTP, hashing, packets); the later notes cover the software engineering that makes a tool distributable and dependable (architecture, CLI, config, plugins, packaging, testing, logging). Every example is defensive and educational, targeting localhost or authorized lab systems only.

Warning

The offensive techniques here (scanning, packet crafting, PoC exploits) are for systems you own or are explicitly authorized to test. Unauthorized use is illegal. Practice on 127.0.0.1 and isolated lab VMs.

Learning Objectives

  • Communicate over the network with TCP/UDP sockets, HTTP, and raw packets.
  • Build a working threaded port scanner and understand banner grabbing.
  • Generate strong secrets and verify data integrity with hashes and HMAC.
  • Structure a tool with clean separation of concerns so it can grow.
  • Ship a tool as a tested, configurable, plugin-extensible, pip-installable CLI.

Prerequisites

  • [[Object-Oriented-Programming/Readme|Object-Oriented Programming]] — tools are structured around classes.
  • [[Scripts,-Modules,-Packages,-and-Libraries/Readme|Modules & Packages]] — socket, ssl, hashlib, argparse, and packaging.
  • [[Python-Automation-for-Security/Readme|Python Automation for Security]] — concurrency and subprocess.
  • [[Error-and-Exception-Handling/Readme|Error & Exception Handling]] — network code fails constantly.

Topics Covered

Foundations — networking, HTTP & crypto building blocks

  • [[Socket-Programming-for-Networking|Socket Programming for Networking]] — TCP/UDP clients and servers
  • [[HTTP-Requests-and-API-Interaction|HTTP Requests and API Interaction]] — requests, sessions, auth
  • [[Hash-Generation-and-Verification|Hash Generation and Verification]] — hashlib, hmac, integrity
  • [[Password-Utility-Scripts|Password Utility Scripts]] — secrets, entropy, strength scoring

Building blocks — offensive tooling

  • [[Building-Port-Scanners|Building Port Scanners]] — a threaded TCP connect scanner
  • [[Packet-Manipulation-with-Scapy|Packet Manipulation with Scapy]] — craft, send, and sniff packets
  • [[Custom-Exploit-Development-Basics|Custom Exploit Development Basics]] — PoC structure: target/payload/delivery

Engineering — designing a maintainable tool

  • [[Security-Tool-Architecture|Security Tool Architecture]] — layout and separation of concerns
  • [[CLI-Tools-with-Argparse|CLI Tools with Argparse]] — a proper command-line interface
  • [[Configuration-Files|Configuration Files]] — CLI/env/INI/YAML with precedence
  • [[Plugin-Architecture|Plugin Architecture]] — dynamic loading, registries, entry points
  • [[Logging-and-Output|Logging and Output]] — structured logging, verbosity, Rich
  • [[Testing-Security-Tools|Testing Security Tools]] — pytest and mocking the network

Packaging — shipping it

  • [[Packaging-and-Distribution|Packaging and Distribution]] — pyproject.toml, entry points, pip, pipx

Practical Exercises

  • Build the threaded port scanner, then refactor it into a layered core/cli/io package.
  • Add an argparse CLI with a validating port-range type and -v/-vv verbosity.
  • Layer configuration from defaults → YAML file → env vars → CLI flags.
  • Turn the tool into a plugin runner and add two drop-in check plugins.
  • Package it with pyproject.toml, unit-test it with mocked network calls, and pipx install it.

Security Applications

This module is where the earlier material becomes a deliverable. The recurring architecture:

cli.py         argument parsing only - no logic
core/          the engine: pure functions and classes, returns data
  scanner.py   probes and result collection
  models.py    Target, Port, Result
report/        renders results as text, JSON, or Markdown
plugins/       pluggable checks behind one interface
  • Socket programming — TCP and UDP clients and servers, the foundation under every scanner and listener.
  • Port scanners — a threaded connect scanner with timeouts, rate limiting, and structured output.
  • HTTP and API interaction — sessions, authentication, retries, and pagination against authorized endpoints.
  • Packet manipulation — crafting and sniffing with Scapy, which requires root and a lab network.
  • Password utilities — generating strong credentials with secrets and scoring strength by entropy.
  • Hash generation and verification — integrity checking and evidence checksums with hashlib and hmac.
  • Exploit development basics — PoC structure (target, payload, delivery, verification) against intentionally vulnerable local targets.

[!warning] Authorized testing only Everything in this module generates traffic or interacts with a target. Build and run these tools only against systems you own, intentionally vulnerable lab VMs, or CTF environments. Exploit-development material here is conceptual and lab-scoped — it teaches structure and defensive understanding, not deployment against real-world systems.

Common Mistakes

  • No timeout on a socket — a filtered port blocks the scanner for the OS default, often minutes.
  • Not closing sockets — use a context manager, or descriptors leak during a long sweep.
  • shell=True when wrapping an external tool — command injection.
  • Disabling TLS verification (verify=False) to make a script work, silently accepting any certificate.
  • Mixing engine and presentation — a scanner that print()s cannot be reused, tested, or given a JSON mode.
  • Hardcoded targets or credentials in the tool source.
  • No rate limiting, degrading the target and guaranteeing detection.
  • Unbounded concurrency exhausting local resources.
  • Fabricated offsets or addresses in exploit examples — they are environment-specific and must be derived in your own lab.

Best Practices

  • Separate the engine from the interface: core returns data, CLI renders it.
  • Set a timeout on every network operation and use with for every socket.
  • Put an authorization/scope check in the engine, not just the CLI.
  • Support both human-readable and machine-readable output from day one.
  • Log to stderr and emit data on stdout so the tool composes in a pipeline.
  • Return a meaningful exit code so the tool can gate a CI pipeline.
  • Test with pytest, mocking the network so tests never send real traffic.
  • Package the tool with pyproject.toml and a console entry point.

Review Questions

  1. What is the difference between connect() and connect_ex() on a socket, and why does a scanner prefer the latter?
  2. When should a security tool separate its engine from its command-line interface?
  3. What security issue can occur if a tool disables TLS certificate verification to work around an error?
  4. How would you troubleshoot a port scanner that reports every port as closed?
  5. Why should exploit-development examples avoid hardcoded offsets and addresses?
  6. Write a Python example of a socket client that always closes its connection, even when the probe raises.

Commands

# run the scanner against localhost only
python -m http.server 8080 &
python scanner.py 127.0.0.1 -p 8000-8100

# set up a proper project and install it as a command
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest -q
mytool --help

References

Related Notes

  • [[Hashlib-Module|Hashlib Module]]
  • [[Argparse-Module|Argparse Module]]
  • [[Socket-Module|Socket Module]]
  • [[Scapy]]
  • [[Rich]]
  • [[Readme|Python for Security Professionals]]

Navigation

  • Previous: [[Python-Automation-for-Security/Readme|13. Python Automation for Security]]
  • Home: [[Readme|Course Home]]
  • Next: [[Practical-Labs/Readme|Practical Labs]]