TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › find, grep and awk Pipelines on Logs

find, grep and awk Pipelines on Logs

When an alert fires on a Linux server, the first questions are almost always answered with a pipeline: which addresses failed to log in, which accounts they tried, which files changed since yesterday, whether the binaries still match their checksums. grep, awk, sort, uniq, find and sha256sum are installed on every Linux system, including the rescue image you boot an infected machine from, so these pipelines work when nothing else does. This lesson builds the classic ones on a synthetic log and a small file tree, inside your sandbox. The tools themselves are introduced in Linux & Bash; Linux Services and Logs explains where the logs come from.

Definitions

  • grep -E: extended regular expressions; -c counts, -v inverts, -o prints only the match, -h drops file names, -F matches a fixed string (no regex).
  • awk: splits each line into fields $1 … $NF and runs a small program on them; awk '/pattern/ { print $11 }'.
  • sort | uniq -c | sort -rn: the "top N" idiom: group equal lines, count them, biggest first.
  • find: walk a tree with tests: -type f, -newer ref, -mtime -1, -perm -4000 (SUID), -user, and actions -print0, -exec … {} +.
  • sha256sum -c manifest: re-hash every file in a manifest and say OK or FAILED.

Who failed to log in?

The log is a synthetic auth.log from a lab server, created by the session. Its sshd lines have two shapes: Failed password for alice from … and Failed password for invalid user admin from …. The field number of the address differs between them, which is the classic trap for awk '{print $11}'.

bash · try it yourself
set -euo pipefail
cat > auth.log <<'LOG'
Jan 15 10:00:01 web1 sshd[811]: Accepted publickey for alice from 10.10.0.5 port 50110 ssh2
Jan 15 10:00:07 web1 sshd[812]: Failed password for root from 203.0.113.7 port 40022 ssh2
Jan 15 10:00:09 web1 sshd[813]: Failed password for invalid user admin from 203.0.113.7 port 40024 ssh2
Jan 15 10:00:11 web1 sshd[814]: Failed password for invalid user oracle from 203.0.113.7 port 40026 ssh2
Jan 15 10:00:15 web1 sshd[815]: Failed password for bob from 10.10.0.22 port 51000 ssh2
Jan 15 10:00:20 web1 sshd[816]: Accepted password for bob from 10.10.0.22 port 51002 ssh2
Jan 15 10:01:02 web1 sshd[817]: Failed password for invalid user test from 198.51.100.9 port 33000 ssh2
Jan 15 10:01:03 web1 sshd[818]: Failed password for root from 203.0.113.7 port 40030 ssh2
Jan 15 10:02:00 web1 CRON[900]: pam_unix(cron:session): session opened for user root
Jan 15 10:03:30 web1 sudo[950]:      bob : TTY=pts/0 ; PWD=/home/bob ; USER=root ; COMMAND=/usr/bin/id
LOG
echo "== failures: $(grep -c 'Failed password' auth.log)"
echo "== naive \$11 (wrong for invalid users)"
grep 'Failed password' auth.log | awk '{print $11}' | sort | uniq -c | sort -rn
echo "== address = the field after 'from'"
grep 'Failed password' auth.log \
  | awk '{for (i = 1; i < NF; i++) if ($i == "from") print $(i + 1)}' \
  | sort | uniq -c | sort -rn
echo "== accounts tried per source"
grep -E 'Failed password for (invalid user )?' auth.log \
  | sed -E 's/.*for (invalid user )?([^ ]+) from ([^ ]+).*/\3 \2/' \
  | sort -u | awk '{n[$1]++; u[$1] = u[$1] " " $2} END {for (s in n) print n[s], s, u[s]}' | sort -rn
echo "== invalid user names (account enumeration)"
grep -oE 'invalid user [^ ]+' auth.log | cut -d' ' -f3 | sort | uniq -c
echo "== sudo commands"
grep -F 'sudo[' auth.log | awk -F'COMMAND=' '{print $2}'
== failures: 6
== naive $11 (wrong for invalid users)
      2 203.0.113.7
      1 test
      1 oracle
      1 admin
      1 10.10.0.22
== address = the field after 'from'
      4 203.0.113.7
      1 198.51.100.9
      1 10.10.0.22
== accounts tried per source
3 203.0.113.7  admin oracle root
1 198.51.100.9  test
1 10.10.0.22  bob
== invalid user names (account enumeration)
      1 admin
      1 oracle
      1 test
== sudo commands
/usr/bin/id

The naive $11 column mixes addresses with the account names of invalid-user lines (admin, oracle, test), so the "top talker" table is wrong. Finding the address by its position after the word from works for both shapes. The per-source summary shows the picture an analyst needs: 203.0.113.7 failed four times on three accounts, root and two that do not exist (admin, oracle), which is either brute force or the start of spraying (Brute Force and Password Spraying).

What changed on disk?

The second session builds a small "web root", records a SHA-256 manifest as a baseline, then simulates an intruder: one file is modified (with its old timestamp put back, as attackers often do with touch -r), and a new file appears. Timestamps are fixed with touch -d, so the session is reproducible.

