Lesson 09 · 30 minutes
Run another program and fingerprint your evidence
- Start another program with subprocess.run and read its output and exit code
- Stop a slow program with a timeout and handle its failure
- Record the SHA-256 of a log before you analyse it
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your lead says: "Before you analyse a log, take its fingerprint. In a month, anybody must be able to prove that the file is the one you read." The shell command sha256sum does this. You need your tool to call it, read its answer and stop with one clear line when it fails. A tool that calls another program is a common source of mistakes, so you also learn how to do it safely.
Recall
Lesson 7: what does "sha256sum hello.txt" print?
One line: the SHA-256 as 64 hexadecimal characters, two spaces, and the file name. Here a Python program runs sha256sum and takes the first word.
Lesson 5: what does an exit code tell another program, and where does the shell show it?
0 means success, any other number means failure. The shell keeps it in $?. Here your program reads the exit code of a program that it starts.
The idea
subprocess.run starts another program, waits for it and hands back what it did.
| Part | What it gives |
|---|---|
subprocess.run(words) | starts the program: the first word is the program, the others are its arguments |
.stdout, .stderr | what the program wrote, when you ask to capture it |
.returncode | its exit code |
timeout= | a limit in seconds: after it, Python stops the program and raises an error |
Pass a list of words, never one text with shell=True. A list starts no shell, so a file name stays a name.
- Your tool → subprocess.run: ["sha256sum", "auth.log"]
- subprocess.run → sha256sum: start, with a timeout
- sha256sum → subprocess.run: hash, and exit code 0
- subprocess.run → Your tool: .stdout and .returncode
Worked example
1. Run a program and read its exit code
Work in ~/krlab/python/loganalyse, the folder of lesson 8 (it holds auth.log; if it is missing, run python3 genlog.py auth.log).
cd ~/krlab/python/loganalysesubprocess.run(words) starts a program and waits for it. These are the options that you need:
capture_output=Truekeeps the output in.stdoutand.stderrinstead of printing it.text=Truemakes it text, not bytes..returncodeis the exit code of the program.timeout=1stops the program after 1 second and raisessubprocess.TimeoutExpired.
In the command below, python3 -c "..." runs a short program, strip() removes the line end, and try and except (lesson 5) catch the error of the timeout. The second subprocess.run starts a Python that sleeps for 5 seconds.
python3 -c "
import subprocess
done = subprocess.run(['sha256sum', 'nothing.log'], capture_output=True, text=True)
print(done.returncode, done.stderr.strip())
try:
subprocess.run(['python3', '-c', 'import time; time.sleep(5)'], timeout=1)
except subprocess.TimeoutExpired:
print('stopped after 1 second')"1 sha256sum: nothing.log: No such file or directory
stopped after 1 secondA failed program raises nothing: you read .returncode. With check=True, an exit code other than 0 raises subprocess.CalledProcessError.
2. See why a list is safer than a text
With shell=True and one text, such as f"sha256sum {path}", a shell reads the line, and a file named x; echo gotcha becomes two commands. The list form starts no shell, so a name stays a name. Both lines below receive the same name. Only the first one is safe.
python3 -c "
import subprocess
name = 'x; echo gotcha'
print(subprocess.run(['sha256sum', name], capture_output=True, text=True).stderr.strip())
print(subprocess.run(f'sha256sum {name}', shell=True, capture_output=True, text=True).stdout.strip())"sha256sum: 'x; echo gotcha': No such file or directory
gotchaThe first line is the list form: sha256sum looks for a file with that odd name and says there is none. The second is shell=True: the shell ran echo gotcha, a command that you never meant to run. In a real tool, the name would come from outside, and the second command could be anything.
3. Fingerprint the log and find the bursts
Create findbursts.py. It records the SHA-256 of the log before it reads it, as proof that the evidence did not change. hashlib could do it too (lesson 7); here sha256sum stands for any program that a tool must call. sys.exit("text") prints the text to standard error and exits with 1. line[:15] is the time at the start of the line, and burst comes from lesson 8.
findbursts.py
import subprocess
import sys
from datetime import timedelta
from burst import burst, parse_time
path = sys.argv[1]
try:
done = subprocess.run(["sha256sum", path], capture_output=True, text=True, timeout=10, check=True)
except subprocess.CalledProcessError as error:
sys.exit(f"sha256sum stopped with exit code {error.returncode}: {error.stderr.strip()}")
print("sha256", done.stdout.split()[0])
events = []
with open(path, encoding="utf-8", errors="replace") as handle:
for line in handle:
if "Failed password" in line:
events.append((parse_time(line[:15]), line.split(" from ")[1].split()[0]))
for address, start in burst(events, timedelta(minutes=5), 10).items():
print(f"{address:<15} 10 failures in 5 minutes from {start:%H:%M:%S}")python3 findbursts.py auth.log
python3 findbursts.py nothing.log
echo "exit code: $?"sha256 d75b5302c4c2c7af51410b4f2ac24f9d199790bda0955bfded11531625f06bc4
203.0.113.7 10 failures in 5 minutes from 08:00:02
192.0.2.77 10 failures in 5 minutes from 09:33:48
198.51.100.23 10 failures in 5 minutes from 08:01:45
sha256sum stopped with exit code 1: sha256sum: nothing.log: No such file or directory
exit code: 1192.0.2.77 has only 94 failures in two hours, under the whole-file limit of lesson 10. The window catches it (the drawing of lesson 8).
Your turn
Make the two logs of lesson 8 again if they are missing (python3 genlog.py server-a.log 4 and python3 genlog.py server-b.log 2). Write fingerprint.py in the same folder. It takes any number of log names. For each name it must:
- Run
sha256sumthroughsubprocess.run, with a list of words and a timeout of 10 seconds. - Print the first 8 characters of the SHA-256, two spaces and the name, for example
670658cf server-a.log. - On a failure of the program, stop at once with
sys.exitand one line that names the file and the exit code, and no traceback.
Run it on both logs, and then on server-a.log nothing.log server-b.log. Answer from your own output.
Check yourself
What does subprocess.run(["sha256sum", "nothing.log"]) do when the file is missing, and how do you notice?
It raises nothing. The program prints its message on its error stream and exits with 1, so .returncode is 1. With check=True, Python raises CalledProcessError instead.
A user gives your tool the file name "x; rm -rf ~". What does subprocess.run(["sha256sum", name]) do, and what would shell=True do?
The list form passes the name as one argument: sha256sum finds no such file and exits with 1. With shell=True, the shell splits the line at ; and runs rm -rf ~.
Why set a timeout, when sha256sum is fast?
The program may wait for a slow disk or a network share, or it may be a different program from the one you expect. Without a timeout, your tool waits for ever, and a scheduled job never ends.
Field notes
- In a scheduled job, give the full path (
/usr/bin/sha256sum), so that a changedPATHcannot swap the program. - Put
--before a file name from outside (["sha256sum", "--", path]), so that a name such as--helpis not read as an option. - Never pass a secret as an argument of another program: every user of the machine can read the arguments with
ps. Use an environment variable or standard input. - Take the fingerprint before you analyse and write it in the report, with the date and the command. Keep a copy of the evidence read-only, and work on a second copy.
- Call another program only when no standard-library function does the job. Here
hashlibcould do it, and it needs no other program on the machine.