Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 80 ยท Practice and Review

Practice: Detection and Response

Six security operations exercises with solutions in Python: detect brute force, impossible travel and scans in logs, build an incident timeline, score CVSS and prioritize fixes.

Defenders spend much of their time reading evidence: logs from servers, sign-in events from identity systems, alerts from endpoint tools, and lists of vulnerabilities that never end. The skill is turning that pile into a short answer to three questions. What happened? How bad is it? What do we do first?

These six exercises train that skill on small synthetic data sets. You will detect a brute-force attack, spot an impossible trip, find a scanner and an injection attempt, merge evidence from three sources into one incident timeline, compute a CVSS score by hand-written code, and rank a list of findings. All hosts and addresses come from ranges reserved for documentation, and nothing here touches a real system.

flowchart LR
    L["Raw logs and events"] --> P["Parse and normalize"]
    P --> D["Detect (rules, thresholds)"]
    D --> T["Triage: how bad?"]
    T --> R["Respond and record a timeline"]
    R --> F["Fix root causes,<br/>prioritize vulnerabilities"]

Every exercise below is one box of this pipeline. Notice that parsing comes before detection: bad parsing makes every later step wrong.

Exercise 1: find the brute-force attack

Task. Below are web log lines: timestamp ip method path status user. Parse them with a regular expression. Flag every IP that has 5 or more failed logins (status 401) within any 60-second window, and report whether the same IP later logged in successfully for the same account, which is the signal that the attack worked. Also include one slow attacker (3 failures spread over 10 minutes) and one forgetful normal user, and decide what your rule does with them.

Hint. Keep a sorted list of failure times per IP and use two pointers for the window. See Spotting Attacks in Logs.

Python Solution 1: brute-force detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The slow attacker slips under the rule: 3 failures in 10 minutes never reach 5 in one minute. That is not a flaw to hide, it is a design fact. A fast-window rule catches noisy attacks; to catch the slow one you add a second rule over a longer window (for instance 10 failures per day per account, regardless of IP) or watch failures per account rather than per address, because real attackers spread guesses across many IPs.

Exercise 2: spot the impossible trip

Task. You have sign-in events with a city's latitude and longitude. For each user, compare consecutive sign-ins: compute the great-circle distance with the haversine formula and the speed needed to get from the first place to the second in the time between the events. Flag speeds above 900 km/h (faster than a plane) when the distance is more than 100 km.

Hint. a = sin^2(dlat/2) + cos(lat1) cos(lat2) sin^2(dlon/2), distance = 2 R asin(sqrt(a)) with R = 6371 km.

Python Solution 2: impossible travel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This rule has well-known false positives: VPNs and corporate proxies make a user "appear" in another country, and mobile networks are often geolocated badly. So an alert is a reason to ask the user or require another factor, not proof of a break-in. Good detection engineering records how often a rule fires wrongly and tunes it.

Exercise 3: find the scanner and the injection attempt

Task. In a small web access log, find (a) addresses that request many distinct paths and get mostly 404 responses (a scanner looking for hidden files), and (b) requests whose decoded URL contains typical attack patterns: ' or , union select, ../ and <script. Use pandas to load the log into a table and group it.

Hint. Decode with urllib.parse.unquote before matching, since attackers percent-encode payloads. Matching on the raw string misses them.

Python Solution 3: scanner and injection hunt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pattern matching like this is the idea behind simple web application firewalls and also its weakness: attackers vary the payload (different case, comments, double encoding) to dodge patterns. Treat matches as leads to investigate and as inputs to a score, not as a complete defense. The status code matters too: a 500 right after a UNION payload suggests the application mishandled it, which is the first thing to investigate.

Exercise 4: build the incident timeline

Task. During an incident you collect events from three sources that use different time zones: the web server (UTC), the authentication service (UTC+02:00) and the endpoint agent (UTC-05:00). Convert everything to UTC, sort it into one timeline, and compute the key response metrics: time from first malicious event to detection, and from detection to containment.

Hint. datetime.fromisoformat understands offsets like +02:00; call astimezone(timezone.utc). See Digital Forensics Basics for timelines and evidence handling.

