Module 4 · Programming for Cyber Security · Lesson 12 of 75

Python for networks, web and hashes; PowerShell; reading code for bugs

Sockets, HTTP requests and hashing in Python, PowerShell scripting for Windows, and how to spot dangerous patterns when reading code.

In this lesson · about 40 minutes

  • Recognise how Python talks to networks and websites
  • Hash data with hashlib and compare file fingerprints
  • Spot injection, hard-coded secrets and unsafe input handling in code

Talking to the network

import socket
s = socket.create_connection(("10.10.30.10", 22), timeout=2)   # lab host only
print(s.recv(100))       # b'SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13\r\n'  (a "banner")
s.close()

That is the heart of a port scanner and a banner grabber in five lines. Real scanners such as Nmap do the same thing, faster and more carefully.

Talking to websites

import requests
r = requests.get("http://127.0.0.1:3000/api/products", timeout=5)
r.status_code, r.headers.get("Server"), r.json()[0]

Web testers use requests to replay and tweak requests, test many inputs, and check security headers.

Hashing

import hashlib
hashlib.sha256(b"invoice.pdf contents").hexdigest()

A hash is a fingerprint of data (Module 6). Analysts hash files to look them up in threat-intel databases and to prove evidence has not changed.

PowerShell scripting

# Find local admins on many PCs (run from an admin workstation in your lab)
$pcs = Get-Content .\computers.txt
foreach ($pc in $pcs) {
  Invoke-Command -ComputerName $pc -ScriptBlock {
    Get-LocalGroupMember Administrators | Select-Object Name
  } | ForEach-Object { "$pc,$($_.Name)" }
}

Reading code for security bugs

You will review code in Modules 11 and 23. Start by looking for these patterns:

PatternDangerSafer version
"SELECT * FROM users WHERE name = '" + name + "'"SQL injectionParameterised query: cur.execute("... WHERE name = %s", (name,))
os.system("ping " + host)Command injection (host = "8.8.8.8; rm -rf /")subprocess.run(["ping", "-c", "1", host]) with validation
API_KEY = "sk_live_51H..." in the sourceHard-coded secret, leaked with the codeEnvironment variable or a secrets manager
eval(user_input), pickle.loads(data)Runs attacker-controlled codeParse with json.loads; never eval input
verify=False in requestsTurns off certificate checks (man-in-the-middle)Keep verification on

Exercise

Did the file change?

Write fingerprint(data) that returns the SHA-256 hex digest of a bytes value, then set changed to True if before and after have different fingerprints.

Code that runs before yours
before = b"Pay supplier 4471 the sum of 1,200.00 to account 0098-1121"
after = b"Pay supplier 4471 the sum of 1,200.00 to account 0098-7754"

Sorting drill

Safe or dangerous?

You are reviewing a pull request. Sort each line.

  • cur.execute("SELECT * FROM orders WHERE id = %s", (order_id,))
  • os.system("nslookup " + request.args["domain"])
  • token = os.environ["PAYMENT_TOKEN"]
  • requests.get(url, verify=False)
  • data = json.loads(body)
  • result = eval(request.form["formula"])

0 of 6 sorted

Flashcards

Module 4 flashcards

0 of 10 known

Say the answer out loud, flip the card, then be honest: cards you miss come back at the end.

10 left in the deck

Practice exam

Module 4 checkpoint

8 questions, 10 minutes.

  • 8 questions · 10 minutes
  • No feedback until you submit. Flag questions to come back to them.
  • Aim for 85% or better before you move on. The real exam's 750 out of 900 is roughly 80–83%.

Exercises solved: 0 of 1

Tip: solve each exercise first. Press Check to test your code.

Written by Noviq Academy in its own words. All labs are simulations: no real systems are touched, and every name, address, password and hash is made up. The offensive techniques taught here are for defending systems and for authorised testing only; never scan, access or test a system without the owner's written permission. Tool and product names belong to their owners, and command output may differ slightly from yours. Read-aloud uses your device's built-in voices.