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

Python essentials for security

Strings, lists, dictionaries, loops, functions and regular expressions, practised on a real-looking SSH log with exercises checked as you go.

In this lesson · about 45 minutes

  • Use strings, lists, dicts and loops to process log lines
  • Write a function that returns a result you can test
  • Use a regular expression to pull fields out of text

The pieces you will use most

line = "Failed password for root from 203.0.113.45 port 50122 ssh2"
"Failed" in line            # True: is this text inside?
parts = line.split()        # ['Failed', 'password', 'for', ...]
ip = parts[-4]              # '203.0.113.45' (4th from the end)

ips = ["203.0.113.45", "192.0.2.15", "203.0.113.45"]
len(set(ips))               # 2 distinct addresses

counts = {}
for ip in ips:
    counts[ip] = counts.get(ip, 0) + 1
# {'203.0.113.45': 2, '192.0.2.15': 1}

def is_private(ip):
    return ip.startswith(("10.", "192.168.")) or ip.startswith("172.")  # rough check

with open("auth.log") as f:   # read a file line by line
    for line in f:
        ...

Regular expressions

A regular expression (regex) describes a pattern of text. In security they pull IP addresses, user names, URLs and hashes out of messy logs, and they power detection rules (Module 18's YARA, many SIEM queries).

  • \d a digit, \w a letter, digit or underscore, \s a space, . any character
  • + one or more, * zero or more, {1,3} between one and three
  • ( ) captures part of the match
import re
m = re.search(r"for (?:invalid user )?(\S+) from (\d{1,3}(?:\.\d{1,3}){3})", line)
m.group(1), m.group(2)      # ('root', '203.0.113.45')

The r"..." prefix makes a "raw" string so backslashes are kept as typed.

Exercise

Count the failed logins

lines is a list of SSH log lines. Set failed to the number of lines that contain Failed password.

Code that runs before yours
auth = """Nov 20 09:00:01 web1 sshd[2201]: Failed password for root from 203.0.113.45 port 50122 ssh2
Nov 20 09:00:03 web1 sshd[2203]: Failed password for root from 203.0.113.45 port 50130 ssh2
Nov 20 09:00:05 web1 sshd[2205]: Failed password for admin from 203.0.113.45 port 50141 ssh2
Nov 20 09:01:12 web1 sshd[2290]: Accepted publickey for alice from 198.51.100.7 port 61040 ssh2
Nov 20 09:02:40 web1 sshd[2301]: Failed password for invalid user test from 192.0.2.15 port 40022 ssh2
Nov 20 09:02:44 web1 sshd[2303]: Failed password for invalid user oracle from 192.0.2.15 port 40031 ssh2
Nov 20 09:03:10 web1 sshd[2310]: Accepted password for bob from 198.51.100.20 port 52211 ssh2
Nov 20 09:04:00 web1 sshd[2320]: Failed password for root from 203.0.113.45 port 50201 ssh2
Nov 20 09:04:02 web1 sshd[2322]: Failed password for root from 203.0.113.45 port 50209 ssh2"""
lines = auth.splitlines()

Exercise

Failures per address

Write failures_by_ip(lines) that returns a dict mapping each source IP to its number of failed logins. The IP is the 4th word from the end of each line.

Code that runs before yours
auth = """Nov 20 09:00:01 web1 sshd[2201]: Failed password for root from 203.0.113.45 port 50122 ssh2
Nov 20 09:00:03 web1 sshd[2203]: Failed password for root from 203.0.113.45 port 50130 ssh2
Nov 20 09:00:05 web1 sshd[2205]: Failed password for admin from 203.0.113.45 port 50141 ssh2
Nov 20 09:01:12 web1 sshd[2290]: Accepted publickey for alice from 198.51.100.7 port 61040 ssh2
Nov 20 09:02:40 web1 sshd[2301]: Failed password for invalid user test from 192.0.2.15 port 40022 ssh2
Nov 20 09:02:44 web1 sshd[2303]: Failed password for invalid user oracle from 192.0.2.15 port 40031 ssh2
Nov 20 09:03:10 web1 sshd[2310]: Accepted password for bob from 198.51.100.20 port 52211 ssh2
Nov 20 09:04:00 web1 sshd[2320]: Failed password for root from 203.0.113.45 port 50201 ssh2
Nov 20 09:04:02 web1 sshd[2322]: Failed password for root from 203.0.113.45 port 50209 ssh2"""
lines = auth.splitlines()

Exercise

Extract user and IP with a regex

Write parse(line) that returns a tuple (user, ip) for a failed or accepted SSH login line, or None if the line does not match. Handle the invalid user form too.

Code that runs before yours
auth = """Nov 20 09:00:01 web1 sshd[2201]: Failed password for root from 203.0.113.45 port 50122 ssh2
Nov 20 09:00:03 web1 sshd[2203]: Failed password for root from 203.0.113.45 port 50130 ssh2
Nov 20 09:00:05 web1 sshd[2205]: Failed password for admin from 203.0.113.45 port 50141 ssh2
Nov 20 09:01:12 web1 sshd[2290]: Accepted publickey for alice from 198.51.100.7 port 61040 ssh2
Nov 20 09:02:40 web1 sshd[2301]: Failed password for invalid user test from 192.0.2.15 port 40022 ssh2
Nov 20 09:02:44 web1 sshd[2303]: Failed password for invalid user oracle from 192.0.2.15 port 40031 ssh2
Nov 20 09:03:10 web1 sshd[2310]: Accepted password for bob from 198.51.100.20 port 52211 ssh2
Nov 20 09:04:00 web1 sshd[2320]: Failed password for root from 203.0.113.45 port 50201 ssh2
Nov 20 09:04:02 web1 sshd[2322]: Failed password for root from 203.0.113.45 port 50209 ssh2"""
lines = auth.splitlines()
import re

Exercise

Flag brute-force sources

Using your counting idea, write suspects(lines, limit) that returns a sorted list of IPs with at least limit failed logins.

Code that runs before yours
auth = """Nov 20 09:00:01 web1 sshd[2201]: Failed password for root from 203.0.113.45 port 50122 ssh2
Nov 20 09:00:03 web1 sshd[2203]: Failed password for root from 203.0.113.45 port 50130 ssh2
Nov 20 09:00:05 web1 sshd[2205]: Failed password for admin from 203.0.113.45 port 50141 ssh2
Nov 20 09:01:12 web1 sshd[2290]: Accepted publickey for alice from 198.51.100.7 port 61040 ssh2
Nov 20 09:02:40 web1 sshd[2301]: Failed password for invalid user test from 192.0.2.15 port 40022 ssh2
Nov 20 09:02:44 web1 sshd[2303]: Failed password for invalid user oracle from 192.0.2.15 port 40031 ssh2
Nov 20 09:03:10 web1 sshd[2310]: Accepted password for bob from 198.51.100.20 port 52211 ssh2
Nov 20 09:04:00 web1 sshd[2320]: Failed password for root from 203.0.113.45 port 50201 ssh2
Nov 20 09:04:02 web1 sshd[2322]: Failed password for root from 203.0.113.45 port 50209 ssh2"""
lines = auth.splitlines()

Check your understanding0 of 3 correct

Question 1

1.What does len(set(ips)) give you?

Question 2

2.In a regex, what does \d{1,3} match?

Question 3

3.Why use counts.get(ip, 0) instead of counts[ip]?

Quiz score: 0 of 3

Exercises solved: 0 of 4

Tip: answer every quiz question correctly first.

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.