SECURITY ENGINEERING · PART 3 · SCRIPTING AND AUTOMATION · BASH · 37 OF 229

Bash for Security: Log Parsing and One-Liners

The shell skills a security engineer uses every day, shown on a practice auth log of 519 lines: counting failed logins with grep, ranking attacker addresses with sort and uniq (one address made 412 of 516 failures), pulling fields with awk, finding the brute force that succeeded, hunting files with find, checking hashes, and turning a one-liner into a safe script.

  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 / 12

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

Key takeaways

  • grep to filter
  • awk to pick fields
  • sort | uniq -c | sort -rn to rank
  • loops to join facts
  • strict, quoted scripts

Notes

grep

Start with grep, which keeps only the lines that match. Our practice log has five hundred and nineteen lines. Counting the lines that contain failed password gives five hundred and sixteen, and only two lines say accepted. In ten seconds you know the shape of the problem: this server was hammered with login attempts, and almost none worked. The flags worth memorising are minus c to count, minus i to ignore case and minus v to invert.

Filter the log
$ wc -l auth.log
519 auth.log
$ grep -c "Failed password" auth.log
516
$ grep "Accepted" auth.log | wc -l
2

-c count  -i ignore case
-v invert -E extended regex

Count and rank

The most useful pattern in all of log analysis is this pipeline. Extract one thing from each line, here the address, using grep with minus o to print only the match. Sort the results, count the duplicates with uniq minus c, and sort again by the count. The answer appears as a ranked list. One address made four hundred and twelve of the failed attempts, and a second made eighty seven. You will type sort, uniq, sort hundreds of times in your career.

Who is attacking?
$ grep "Failed password" auth.log \
  | grep -oE "([0-9]{1,3}\.){3}[0-9]+" \
  | sort | uniq -c | sort -rn | head
    412 203.0.113.9
     87 198.51.100.23
     14 192.0.2.77
      3 203.0.113.50

awk

When the value you want sits in a fixed column, use awk. It splits each line on spaces and lets you print fields by number. Here we print the user and the address from the two accepted logins. Both are the deploy account. One came from an internal address, which is expected. The other came from two zero three dot zero dot one one three dot nine. That is the same address at the top of the attacker list. Now this is an incident.

Which accounts were tried?
$ grep "Accepted" auth.log \
  | awk '{print $9, $11}'
deploy 10.0.0.9
deploy 203.0.113.9

# awk splits each line on spaces:
# $1 first field, $NF the last
# cut -d" " -f9 does one field

Join the facts

To confirm it, join the two facts with a small loop. For every address that logged in successfully, count how many failures came from that same address. The internal address has zero. The outside address has four hundred and twelve failures followed by a success: a brute-force attack that worked, against the deploy account. That one loop is a detection rule. In Part thirteen you will write the same logic in a monitoring system so it runs all day.

Did a brute force succeed?
for ip in $(grep Accepted auth.log \
    | awk '{print $11}' | sort -u); do
  n=$(grep "Failed password" auth.log \
      | grep -c "from $ip ")
  echo "$ip failed=$n"
done
10.0.0.9 failed=0
203.0.113.9 failed=412

What came next

With a suspect in hand, read what happened next. Searching for the account name shows that seconds after the successful login, the deploy user ran sudo and opened a root shell. The attacker now controls the server. Two grep options help here: minus n prints line numbers, and minus capital A and minus capital B print the lines after and before each match, which gives you the surrounding story instead of one isolated line.

Follow the account
$ grep -n "deploy" auth.log | tail -3
...Accepted password for deploy
   from 203.0.113.9 port 51022
...sudo: deploy : USER=root ;
   COMMAND=/bin/bash

# -n line numbers
# -A 5 / -B 5: lines after / before

More tools

A few more commands belong in your fingers. Find, to list files changed in the last day or files with the SUID bit. sha256sum, to fingerprint a suspicious file so you can look it up or prove it has not changed. ss, to see what is listening. last, for recent logins. journalctl with a time window. zgrep, to search rotated, compressed logs without unpacking them. And jq, because more and more logs are written as JSON.

