SECURITY ENGINEERING · PART 3 · SCRIPTING AND AUTOMATION · PYTHON · 38 OF 229

Python for Security Engineers: Requests, Sockets

The parts of Python a security engineer actually uses, each as a small working snippet: reading and counting log lines with re and Counter (the same 412 failed logins as the Bash episode), hashing files with hashlib, checking addresses with ipaddress, talking to web services with requests, raw connections with socket, JSON in and out, and the habits that keep a security script from becoming a security problem.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • re and Counter for logs
  • hashlib
  • ipaddress
  • requests for APIs
  • socket
  • JSON and exit codes
  • secrets out of code

Notes

Parse a log

First, the same job as the Bash episode, in Python. A regular expression describes the line we care about and captures the user and the address. A Counter keeps the tally. The loop reads the file one line at a time, so it works on a log of any size without loading it into memory. Most common three prints the top three. On our practice log it reports the same result: four hundred and twelve failures from one address.

Count failed logins by address
import re, collections
pat = re.compile(r"Failed password for"
  r" (?:invalid user )?(\S+) from (\S+)")
hits = collections.Counter()
with open("auth.log") as f:
    for line in f:
        m = pat.search(line)
        if m:
            hits[m.group(2)] += 1
print(hits.most_common(3))

Why Python here

Why bother, when Bash did this in one line? Because the count is now data you can reason about. You can apply a threshold, compare against an allow list of your own office addresses, look each address up in a reputation service, and decide what to do, all in the same script with proper error handling. On the practice log, two addresses pass the threshold of fifty. That decision step is where Python earns its place.

From a count to a decision
for ip, n in hits.most_common():
    if n >= 50:
        print("block", ip, n)

# output on the practice log
block 203.0.113.9 412
block 198.51.100.23 87

# next: check each against an
# allow list, a geo lookup, an API

hashlib

Next, hashing. A hash is a fingerprint of a file's contents. This function reads the file in chunks, so it can hash something larger than memory, and returns the SHA two fifty six value. Security engineers use it constantly: to verify that a download is the file the vendor published, to detect that a system file has changed, and to look a suspicious file up in a malware database without uploading the file itself.