bash · try it yourself
set -euo pipefail
mkdir -p www/js && cd www
printf '<h1>lab</h1>\n' > index.html
printf 'console.log("app")\n' > js/app.js
printf 'User-agent: *\n' > robots.txt
touch -d '2026-01-10 09:00:00' index.html js/app.js robots.txt
find . -type f -print0 | sort -z | xargs -0 sha256sum > ../baseline.sha256
touch -d '2026-01-14 00:00:00' ../since

# --- simulated intrusion (inside this sandbox only) ---
printf '<h1>lab</h1>\n<script src="//cdn.lab.test/x.js"></script>\n' > index.html
touch -d '2026-01-10 09:00:00' index.html          # timestamp put back
printf '<?php /* lab marker file */ ?>\n' > js/.cache.php
touch -d '2026-01-15 10:04:00' js/.cache.php

echo "== files newer than 2026-01-14 (timestamps can lie)"
find . -type f -newer ../since -print
echo "== checksum verification against the baseline"
sha256sum -c --quiet ../baseline.sha256 || echo "sha256sum exit: $?"
echo "== files not in the baseline"
comm -13 <(cut -c67- ../baseline.sha256 | sort) <(find . -type f | sort)
echo "== hidden files and server-side scripts in a static site"
find . -type f \( -name '.*' -o -name '*.php' \) -print
== files newer than 2026-01-14 (timestamps can lie)
./js/.cache.php
== checksum verification against the baseline
./index.html: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
sha256sum exit: 1
== files not in the baseline
./js/.cache.php
== hidden files and server-side scripts in a static site
./js/.cache.php

The -newer search finds only the new file, because the modified index.html had its timestamp restored. The checksum comparison is not fooled: index.html FAILED. comm lists the file that is not in the baseline at all. Timestamps are evidence, but they are evidence the attacker can edit; content hashes against a baseline stored elsewhere are much harder to fake. This is the idea behind the file-integrity monitor project.

How pipelines go wrong (detection)

  • Field positions change with the message shape, as $11 showed. Check a pipeline on every line shape in the log (awk '{print NF}' | sort | uniq -c shows how many shapes there are).
  • Silent empty results: a typo in a pattern gives no output and exit status 1. Under set -e a grep with no match stops the script; use grep … || true where "no match" is a valid answer.
  • Rotated and compressed logs: auth.log.1, auth.log.2.gz. Use zgrep or zcat -f auth.log* | grep … so the evidence from last week is not missed.
  • Locale and sort order: sort depends on LC_ALL; set LC_ALL=C in scripts for byte order and speed.

How to make them reliable (prevention)

  1. Anchor on keywords, not columns: "the field after from", or a sed -E with named parts.
  2. Store baselines off the host (or at least read-only and signed); a manifest on the same disk can be rewritten by the intruder.
  3. Use -print0 and xargs -0 for file names, as in Safe Bash.
  4. Keep the evidence: copy logs before analysing them, and record the commands you ran (script or a shell history file) for the incident report.
  5. Move to a real parser when a pipeline grows past a few stages: a Python script with tests, or the SIEM.

Pitfalls

  • uniq only merges adjacent lines: always sort first.
  • grep "$var" treats the variable as a regex; an address like 10.10.0.5 also matches 10.10.0.50 and 10a10b0c5. Use grep -wF -- "$var".
  • find / … on a live system crosses into /proc and network mounts; add -xdev and limit the starting points.
  • Clock skew: logs from several hosts are only comparable if their clocks were synchronised (NTP) and their time zones are known.

Practice

1. Print the number of failed logins per minute, using the timestamp field.

grep 'Failed password' auth.log | awk '{print $1, $2, substr($3, 1, 5)}' | uniq -c gives 4 Jan 15 10:00 and 2 Jan 15 10:01 for the sample log (uniq -c works here because the log is already in time order).

2. Find SUID-root files under /usr that are not in a known list suid.allow.

find /usr -xdev -type f -perm -4000 -user root -print | sort > suid.now; comm -13 <(sort suid.allow) suid.now. New SUID binaries are a classic persistence and privilege-escalation sign (Linux Permissions).

3. Why is sha256sum -c on a manifest stored next to the files weak evidence after a root compromise?

Root can rewrite both the file and the manifest line. The manifest must be stored where the intruder could not reach (another host, read-only media) or be signed with a key that never lived on the server.

Test yourself

Why did awk '{print $11}' give a wrong top-talker list?

  1. awk counts from 0
  2. Lines for invalid users have two extra words, so the address is in a different field
  3. sort was missing
  4. The log was compressed

find . -newer ../since missed the modified index.html. Why?

  1. find ignores HTML files
  2. The intruder restored its old timestamp, and find compares timestamps, not content
  3. The file was hidden
  4. find needs root

Which command adds lines from compressed rotated logs to a search?

  1. grep -r
  2. zgrep (or zcat -f auth.log* | grep)
  3. uniq -c
  4. find -newer

What must come before uniq -c in a counting pipeline?

  1. sort
  2. awk
  3. cut
  4. nothing