The rest of the kit
find / -mtime -1 -type f   changed today
find / -perm -4000         SUID files
sha256sum file             fingerprint
ss -tlnp                   listening ports
last -a | head             recent logins
journalctl --since "1 hour ago"
zgrep pat /var/log/*.gz    old logs
jq .field file.json        JSON logs

From one-liner to script

When you run a one-liner twice, save it as a script. Three habits make it safe. Start with set minus e u o pipefail, so the script stops on errors and on unset variables instead of carrying on with garbage. Quote every variable, so a filename with a space cannot split into two arguments. And take inputs as parameters with defaults. This script prints every address with at least fifty failed logins, ready to feed an alert or a block list.

failed-logins.sh
#!/usr/bin/env bash
set -euo pipefail
log="${1:-/var/log/auth.log}"
min="${2:-50}"
grep "Failed password" "$log" \
 | grep -oE "([0-9]+\.){3}[0-9]+" \
 | sort | uniq -c \
 | awk -v m="$min" '$1>=m {print $2,$1}'

Care with evidence

One discipline separates an investigator from someone poking around. Do not change what you are investigating. Read logs; never open one in an editor and save it. Copy the logs off the machine and work on the copy. Keep a record of every command you ran and when. Hash the files you collect, so you can prove later they were not altered. And remember attackers edit local logs, which is why Part one insisted on shipping them elsewhere.

Working on a live system
  • read, do not edit: never open a log in an editor and save
  • copy logs off the box first; work on the copy
  • record the commands you ran and when (script, or history with timestamps)
  • hash files you collect
  • attackers edit logs: compare with the central copy

Common mistakes

Mistakes. Unquoted variables that break on spaces. Scripts without strict mode that keep running after an error. Relying on column numbers that shift when the log format changes slightly; check a few lines first. Forgetting the rotated, compressed logs, where the start of the attack usually is. Trusting only the local log. Running an untested one-liner as root. And redirecting output over the very file you were reading.

Avoid these
  • unquoted variables
  • no set -euo pipefail
  • parsing with fragile column numbers that shift
  • forgetting rotated .gz logs
  • trusting only the local log
  • running untested one-liners as root
  • rm or > on evidence

Say it like this

In the interview: working on a copy of the authentication log, I count the failures, rank the source addresses with sort and uniq, and then check whether any address with many failures also has an accepted login, which would mean the brute force worked. If it did, I follow that account: sudo use, new SSH keys, what ran next. Then I contain it by disabling the account and blocking the source, and move to key-only login.

In the interview
  • "On a copy of the auth log: count failures, rank source
  • IPs with sort | uniq -c, then check whether any IP with many
  • failures also has an Accepted
  • line. If so, follow that account: sudo use, new keys, what ran next. Then contain."

Interview questions

Q1How do you find the top source IPs of failed SSH logins in a log?

Filter the failures with grep, extract the addresses with grep -oE and an IP pattern (or awk on the right field), then rank them: sort | uniq -c | sort -rn | head. The output lists each address with its number of attempts, highest first.

Q2What does sort | uniq -c | sort -rn do?

The first sort groups identical lines together, uniq -c collapses each group and prefixes its count, and sort -rn orders the result numerically from highest to lowest. It is the standard way to turn a list of values into a frequency ranking.

Q3How would you check whether a brute-force attack succeeded?

List the source addresses of successful logins (Accepted lines) and, for each, count failed attempts from the same address. An address with many failures followed by a success indicates a successful brute force; then review what that account did afterwards.

Q4What does set -euo pipefail do in a Bash script?

It makes the script exit when a command fails (-e), treat unset variables as errors (-u), and fail a pipeline if any command in it fails (-o pipefail), instead of silently continuing with bad or empty data.

Q5Why should variables be quoted in Bash?

Unquoted variables undergo word splitting and filename expansion, so a value containing spaces or wildcard characters becomes several arguments or matches files. Quoting ("$var") keeps the value intact and avoids both bugs and injection problems.

Q6How do you search rotated, compressed log files?

With zgrep (or zcat piped to grep), which reads .gz files without unpacking them, for example zgrep "Failed password" /var/log/auth.log*. Older activity, often including the start of an attack, lives in the rotated files.

Q7How do you avoid damaging evidence when investigating a server?

Use read-only commands, copy logs and artefacts off the host and analyse the copies, record the commands run with timestamps, hash collected files, and compare local logs with the centrally stored copy since attackers may have altered local ones.

Q8When should you move from Bash to Python?

When the task needs real data structures, parsing of complex or nested formats, calls to web APIs, error handling or tests. Bash is ideal for quick filtering and gluing commands together; Python is better once logic grows beyond a few lines.