Hash a file safely
import hashlib
def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(
                lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()

# use: verify downloads, detect
# changed files, look up malware

ipaddress

Addresses are not strings, and comparing them as strings causes bugs. The ipaddress module understands them. You can ask whether an address is private, and whether it falls inside a network range. That turns questions like is this login from inside the company, or is this destination in a range we have blocked, into one clear line. Both checks here return true for our practice data.

Reason about addresses
import ipaddress as ipa
ipa.ip_address("10.0.0.9").is_private
# True
net = ipa.ip_network("203.0.113.0/24")
ipa.ip_address("203.0.113.9") in net
# True

# is this source internal?
# is it inside a blocked range?

requests

Nearly every security product, cloud and code platform is driven through a web API, and the requests library is how Python talks to them. Four habits are visible in this snippet. The token comes from an environment variable, never from the source code. There is a timeout, so a hung server cannot hang your script. Raise for status turns an error response into an exception instead of silent bad data. And certificate checking stays on, always.

Call an API, carefully
import os, requests
r = requests.get(
    "https://api.example/v1/findings",
    headers={"Authorization":
        "Bearer " + os.environ["TOKEN"]},
    params={"severity": "critical"},
    timeout=10)
r.raise_for_status()
for f in r.json()["items"]:
    print(f["id"], f["title"])

socket

Sometimes you need to go one level below HTTP. The socket module opens raw network connections. This small function tries to connect to a host and port and reports whether it worked: connect ex returns zero on success and an error number otherwise, such as one hundred and eleven for connection refused. It is the building block of the port scanner you write in the next episode, and of quick checks like is our database port reachable from here?

Is a port open?
import socket
def is_open(host, port):
    s = socket.socket()
    s.settimeout(1)
    try:
        return s.connect_ex(
            (host, port)) == 0
    finally:
        s.close()
# 0 = connected; an error code
# such as 111 = refused

JSON and exit codes

A security script is rarely the last step. Something else consumes its output: a pipeline, a ticket system, a chat alert. So print structured output, usually JSON, which every tool can read. And set the exit code: zero when all is well, non-zero when something was found. That one convention is how a script becomes a gate in a build pipeline, because the pipeline stops when a step exits with an error.

Make it usable by machines
import json, sys
result = {"ip": "203.0.113.9",
          "failed": 412}
print(json.dumps(result))
# {"ip": "203.0.113.9", "failed": 412}

sys.exit(1 if findings else 0)
# a non-zero exit code fails
# the pipeline step

More modules

A few more modules complete the kit. Argparse for command-line options. Pathlib for files. Subprocess to run other programs, always with the arguments as a list, never as one shell string built from outside input. The csv and json modules for common formats. Logging instead of print statements for anything you will run unattended. Datetime, in UTC, because investigations cross time zones. The cloud libraries and scapy get their own episodes.

Worth knowing
  • argparse: command-line options
  • pathlib: files and folders
  • subprocess: run a command (pass a list, never shell=True with outside input)
  • csv, json: common formats
  • logging: not print, for tools
  • datetime: use UTC
  • boto3 / cloud SDKs (episode 6)
  • scapy: packets (episode 4)

Scripts with power

One more thing separates a security engineer's scripts. They often hold powerful credentials, so write them as if they matter. Secrets come from the environment or a secret manager, never the file. Use a read-only token unless the script truly must write. Give anything that changes things a dry-run mode. Validate input and stop on anything unexpected. Pin your dependencies, because a malicious package runs with your script's access. And log what it did.

Write it like it matters
  • secrets from the environment or a secret manager, never in the file or in git
  • least privilege: a read-only token unless it must write
  • a --dry-run flag for anything that changes things
  • validate input; fail closed
  • pin and review dependencies
  • log what it did

Common mistakes

Mistakes. An API key pasted into the source and pushed to git. Certificate checking switched off. No timeout. Running shell commands built from outside input, which is command injection in your own tool. Reading a ten gigabyte log into memory. Catching every exception and ignoring it, so failures are silent. Installing a package under a mistyped name, which attackers register on purpose. And no dry-run mode on a script that deletes or blocks things.

Avoid these
  • API keys in the source
  • verify=False
  • no timeout
  • shell=True with user input
  • reading a huge file into memory
  • bare except: pass
  • installing packages by a mistyped name
  • no dry run on destructive actions

Say it like this

In the interview: I use Python to automate what I would otherwise do by hand. Parsing logs with regular expressions and counters, hashing files, calling the APIs of security tools and clouds with requests, and small network checks with sockets. I keep secrets out of the code, use timeouts and least-privilege tokens, add a dry-run mode for anything destructive, and emit JSON with proper exit codes so the script fits into a pipeline. Then describe one script you actually wrote.

In the interview
  • "For automation: parsing logs
  • with re and Counter, hashing
  • with hashlib, calling tool and cloud APIs with requests, and small network checks with socket. I keep secrets out of code, use timeouts and least-privilege tokens, emit
  • JSON and exit codes so it
  • fits a pipeline."

Interview questions

Q1Which Python modules are most useful for security work?

re and collections for parsing and counting, hashlib for hashes, ipaddress for networks, requests for HTTP APIs, socket for raw connections, json and csv for data, subprocess for running tools, argparse and logging for usable scripts, plus cloud SDKs and scapy for specialised tasks.

Q2How do you process a very large log file in Python?

Iterate over the file object line by line (for line in f), which streams the file instead of loading it into memory, and keep only the aggregates you need, for example in a collections.Counter.

Q3How should a script handle API tokens and other secrets?

Read them from environment variables or a secret manager at run time, never hard-code them or commit them to git, use the least-privileged token that works, and avoid printing them in logs or error messages.

Q4Why always set a timeout on network calls?

Without a timeout a request can block indefinitely if the server stalls, hanging the script or pipeline. A timeout makes failure explicit so the script can retry, alert or exit with an error.

Q5Why is subprocess with shell=True dangerous?

The command string is interpreted by a shell, so any outside input included in it can inject additional commands. Passing the program and its arguments as a list avoids the shell and keeps input as data.

Q6How do you hash a large file without loading it into memory?

Open it in binary mode and feed fixed-size chunks to a hashlib object with update(), then call hexdigest(). This works for files of any size and is the standard way to compute SHA-256 fingerprints.

Q7How does a script signal a failure to a CI pipeline?

By exiting with a non-zero status code (sys.exit(1)). Pipelines treat a non-zero exit as a failed step, which is how a security check blocks a build; structured output such as JSON carries the details.

Q8What is the risk of installing Python packages carelessly?

Package code runs with your privileges. Typosquatted or compromised packages can steal credentials or tamper with results, so dependencies should be pinned, reviewed, installed from trusted indexes and scanned.