Python Solution 4: merged incident timeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without the time-zone conversion, the endpoint events would look as if they happened the evening before the attack. Mixed time zones are a classic source of wrong conclusions in investigations. Record times in UTC and keep the original value too. The three metrics are what teams track to improve: shorter detection and containment times mean less damage.

Exercise 5: compute a CVSS base score

Task. The Common Vulnerability Scoring System (version 3.1) turns eight base metrics into a score from 0 to 10. Implement the base score and check it against four known vectors. The formulas, with the metric weights in the code, are:

  • ISS = 1 - (1-C)(1-I)(1-A)
  • Impact: 6.42 x ISS if the scope is unchanged, otherwise 7.52 x (ISS - 0.029) - 3.25 x (ISS - 0.02)^15
  • Exploitability: 8.22 x AV x AC x PR x UI
  • Base score: 0 if impact is 0 or less; otherwise roundup(min(Impact + Exploitability, 10)), and for a changed scope roundup(min(1.08 x (Impact + Exploitability), 10)).

Hint. "Roundup" means rounding up to one decimal place. Do it with integers to avoid floating-point surprises. See Vulnerability Management and Patching.

Python Solution 5: a CVSS v3.1 calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the first two vectors side by side to see what drives severity: a network-reachable bug that needs no login and no user action, with full impact, is a 9.8. The same system reached only through a victim's click, with limited impact, is a 6.1. CVSS measures how bad a flaw is in the abstract. It says nothing about whether your servers are exposed to it or whether attackers are using it today, which is the next exercise.

Exercise 6: decide what to patch first

Task. Given a list of findings with a CVSS score, whether the flaw is known to be exploited in the wild, whether the system faces the internet, and how critical the asset is (1 to 3), assign a priority and a deadline using these rules, then sort the list:

  • P0 (fix within 2 days): known to be exploited, on an internet-facing system.
  • P1 (7 days): known to be exploited, or CVSS 9.0 or higher, or CVSS 7.0 or higher on an internet-facing system.
  • P2 (30 days): CVSS 7.0 or higher.
  • P3 (90 days): CVSS 4.0 or higher.
  • P4 (next maintenance window): everything else.

Within a priority, put more critical assets first and then higher scores.

Hint. Write the rules as an ordered list of if statements; the first that matches wins.

Python Solution 6: risk-based patch priority

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the 9.8 on an internet-facing server that nobody is exploiting yet lands in P1, behind the 7.5 that attackers are already using (P0). A pure score sort would reverse them. Mature programs use signals such as the CISA Known Exploited Vulnerabilities list and exploit-prediction scores for exactly this reason: exploitation and exposure matter more than the raw score.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A rule flags 5 failed logins per IP within 60 seconds. Which attack is it most likely to miss?

    A short-window, per-IP threshold catches noisy attacks. Slow or distributed attacks need longer windows and per-account counting.
  2. 2. Why convert every timestamp to UTC when building an incident timeline?

    Mixed offsets can make events appear in the wrong order and hide the real sequence of the attack.
  3. 3. Why must a web log hunt decode URLs before matching attack patterns?

    A payload such as %27%20OR%20%271 does not contain the text ' OR ' until it is decoded, which is how the server will interpret it.
  4. 4. What does a CVSS base score NOT tell you?

    The base score describes the flaw itself. Exploitation in the wild and your own exposure are separate inputs to prioritization.
  5. 5. An impossible-travel alert fires for an employee who uses a corporate VPN. What is the best reading?

    Location signals are noisy. Verify with the user or ask for another factor, and tune the rule to account for known VPN ranges.

Summary

  • Parse before you detect, and state each rule's blind spots: a short-window brute-force rule misses slow attackers, so add longer windows and per-account counts.
  • Impossible-travel checks compare distance and time between sign-ins; treat alerts as prompts to verify, because VPNs cause false positives.
  • Decode URLs before pattern matching, and look at status codes to see how the application reacted.
  • Normalize every event to UTC, sort across sources, and compute time to detect and time to contain.
  • CVSS scores a flaw in the abstract; priority comes from exploitation in the wild, exposure and asset importance.

Next: Cybersecurity Interview Questions, a set of common concept questions with model answers across the whole course.