
Security tools are only trustworthy when you know exactly what they run on. A script that behaves differently on two machines can hide a vulnerability or invent a false alarm. In this opening lecture you will verify an isolated Python environment, the foundation of the lab you will use for the whole course.
You will begin with the reasons for isolation. A security lab should be separate from your everyday work, so that experiments cannot affect your normal files and so that package versions cannot drift without your knowledge. You will learn what a virtual environment is and why it is the standard Python answer.
Next you will create one with the venv module and activate it on your operating system. You will then write a short verification script that checks the environment from the inside. It will print the interpreter path and version, compare sys.prefix with sys.base_prefix to decide whether the environment is active and refuse to continue with a clear message if it is not.
You will add the idea of a lab safety banner, a short check that confirms the script is running in the intended place before any tool does its work. This is a good habit for security tooling, where running something in the wrong context can have real consequences.
You will also discuss ground rules for the course. Every exercise uses local, synthetic or deliberately built practice targets, and you should only ever test systems that you own or have written permission to assess.
By the end of this lecture you will be able to create and verify an isolated environment and apply a simple safety check at the start of a security script.
Before you trust a lab, you should know what is installed in it. Every package is code that runs with your privileges, and an unexpected one is worth noticing. In this lecture you will inspect the installed packages in your lab environment.
You will begin with the tools Python gives you for this. You will run pip list and pip show on the command line to see names, versions and dependencies, and then do the same from Python using importlib.metadata, which lets a script read the same information programmatically. You will loop over the installed distributions and print their names and versions in a sorted table.
Next you will use the data. You will write a function that returns the installed packages as a dictionary and another that checks whether a required package is present and at an acceptable version, using simple version comparison. You will explore how a package declares its own requirements, and why one package can bring many others with it, which is the starting point for understanding supply chain risk.
You will save an inventory of the environment as JSON, with the date and the Python version, so that you have a record to compare with later. You will discuss why an inventory is a basic security control, since you cannot defend what you cannot list.
You will practise by installing a small, harmless package, running the inventory again and spotting the difference.
By the end of this lecture you will be able to list and describe installed packages from the command line and from Python and save an inventory.
A lab that was correct last month may not be correct today if packages quietly change underneath it. This is called dependency drift, and in security work it is a risk to both reliability and safety. In this lecture you will pin dependencies and detect drift.
You will begin with the difference between loose and pinned requirements. A line that names a package without a version can resolve to a different release next time, while a pinned line with double equals fixes one exact version. You will see why pinning matters for repeatable results and for knowing precisely which code you ran.
Next you will create a requirements file from your environment with pip freeze and read it carefully. You will write a drift checker in Python. It reads the pinned file, reads the installed packages with importlib.metadata and reports each package as matching, missing, a different version or extra. You will print the report and exit with a non-zero status if drift is found, so that a script or scheduler can react.
You will test by changing the environment on purpose, installing a different version of a small package, and watching the checker catch it. You will then restore it.
You will discuss related practices, such as keeping a separate file for development tools, updating pinned versions deliberately and reviewing changes, and how hashes in requirements files can strengthen integrity.
By the end of this lecture you will be able to pin dependencies and write a drift detector that fails loudly.
Over the course you will build many small tools, and each one needs the same things: a way to take options, a consistent help message and predictable error handling. Instead of rebuilding these every time, you will create a reusable command-line scaffold. In this lecture you will build it with argparse.
You will begin with what a good command-line interface offers. Users expect a clear usage line, helpful descriptions, sensible defaults and error messages that say what went wrong. You will see why reading sys.argv by hand quickly becomes fragile.
Next you will build the scaffold. A function creates an ArgumentParser with a description and common options that every tool will share, such as a verbosity flag, an output format choice between text and JSON and a dry-run switch. Another function adds tool-specific arguments, and a main function ties together parsing, logging setup and a call to the tool's logic. You will use subcommands to let one program offer several related actions.
You will add the logging configuration from the start, with levels controlled by the verbosity flag, and make sure that tools return an exit code. You will include a prominent reminder in the help text that the tool must only be used on systems that you are authorised to test.
You will test the scaffold by calling it with a list of arguments, which allows tests to run without a terminal.
By the end of this lecture you will be able to build a reusable, testable command-line scaffold that you will use throughout the course.
File hashing is one of the most useful ideas in security. A hash is a short fingerprint calculated from the contents of a file, and if the contents change in any way, the fingerprint changes completely. In this lecture you will hash a small file with hashlib.
You will begin with what a hash function does. It turns data of any size into a fixed-length value, it always gives the same output for the same input and it is designed so that you cannot work backwards from the output or easily find two inputs with the same result. You will see these properties in practice by hashing a short string and then changing a single character.
Next you will hash a file. You will open it in binary mode, read its bytes and pass them to hashlib.sha256, then call hexdigest to get the readable value. You will compare SHA-256 with older algorithms such as MD5 and SHA-1, and learn why those are no longer suitable when security matters, although you may still meet them in legacy contexts.
You will write a function that takes a path and returns the digest, with clear errors for a missing or unreadable file. You will create two practice files with identical content and different names, confirm that their hashes match and then alter one byte and see the difference.
You will discuss practical uses, including checking downloads, detecting tampering and recognising known files.
By the end of this lecture you will be able to compute and compare file hashes and explain why hash choice matters.
Reading an entire file into memory to hash it works for small files, but a large file can use a great deal of memory or fail altogether. The solution is to process the file in chunks. In this lecture you will hash large files with chunked reading.
You will begin by demonstrating the problem on a larger practice file that you generate with a short script, using synthetic data of a few hundred megabytes or less. You will observe the memory use of the simple approach and understand why it does not scale.
Next you will use the update method of the hash object. Instead of passing all the bytes at once, you read a fixed-size block, such as sixty-four kilobytes, and feed it to update, repeating until the file ends. You will use a loop with the two-argument form of iter, or the walrus operator, to read until an empty block is returned. At the end, hexdigest gives the same result as the one-shot approach, and you will prove it by comparing the two on a smaller file.
You will experiment with different block sizes and time them, seeing that very small blocks are slow and very large ones bring little extra benefit. You will add an optional progress message for long files.
You will also make the function flexible, accepting an algorithm name, and reject algorithms that are not available. You will test the function on files of different sizes, including an empty file.
By the end of this lecture you will be able to hash files of any size efficiently with constant memory use.
How do you know that a set of files has not been changed? One answer is a checksum manifest, a list of files and their expected hashes that you can check at any time. In this lecture you will verify integrity against a checksum manifest.
You will begin with the idea, which is the basis of file integrity monitoring. You calculate a trusted hash for each file when you know the files are in a good state, store the results in a manifest and later recompute the hashes and compare. Any difference shows that a file has changed, which might be a legitimate update or a sign of tampering.
Next you will write a function that builds a manifest for a practice folder. It walks the folder with pathlib, hashes each file in chunks and records the relative path, the hash and the size in a dictionary, which you save as JSON. You will use relative paths so that the manifest works when the folder is moved.
Then you will write the verification. It reads the manifest, recomputes the hashes and reports each file as unchanged, modified, missing or new, with a summary and an exit status. You will test it by altering, deleting and adding files in the practice folder.
You will discuss the limits. A manifest stored next to the files could be altered by the same person who alters the files, so it should be protected, and a signature or a separate trusted location strengthens it.
By the end of this lecture you will be able to build and verify a checksum manifest.
Security logs can be enormous, and loading a whole log into memory just to look for a few lines is wasteful. Generators let you process a log one line at a time. In this lecture you will stream log lines with generators.
You will begin with the idea of lazy evaluation. A generator function uses the yield keyword to produce values one at a time, pausing between them, so that the program only holds the current item in memory. You will write a very small generator and iterate over it to see the behaviour, and compare it with a function that builds a full list.
Next you will apply it to files. You will write a function that opens a log file and yields each line stripped of its newline, and another generator that takes any stream of lines and yields only those that contain a keyword. You will chain generators together into a pipeline, one that reads, one that filters and one that transforms, and see how the data flows through without ever being stored in full.
You will create a synthetic log file with thousands of invented entries, including a few lines that look like failed logins, so that you have something realistic to search. You will measure the memory used by the generator approach against loading everything.
You will also handle practical matters, such as encoding errors with a replacement strategy, files that grow while being read and closing files properly with a with statement inside the generator.
By the end of this lecture you will be able to write generators and build memory-efficient pipelines for reading logs.
A log line is just text until you extract its meaning. To search, count and alert on events, you need to turn each line into a structured record with fields such as the time, the source address and the type of event. In this lecture you will parse log entries into structured findings with regular expressions.
You will begin with the format of a typical authentication log line from a synthetic file that you generate, with a timestamp, a host name, a process and a message. You will study the text and identify the parts that you want to capture.
Next you will write a regular expression using named groups, which gives each captured part a meaningful name. You will compile it with re.compile, use match or search on each line and convert the result into a dictionary with the groupdict method. You will then convert the timestamp into a datetime object and the address into an ipaddress object, which validates it and allows comparisons.
You will handle lines that do not match, counting them and keeping a few examples for review instead of ignoring them silently, which is an important habit because unexpected formats often hide interesting events. You will define a small data class for a finding, with a type, a severity, a source and the original line.
You will classify lines with several patterns, such as failed logins, successful logins and invalid users, and produce a summary count by type and by source address. You will discuss regular expression performance and the danger of patterns that can take very long on crafted input.
By the end of this lecture you will be able to parse logs into structured data safely and summarise the results.
Network programming starts with the idea of moving bytes between two programs. Before you ever touch a real network, you can learn the whole pattern on your own machine. In this lecture you will send and receive bytes over a socket pair.
You will begin with the concept of a socket as an endpoint for communication. You will learn the difference between a stream socket and a datagram socket, and why the streaming kind, which TCP uses, does not preserve message boundaries. This is the source of many beginner bugs and an important idea for any network tool.
Next you will use socket.socketpair, which creates two connected sockets inside your own program, with no network access at all. You will send a message from one side with sendall and read it from the other with recv, and see that you are sending bytes, not text, so you must encode and decode explicitly. You will send several messages quickly and observe how they can arrive joined together, then solve it with a simple framing scheme, such as a length prefix or a newline delimiter.
You will handle closing sockets properly with context managers and see what happens when one side closes, with recv returning an empty bytes object.
You will write a tiny echo exchange between two threads using the pair, to practise the request and response pattern.
Everything runs locally and nothing leaves your computer.
By the end of this lecture you will be able to send and receive framed bytes with sockets and understand stream behaviour.
When a service accepts a connection, it often sends a short message announcing what it is, called a banner. Reading banners is a basic way for an administrator to inventory their own services. In this lecture you will perform banner grabbing with timeouts, against local practice services that you start yourself.
You will begin with the purpose. Defenders use banner information to check that the right software and versions are running on their own systems, and to find forgotten services. You will emphasise that you should only connect to systems that you own or are explicitly authorised to test, since even a simple connection can be unwelcome or a breach of policy elsewhere.
Next you will build the practice target. You will write a small server using the socket module that listens on the loopback address, accepts a connection and sends a made-up banner line. You will run it in a thread so that everything stays on your machine.
You will then write the client. It creates a socket, sets a timeout with settimeout so that it never hangs, connects, reads up to a limited number of bytes and returns the decoded text. You will handle the errors you may meet, including a refused connection, a timeout and a service that sends nothing, and report each distinctly.
You will limit the amount of data read and decode safely, since banners from unknown services can contain unexpected bytes.
You will finish by checking the banner against an expected pattern and flagging a mismatch.
By the end of this lecture you will be able to read service banners with safe timeouts and error handling in a controlled lab.
A scanner needs a list of things to examine, and writing every address and port by hand does not scale. In this lecture you will expand targets and port ranges from compact descriptions.
You will begin with the notations that administrators use. Network ranges are written in CIDR form, such as an address followed by a slash and a prefix length, and port lists combine single numbers with ranges, such as a few ports and a range separated by commas. You will learn what these mean and why they are convenient.
Next you will use the ipaddress module. You will parse a network with ip_network, count its addresses, iterate over its hosts and test whether an address belongs to it. You will see how the module validates input and raises a clear error for a malformed address, and how it distinguishes IPv4 and IPv6.
You will write a parser for port specifications. It splits on commas, expands ranges with range, validates that every port is between one and sixty-five thousand five hundred thirty-five, removes duplicates and returns a sorted list. You will test it with a variety of valid and invalid strings.
An important safety feature is a scope check. You will write a function that refuses to produce targets outside an allow list that you define, such as the loopback range, and add a limit on the total number of targets. This models the way professional assessments are tied to a written scope.
By the end of this lecture you will be able to expand and validate target and port specifications and enforce a scope.
Network tools spend almost all their time waiting for replies. Asynchronous programming lets a single program handle many waiting operations at once. In this lecture you will write your first coroutines with asyncio, the foundation of the concurrent scanner in the next lecture.
You will begin with the problem. If a tool checks one port at a time and each check may wait a second for a response, then a thousand checks take a thousand seconds. Doing them one after another wastes time that could be spent on the others.
Next you will learn the key ideas. A coroutine is a function defined with async def, which can pause at an await expression and let other work run. An event loop schedules the coroutines. You will write a coroutine that simulates a slow check with asyncio.sleep, run it with asyncio.run and see that calling it without await does not run it.
You will run several coroutines together with asyncio.gather, and time the result to see that ten one-second waits take about one second in total. You will create tasks with create_task, and use asyncio.wait_for to apply a timeout and handle the error that follows.
You will also learn the main pitfall. A blocking call, such as time.sleep or a plain socket read, inside a coroutine freezes the entire loop, so you must use awaitable versions or run the blocking work in a thread.
You will use only simulated delays in this lecture, so that nothing touches a network.
By the end of this lecture you will be able to write coroutines, run them concurrently and apply timeouts.
Now you will combine sockets and asyncio into a concurrent port scanner for use only on your own lab targets. In this lecture you will build a bounded concurrent port scanner.
You will begin with the purpose and the boundaries. Administrators scan their own systems to find services that should not be exposed, which is a standard defensive task. You will keep the scanner locked to the loopback address and a lab service that you start yourself, and include the scope check from the earlier lecture, so that the tool refuses anything else.
Next you will write the check. A coroutine uses asyncio.open_connection with asyncio.wait_for to attempt a connection with a timeout. A successful connection means the port is open, a refusal means closed and a timeout means filtered or unresponsive. You will close the connection cleanly and return a small result record.
The key lesson is bounding the concurrency. Launching thousands of connections at once can exhaust file descriptors, overwhelm a target or trigger defences. You will use an asyncio.Semaphore to limit the number of simultaneous attempts, and gather the results while preserving their order. You will make the limit a setting and discuss sensible values.
You will start a few local listeners on chosen ports, scan a range and compare the results with what you started. You will print a tidy summary and write the findings in JSON, using the command-line scaffold from earlier.
You will discuss responsible use, including permission, rate limits and logging what was done.
By the end of this lecture you will be able to write a bounded, scope-limited asynchronous scanner and test it against local services.
Understanding network traffic means understanding how packets are built, layer by layer. Scapy is a Python library that lets you create and examine packets as objects. In this lecture you will build packets layer by layer with Scapy, entirely offline.
You will begin with a review of the layered model in plain terms. An Ethernet frame carries an IP packet, which carries a TCP segment or a UDP datagram, which carries application data. Each layer has its own header fields, such as addresses, ports and flags, and each wraps the one above it.
Next you will install Scapy in your lab environment and import the layers you need. You will create objects for IP, TCP and Raw data and stack them with the slash operator, which is Scapy's notation for putting one layer on top of another. You will set fields such as the source and destination addresses, using documentation addresses that are reserved for examples, ports and flags, and print the packet with show to see the structure and the default values that Scapy fills in.
You will learn how to read individual fields, change them and see how derived fields, such as lengths and checksums, are calculated when the packet is built. You will not send anything. The packets exist only in memory, and you will inspect them to learn what each field means.
You will also discuss why defenders build packets, for example to create test data for detection rules and to understand protocol behaviour.
By the end of this lecture you will be able to construct and inspect layered packets without sending them.
A packet object is convenient to work with, but on the wire it is only a sequence of bytes. Understanding the conversion in both directions is essential for analysis. In this lecture you will serialise packets to raw bytes and back.
You will begin by building a packet as in the previous lecture and converting it with bytes, which asks Scapy to assemble the headers, calculate the lengths and compute the checksums. You will print the result as hexadecimal and use a small helper to display it in a readable dump with offsets, hex values and printable characters.
Next you will study the bytes. You will locate the version and header length in the first byte, the total length, the protocol number, the addresses and the TCP ports, and compare what you read by hand with what Scapy reports. This helps you connect the abstract fields to the actual data.
You will then go the other way. Given a sequence of bytes, you will rebuild the packet by calling the layer class on them, such as IP applied to the bytes, and see Scapy decode the fields. You will compare the decoded packet with the original and confirm that they are identical, which shows that the process is reliable.
You will experiment with deliberately damaged bytes, such as a truncated packet or a wrong checksum, and see how the library and your own validation functions respond.
You will write a function that validates basic properties of a byte string before parsing it.
By the end of this lecture you will be able to move between packet objects and bytes and read headers from a hex dump.
Packet captures are the standard way to record network traffic for later study. They are saved in the PCAP format. In this lecture you will write and read PCAP files offline, using packets that you generate yourself.
You will begin with what a capture file contains. It has a global header that identifies the format and the link type, followed by a series of records, each with a timestamp, the length and the packet bytes. You will see why a capture is a precise record that can be shared and analysed repeatedly, and why captures must be handled carefully, since they can contain sensitive data.
Next you will create a small set of packets with Scapy, such as a few synthetic web requests and replies between documentation addresses, and give each a distinct timestamp. You will save them with wrpcap and open the file in a hex viewer to recognise the header. You will also write a minimal PCAP by hand with the struct module, to see exactly how the format is organised.
You will then read the file back with rdpcap, loop through the packets and print a summary of each, with the time, the addresses, the protocol and the length. You will use a PcapReader for large files so that packets are processed one at a time instead of being loaded together.
You will count packets by protocol and by address pair, and calculate the capture's duration and average rate.
By the end of this lecture you will be able to create and analyse capture files without any live network access.
A capture may contain thousands of packets, and an analyst needs to focus on the ones that matter. In this lecture you will filter packets by layer and flags.
You will begin with the questions that filtering answers. Which packets use TCP? Which are connection attempts? Which come from a particular address? You will generate a synthetic capture that mixes many kinds of traffic, including normal web exchanges, a few DNS queries and some unusual packets, and save it as a PCAP file.
Next you will use Scapy's layer tests. Writing packet.haslayer with a layer class tells you whether a layer is present, and indexing the packet with the class retrieves it. You will write functions that select packets with an IP layer, with a TCP layer and with a specific port.
You will then work with TCP flags. You will learn what the SYN, ACK, FIN, RST and PSH flags mean in the life of a connection, and read the flags field as a value that combines these bits. You will write a helper that tests individual flags with bit operations, and filter for packets that have only the SYN flag set, which are the first step of a connection, and for resets, which are replies from closed ports.
You will combine filters in a small query function that accepts conditions, and return both the packets and a count. You will compare your filtering with the capture filter language used by common tools.
By the end of this lecture you will be able to filter packets by layer, address, port and flag and read the flags correctly.
Defenders often need to recognise reconnaissance in their own traffic. One well-known pattern is a SYN scan, in which a source sends connection requests to many ports and never completes the connections. In this lecture you will detect a SYN scan from a capture.
You will begin with the behaviour. A normal client opens a few connections and completes them. A scanner sends a SYN to many different ports in a short time, and for closed ports receives resets. The distinctive signs are many distinct destination ports from one source, many unanswered or reset attempts and little or no completed data.
Next you will create the data. You will generate a synthetic capture containing normal sessions and one simulated scan, built from documentation addresses with Scapy, so that you know the right answer. You will save it as a PCAP file.
You will then write the detector. You will read the packets, keep only those with just the SYN flag, group them by source address and count the number of distinct destination ports and the time span. You will apply a threshold, such as more than a chosen number of ports within a chosen number of seconds, and report the sources that exceed it with the evidence.
You will test for false positives and false negatives by adjusting the thresholds, and discuss how a legitimate monitoring system or a busy proxy might look like a scanner. You will make the thresholds settings in your command-line tool.
By the end of this lecture you will be able to implement and tune a basic scan detection rule and explain its limits.
Before you can assess a web application's security, you must understand what an HTTP response really looks like on the wire. Libraries hide the details, and the details are where many security issues live. In this lecture you will read a raw HTTP response over a local socket pair.
You will begin with the structure of the protocol in plain terms. A response starts with a status line that gives the protocol version, a status code and a reason phrase. It continues with header lines, each a name and a value separated by a colon, then a blank line made of a carriage return and a line feed and finally the body.
Next you will build a tiny local setup using socket.socketpair, with one side acting as a server that sends a prepared response from a byte string and the other side as a client that reads it. No network is involved. You will read from the socket until the header terminator appears, which teaches you why you cannot assume that one read gives a whole message.
You will parse the response by hand. You will split the head from the body at the blank line, split the head into lines, parse the status code into an integer and turn the headers into a dictionary with lowercase names, handling repeated headers such as cookies carefully. You will then use the Content-Length header to read exactly the right number of body bytes.
You will compare your parser with the http.client module's behaviour, and discuss why strict parsing matters, since disagreements between parsers are a source of real vulnerabilities.
By the end of this lecture you will be able to read and parse raw HTTP responses and explain their structure.
Security headers are instructions that a web server sends to browsers to switch on protective behaviour. A missing header is one of the most common and easily fixed weaknesses. In this lecture you will audit security headers on a local practice application.
You will begin with the headers that matter and what each is for, in plain language. Strict-Transport-Security tells browsers to use encrypted connections, Content-Security-Policy limits where scripts and other resources may load from, X-Content-Type-Options stops a browser guessing the type of content, a framing policy helps prevent clickjacking, Referrer-Policy limits what is shared when following links and Permissions-Policy limits browser features. You will also note the headers that reveal too much, such as detailed server version information.
Next you will build the target. You will write a small WSGI application, which you will run in-process with the wsgiref tools or by calling it directly, that returns responses with different sets of headers. One has none of the protections, one has some and one has a good configuration.
You will write the auditor. It takes a dictionary of headers, checks each expected one against a rule, such as present, present with a required value or absent, and returns findings with a severity, a short explanation and a recommended fix. You will give the output as a score and a table.
You will discuss that the right policy depends on the application, and that an audit is a checklist and not a guarantee.
By the end of this lecture you will be able to audit response headers and produce clear findings and recommendations.
Cookies carry session identifiers, which makes them valuable and a common target. A few flags decide whether a cookie is well protected. In this lecture you will audit session cookie flags on a local practice application.
You will begin with the flags and what they do. Secure ensures that the browser sends the cookie only over encrypted connections. HttpOnly keeps the cookie out of reach of scripts running in the page, which limits the damage of certain bugs. SameSite restricts when the cookie is sent in requests started from other sites, reducing the risk of cross-site request forgery. Domain, Path and expiry settings control scope and lifetime, and a cookie name prefix can enforce extra rules.
Next you will examine the Set-Cookie header. You will use http.cookies.SimpleCookie and the lower-level parsing of the header to read the name, value and attributes, taking care with attributes that have no value, such as Secure and HttpOnly. You will work with example headers from your own practice WSGI application, with one well configured session cookie and several poorly configured ones.
You will write the auditor. For each cookie, it checks the flags, flags a session cookie lacking Secure or HttpOnly, warns about missing SameSite or an excessively long lifetime and notes cookies that appear to carry readable data. It returns findings with severity and advice, using the same structure as the header auditor.
You will discuss how to set the flags correctly in your own application code.
By the end of this lecture you will be able to parse Set-Cookie headers and audit their protective flags.
If a session cookie is stolen, whoever holds it may be treated as the user. Understanding why helps you design stronger defences. In this lecture you will replay a session cookie against a local WSGI application that you control, to see how session handling can fail.
You will begin with the concept. A server that identifies users only by a cookie value cannot tell the real user from anyone who presents the same value. You will explain, at a conceptual level, how cookies can leak, for example through unencrypted connections or through scripts, and why the flags from the previous lecture and short lifetimes reduce the risk. You will not use any real accounts or sites.
Next you will build the practice application. It is a small WSGI function with a login that issues a random session identifier, an in-memory session store and a protected page that returns a greeting only when a valid session cookie is present. You will call it directly with a test helper that builds the request environment, with no server needed.
You will log in as an invented user, capture the cookie, and then call the protected page with the cookie from a new, separate client, and observe that it is accepted. This demonstrates the weakness in a harmless setting.
You will then add defences and test them again. These include expiring sessions, rotating the identifier at login, binding a session to extra attributes where appropriate and invalidating it on logout.
By the end of this lecture you will be able to explain session replay and implement basic mitigations in a local test application.
Injection flaws occur when an application mixes untrusted input into a command or query. Testing for them safely is a core skill for defenders and for developers who write tests. In this lecture you will probe a local practice application for SQL injection weaknesses, and learn how to fix them.
You will begin with the concept in plain language. If an application builds a database query by joining strings, special characters in the input can change the meaning of the query. The safe approach is to use parameterised queries, which keep data separate from the command. You will stress the rules of engagement: you will test only the practice application that you build in this lecture, which uses an in-memory SQLite database filled with invented data.
Next you will create two versions of a small lookup function. One is deliberately written the unsafe way, and the other uses placeholders with a parameter tuple. You will explain why each behaves as it does.
You will write a harmless probe. It takes a short list of benign test strings, such as an unmatched quotation mark, and checks the application's responses for signs of a problem, such as an unhandled database error or a response that differs in a suspicious way. You will not use payloads that extract or alter data. The goal is to detect the weakness and report it.
You will run the probe against both versions, see it flag the unsafe one and pass the safe one, and write findings with remediation advice.
You will discuss defence in depth, including least privilege for database accounts and input validation.
By the end of this lecture you will be able to test for injection weaknesses safely and fix them with parameterised queries.
Storing passwords safely is one of the most important and most frequently mishandled security tasks. A plain or quickly hashed password is disastrous if a database leaks. In this lecture you will hash passwords with salts using hashlib.scrypt.
You will begin with why ordinary hashes are not enough. A fast hash such as SHA-256 allows an attacker who steals a database to test billions of guesses per second. Passwords need a deliberately slow, memory-hungry function so that each guess is expensive. You will also learn what a salt is, a unique random value for each password that prevents identical passwords from producing identical hashes and defeats precomputed tables.
Next you will use os.urandom or the secrets module to generate a random salt of sufficient length. You will call hashlib.scrypt with the password encoded as bytes, the salt and the cost parameters n, r and p, and a chosen output length. You will learn what the parameters control, how raising them increases the work needed and how to select values that take a noticeable fraction of a second on your hardware.
You will design a storage format that keeps everything needed to check the password later, such as an identifier of the algorithm, the parameters, the salt and the hash, encoded together in one string. This makes it possible to increase the cost in the future while still verifying older entries.
You will use only invented passwords in the exercises and explain that real passwords must never be written to code or logs.
By the end of this lecture you will be able to produce salted scrypt hashes and a self-describing storage format.
Creating a hash is only half of the story. When a user logs in, you must check their password against the stored value correctly and safely. In this lecture you will verify stored password hashes.
You will begin by reading the storage format from the previous lecture. A function splits the string into its parts, decodes the salt and the expected hash, reads the parameters and validates that the format is as expected, refusing anything malformed or using parameters that are unreasonably large, which would let an attacker cause excessive work.
Next you will recompute the hash. You will take the password supplied by the user, apply scrypt with the stored salt and parameters and compare the result with the stored hash. You will learn why the comparison must use hmac.compare_digest, which takes the same time regardless of where the first difference occurs, and why an ordinary equality check could leak information through timing.
You will return only a simple true or false and use the same generic message for a wrong password and an unknown user, so that the response does not reveal which usernames exist. You will also add a dummy hash computation for unknown users to keep the timing similar.
You will then implement an upgrade path. If a stored hash uses weaker parameters than the current policy, the function can signal that the entry should be rehashed after a successful login.
You will test with correct and incorrect invented passwords, tampered records and unusual input, including very long passwords.
By the end of this lecture you will be able to verify password hashes using constant time comparison and support parameter upgrades.
Not all passwords are equal, and the length and variety of a password affect how hard it is to guess. A strength audit can help an organisation find weak choices in its own systems. In this lecture you will audit password strength with entropy estimates, using made-up passwords only.
You will begin with the concept of entropy, a measure of unpredictability, expressed in bits. For a password chosen at random from a set of characters, the entropy is the length multiplied by the base-two logarithm of the size of the set. Each extra bit doubles the number of guesses needed. You will calculate it for several examples and see how length contributes more than complexity rules.
Next you will write an estimator. It determines which character classes appear, calculates the pool size, applies the formula and reports the result. You will then see its weakness. Human-chosen passwords are not random, so a password such as a common word with a digit on the end has far less real strength than the formula suggests.
You will improve the audit with practical checks. You will compare passwords against a small list of common choices that you write yourself, detect repeated characters, sequences and keyboard patterns, and reduce the estimate when such patterns are found. You will classify results into weak, fair and strong, and explain why in the output.
You will discuss modern guidance, which favours length, a check against known breached passwords and password managers over frequent forced changes.
You will never log the passwords themselves, only the scores.
By the end of this lecture you will be able to estimate and explain password strength and understand the limits of the estimate.
Hashing protects passwords, but you also need to protect data that must be read again later, such as a stored secret or a message. Encryption does that. In this lecture you will use authenticated encryption with Fernet.
You will begin with the difference between hashing and encryption. A hash is one way, while encryption can be reversed with the right key. You will also learn why plain encryption is not enough. Without authentication, an attacker who can modify the encrypted data might change it in ways that go undetected. Authenticated encryption ensures that any tampering is noticed.
Next you will install the cryptography package and use Fernet, a high-level recipe that combines AES encryption with an integrity check and a timestamp. You will generate a key with Fernet.generate_key, create a Fernet object, encrypt a short invented message and print the resulting token. You will decrypt it and confirm that you get the original back.
You will test the integrity protection. You will change one character in the token and see the InvalidToken error when you decrypt, and you will use the ttl option to reject tokens that are too old. You will learn that the key is the secret that must be protected, and see how a key can be derived from a passphrase with a key derivation function and a salt.
You will discuss key handling, including never hard-coding keys, storing them in a secrets manager or environment, rotating them with MultiFernet and understanding that losing the key means losing the data.
By the end of this lecture you will be able to encrypt and decrypt data safely with Fernet and handle tampering and expiry.
Static analysis examines a file without running it, and it is the safest way to learn about unknown software. One of the simplest static techniques is extracting printable strings. In this lecture you will extract printable strings from a binary blob, using a harmless synthetic blob that you create.
You will begin with the purpose. Programs often contain readable text, such as file paths, messages, addresses and function names, that gives hints about what they do. Analysts commonly extract these strings as a first step in triage. You will emphasise safe handling rules: work in an isolated lab, never execute unknown samples and in this course use only data that you generate.
Next you will create a practice blob. A script builds a byte string that mixes random bytes with a few readable strings, such as a made-up URL on a reserved example domain and a fake message, and some padding. This stands in for a real binary without any risk.
You will write the extractor. It scans the bytes and collects runs of printable ASCII characters of at least a minimum length, using a regular expression on bytes or a simple state machine. You will extend it to find UTF-16 little-endian strings, which are common in Windows programs, by looking for printable characters alternating with zero bytes. You will return the offset of each string along with its text.
You will then filter the results for interesting categories, such as URL-like text, and sort and de-duplicate them.
By the end of this lecture you will be able to extract and categorise strings from binary data safely.
Executable files on Windows use the Portable Executable format, and its header describes what the file is and how it is organised. Reading it is a standard part of static analysis. In this lecture you will parse a PE header with struct, using a small synthetic header that you build yourself.
You will begin with the structure of the format in plain terms. A file starts with the letters MZ, which belong to a legacy DOS header. A field at a fixed offset points to the PE signature, followed by the file header, which includes the machine type, the number of sections and a timestamp, and by the optional header, which includes the entry point and sizes. A table of section headers follows.
Next you will learn the struct module. You will use format strings to unpack binary fields, with a prefix that selects little-endian byte order and codes for integers of different sizes, and see how to calculate the size of a format.
You will build a minimal synthetic file in memory containing a valid-looking header with chosen values, no executable code and no real program. You will then write a parser that checks the MZ marker, follows the pointer to the PE signature, validates it and unpacks the file header fields, converting the timestamp to a date and the machine code to a name.
You will add careful bounds checking at every step, since malformed files are common in the real world and a parser must never trust offsets blindly. You will report errors clearly.
By the end of this lecture you will be able to read binary structures with struct and parse a PE header defensively.
YARA is a tool and rule language that analysts use to describe patterns in files so that known families and suspicious traits can be found automatically. In this lecture you will scan files with YARA rules using harmless test content.
You will begin with the idea. A rule has a name, optional metadata, a strings section that defines patterns to look for and a condition that says how they must combine. Rules can match text, hexadecimal byte sequences and regular expressions, and conditions can count matches or check file properties. You will explain how defenders use rules to find indicators across many files.
Next you will install yara-python in your lab environment and write a first rule. It looks for a made-up marker string that you plant yourself in a test file, such as a phrase that exists only in your exercise. You will compile the rule with yara.compile, scan a file or bytes with match and read the result, including which strings matched and at what offsets.
You will write several rules with different conditions, such as requiring two of three strings, combining text and a PE marker, and using a length check. You will test them against a folder of synthetic files that includes matches, near-misses and clean files, and count true and false results.
You will discuss rule quality, including the cost of overly broad rules, the importance of testing on clean files and the use of metadata to record the author, purpose and date.
By the end of this lecture you will be able to write, compile and run YARA rules and evaluate their accuracy.
After collecting strings, header details and rule matches, an analyst needs to bring the findings together in a form that others can read and act on. In this lecture you will build a triage report for suspicious samples, using synthetic files only.
You will begin with the purpose of triage. It is a quick first look that decides how much further attention a file deserves. A good triage report is short and consistent, and it states clearly what was observed and what was not checked. You will recall the safety rules: samples are never executed, analysis happens in an isolated lab and in this course the samples are harmless files you generate.
Next you will design the report. Each entry contains the file name, size, several hashes, the detected file type, a summary of the header information if applicable, interesting strings, the YARA matches and an overall assessment level with reasons. You will represent it as a data class that can be converted to a dictionary.
You will write the pipeline that combines your earlier tools. For each file in a folder, it computes hashes with chunked reading, checks the type from the first bytes, parses the header safely if it is a PE file, extracts and categorises strings and runs the rules. A simple scoring function converts the evidence into a level, such as informational, suspicious or high interest, and records the reasons.
You will output the results in JSON and as a readable text summary sorted by level, and handle failures on individual files without stopping the batch.
By the end of this lecture you will be able to combine static analysis tools into a structured, explainable triage report.
Brute-force attempts leave a distinctive pattern in logs: many failed logins from one source in a short time. Detecting it requires counting events over a moving window. In this lecture you will build a sliding window brute-force detector, using synthetic logs.
You will begin with the behaviour. A single failed login is normal, since people mistype. Dozens within a minute from the same address are not. A detector must therefore consider both the number of failures and the time period. A fixed bucket per minute can miss an attack that straddles two buckets, so you will use a sliding window instead.
Next you will learn the data structure. For each source address, you will keep a deque of the timestamps of recent failures. When a new event arrives, you add its timestamp, remove the entries older than the window from the left and check whether the length exceeds the threshold. You will explain why a deque is efficient for this, since adding and removing at the ends takes constant time.
You will generate a synthetic log that includes normal activity, a few ordinary mistakes and one simulated burst of failures, and process it with the log parser from earlier. You will emit an alert only once per episode, using a cooldown, to avoid flooding the analyst.
You will write tests with fixed timestamps, so that results are deterministic, and tune the window and threshold to balance missed detections against false alarms. You will also handle clock oddities, such as events that arrive out of order.
By the end of this lecture you will be able to implement a sliding window detector, test it deterministically and tune it.
Hard-coding every detection in Python makes it difficult to change and review. Security teams prefer to describe rules as data, which analysts can edit and version without touching the program. In this lecture you will write detection rules as data.
You will begin with the motivation. A rule that lives in a configuration file can be reviewed by someone who does not write Python, changed quickly in response to a new threat and tested separately. This is the same idea that underlies widely used detection rule formats.
Next you will design a simple rule format in JSON or a similar structure. A rule has an identifier, a name, a severity, a description, a data source or event type, a set of conditions and a recommended action. Conditions might say that a field equals a value, that a field matches a pattern, or that a count over a window exceeds a threshold. You will write several example rules, including one that uses the sliding window.
You will then write the engine. A loader reads the rules and validates them, rejecting unknown fields and invalid patterns. A matcher applies each rule to each event, using a table that maps condition types to small functions. You will precompile the regular expressions once, and make the engine return a list of alerts with the rule identifier, severity and the evidence.
You will test with synthetic events, including cases that should not match, and write a check that every rule has at least one example that triggers it.
You will discuss rule lifecycle, including versioning, review and retirement.
By the end of this lecture you will be able to define, validate and run detection rules from data.
An alert that says only that an address did something is much more useful if you also know whether that address is already known to be bad. Threat intelligence feeds supply that context. In this lecture you will enrich indicators using a mock threat intelligence feed that you create.
You will begin with the idea of an indicator of compromise, such as an IP address, a domain or a file hash, and with the way that organisations share lists of them. You will explain that feeds vary in quality, that an indicator can go out of date and that the confidence and source of each entry are as important as the entry itself.
Next you will create the mock feed as a JSON file containing invented indicators, with fields for the type, the value, a category, a confidence level, the source, the first and last seen dates and an expiry. You will use documentation address ranges and reserved example domains, so that nothing refers to a real system.
You will write the lookup layer. It loads the feed into dictionaries keyed by type and value, so that checks take constant time, normalises values before lookup, such as lowercasing domains, and ignores expired entries. You will write a function that takes an alert and adds a list of matching indicators and an adjusted severity.
You will test with alerts that match, partly match and do not match, and discuss caching, rate limits and privacy when using real services, since sending an indicator to a third party can itself reveal information.
By the end of this lecture you will be able to enrich alerts with indicator context and handle expiry and confidence.
Detections only help if people see them. A report that is clear, consistent and prioritised turns raw alerts into action. In this lecture you will generate automated alert reports.
You will begin by thinking about the readers. A busy analyst wants the most urgent items first, a short explanation of why each was raised, the evidence and a suggested next step. A manager wants totals and trends. You will design a report that serves both, with a summary at the top and details below.
Next you will take the alerts produced by your earlier tools, including the brute-force detector and the rule engine, and group them by severity and by source. You will count them, calculate the first and last times and identify the most active sources. You will remove duplicates and combine repeated alerts into a single entry with a count, which reduces noise.
You will then render the report in several formats. You will write JSON for other programs, a Markdown or plain text version for people and a simple HTML page using string templates, taking care to escape any text taken from logs, since log content can contain characters that would otherwise be interpreted by a browser. You will include the time range, the data sources and the versions of the rules.
You will save the report with a dated name, handle empty results gracefully with a clear statement that nothing was found and log what was done.
By the end of this lecture you will be able to produce prioritised, safe and well-structured alert reports in several formats.
The capstone combines the whole course into a single assessment tool. The first step is a common language. Every scanner, auditor and detector produces results in its own shape, and combining them requires a shared structure. In this lecture you will define a unified finding model.
You will begin by looking at what the tools you have built produce. The port scanner reports open ports, the header auditor reports missing headers, the password auditor reports weak choices and the detector reports alerts. They all describe a finding of some kind, but with different fields, which makes combining them awkward.
Next you will design the model. A finding has an identifier, a title, a description, a category, a severity from a defined scale, a confidence, the target or asset it concerns, the evidence, a recommendation, references and the name of the check that produced it and a timestamp. You will implement it as a data class with type hints, using an enumeration for the severity so that only valid values are possible, and add validation in the post-init step.
You will write methods that convert a finding to and from a dictionary, so that it can be saved as JSON, and a sort key that orders by severity and then by title. You will give each finding a stable fingerprint, calculated from its key fields, so that the same issue found twice can be recognised and merged.
You will update a small sample of your earlier tool outputs to produce findings in the new model.
By the end of this lecture you will be able to define and validate a unified, serialisable finding model.
With a shared finding model in place, each tool in the course can be turned into a check that fits into one framework. In this lecture you will wrap scanners as pluggable check functions.
You will begin with the design. A check is a function that receives a context, such as the target description, the settings and a scope, and returns a list of findings. By agreeing on this signature, the assessment tool can run any check without knowing its details, and new checks can be added without changing the existing code.
Next you will build the registry. A dictionary maps check names to functions, and a decorator registers a function with metadata such as its name, description and category. You will write a runner that looks up the requested checks, runs each one inside a try and except block so that a failure in one does not stop the others, records the duration and collects the findings together with any errors. You will include the scope check, so that every check refuses targets outside the permitted list.
You will wrap several earlier tools as checks, for example the header audit, the cookie audit, the file integrity check and the password policy check, all running against the local practice targets and synthetic data. You will make the set of checks selectable from the command line.
You will test the registry, the runner and error isolation by registering a check that raises an exception on purpose.
By the end of this lecture you will be able to design a plugin-style check framework and wrap existing tools within it.
Individual findings are useful, but decision makers want an overview. The next step is to aggregate findings into a risk summary and save a report. In this lecture you will build the aggregation and the JSON report.
You will begin with the summary. You will group the findings by severity and by category, count them and calculate an overall risk rating, using a transparent rule, such as weights for each severity, which you will document in the output. You will list the most important findings first, and identify the checks that failed to run, since a missing result is not the same as a clean result.
Next you will de-duplicate. Using the fingerprints from the unified model, you will merge findings that represent the same issue found by different checks, keeping the highest severity and combining the evidence. You will record how many were merged.
You will then build the report as a dictionary containing metadata, such as the tool version, the date, the scope and the checks that were run, the summary, the sorted findings and the errors. You will write it with json.dump, with indentation and sorted keys for stable output, using a safe write pattern that creates a temporary file and then replaces the final one, so that a crash cannot leave a half-written report.
You will add a short text summary for the console, set the exit code according to the highest severity found, so that automation can react, and check the file by loading it again.
You will discuss the importance of stating the limits of the assessment clearly.
By the end of this lecture you will be able to aggregate, de-duplicate and summarise findings and write a reliable JSON report.
A security tool that is not tested cannot be trusted, since a bug could hide a real problem. In this final lecture you will test the assessment tool with unittest, which is included with Python.
You will begin with the basics. A test case is a class that inherits from unittest.TestCase, and each method whose name starts with test is run separately. You will use assertions such as assertEqual, assertIn, assertRaises and assertTrue, and run the suite with python -m unittest, learning how to read the output for failures and errors.
Next you will plan what to test. You will write tests for the finding model, including that invalid severities are rejected and that serialisation round-trips. You will test the aggregation with small, hand-built lists of findings where you can calculate the expected summary, and the de-duplication with findings that share a fingerprint. You will test the check runner to confirm that an exception in one check is recorded and does not stop the others, and that a target outside the scope is refused.
You will use setUp and tearDown, or temporary directories from the tempfile module, so that each test starts clean and never touches real files. You will use unittest.mock to replace the clock and any function that would touch a socket, so that the tests are fast, deterministic and never perform network activity.
You will also write regression tests for the detectors, using fixed synthetic inputs, and measure which parts of the code are covered.
By the end of this lecture you will be able to write a reliable unittest suite for a security tool and run it with confidence.
This course contains the use of artificial intelligence.
Master Python for Cybersecurity and develop practical skills in Ethical Hacking, Security Automation, Network Security, Penetration Testing, Malware Analysis, Cryptography, Digital Forensics, and Threat Intelligence through hands-on coding exercises and real-world security scenarios.
Welcome to Python for Cybersecurity: 25 Hands-On Projects, a comprehensive, project-based course designed to help developers, cybersecurity professionals, and aspiring ethical hackers transform their Python programming knowledge into practical cybersecurity solutions.
Cybersecurity threats are constantly evolving, and organizations need professionals who can automate security operations, detect vulnerabilities, investigate suspicious activities, and develop custom security tools. This course takes you beyond theoretical concepts and teaches you how to build functional Cybersecurity Tools using Python from scratch.
You will begin by establishing an isolated cybersecurity lab, managing Python dependencies, and building reusable Command-Line Interface (CLI) tools. Learn how to implement File Integrity Monitoring, SHA-256 Hashing, Checksum Verification, Log Analysis, and Regular Expressions to identify security-related events and potential threats.
Explore Network Security and Network Reconnaissance by working with Python sockets, asynchronous programming, concurrent port scanners, service banner analysis, and IP address processing. Develop practical experience with Scapy, Packet Crafting, Packet Analysis, TCP/IP, PCAP Files, and Network Traffic Monitoring to understand network communications and detect suspicious behavior.
Dive into Web Application Security, Vulnerability Assessment, HTTP Security Headers, Session Management, Cookie Security, and SQL Injection Testing. Understand common application vulnerabilities, investigate security misconfigurations, and implement defensive programming techniques within controlled testing environments.
Strengthen your understanding of Applied Cryptography, Password Security, Password Hashing, Encryption, Decryption, Key Derivation, Password Entropy, and Authenticated Encryption. Learn how modern cryptographic techniques protect sensitive information and help prevent unauthorized access.
Discover the fundamentals of Malware Analysis, Digital Forensics, Binary Analysis, Static Malware Analysis, YARA Rules, and Security Incident Investigation. Build Python tools that extract suspicious artifacts, inspect executable file headers, identify malicious patterns, and generate structured security triage reports.
Develop essential Security Operations Center (SOC), Threat Hunting, Threat Detection, Security Monitoring, and Threat Intelligence skills. Create automated brute-force detection systems, configurable detection rules, indicator-of-compromise lookup tools, and security alert reporting solutions.
Throughout this course, you will gain practical experience with:
Python Cybersecurity Programming and Security Scripting
Ethical Hacking and Penetration Testing Fundamentals
Network Scanning and Packet Analysis
Web Application Vulnerability Testing
Cyber Defense and Security Automation
Cryptography and Secure Password Management
Malware Detection and Digital Forensics
Threat Intelligence and Security Incident Detection
Automated Cybersecurity Reporting
Secure Coding and Software Security Testing
The course concludes with a comprehensive Cybersecurity Capstone Project, where you will develop an integrated security assessment tool combining multiple scanning capabilities, standardized security findings, risk assessment, JSON reporting, and automated unit testing.
With 9 comprehensive modules and 40 practical lessons, this course emphasizes learning by doing rather than memorizing cybersecurity terminology. The exercises are designed around controlled, authorized environments, without requiring expensive commercial security software or paid cloud services.
Whether you are a Python Developer, Cybersecurity Analyst, Ethical Hacker, Security Engineer, SOC Analyst, DevSecOps Engineer, Network Administrator, IT Professional, or Computer Science Student, this course will help you develop valuable, industry-relevant cybersecurity programming skills.
Build your Cybersecurity Portfolio, strengthen your technical confidence, and transform Python into your personal cybersecurity toolkit.
Enroll today and start building practical Python-Powered Cybersecurity Solutions!