Something Is Wrong With This Machine
It is Monday morning. You help run the computer lab, and over the weekend the lab server (a Linux machine called lab-07) was slow enough that people noticed. Nothing is obviously broken. Nothing popped up a warning. Somebody just says "it felt weird."
That is what a real security incident usually looks like at the start: not an alarm, just a question. Was that ordinary slowness, or was somebody trying to get in?
The good news is that the machine has been taking notes the whole time. Two sources answer almost every early question:
- A log file is a plain text file the system writes to as things happen. Every login attempt, every service that starts, every error gets one line, in time order. Logs tell you what happened.
- A process is a program that is running right now. The machine can list every one of them, who owns it, and how much of the CPU it is eating. Processes tell you what is happening.
This tutorial is about pulling answers out of both, using nothing but a shell.
Why the investigation happens in a terminal
A shell is the program that reads commands you type and asks the operating system to carry them out. On Linux the usual shell is called bash, and the window you type into is called a terminal. Security work lives there for four practical reasons.
- Servers usually have no desktop. The machine holding a school's grade database is a box in a rack with no monitor attached. You reach it over the network with a program called SSH, and what you get is a shell. There is no window to click in.
- Logs are enormous. A week of authentication logs on a busy server is millions of lines. Scrolling is not a strategy. A command that filters and counts them finishes in under a second.
- Commands are exact and repeatable. "Click the third item in the menu" changes when software updates. grep "Failed password" auth.log means the same thing on every Linux machine, this year and in ten years.
- Your work becomes evidence. The shell keeps a history of every command you ran. Being able to show exactly what you did, in order, is the difference between a finding somebody can act on and a hunch.
Everything on this page belongs on a system you own or have been explicitly given permission to administer: your own laptop, a virtual machine you set up, a school lab account, or a practice environment built for it. Reading logs on somebody else's server without authorization is not a gray area, and "I was only looking" is not a defense. The skills are identical either way. The permission is what makes it a career.
What You Need to Know First
This page assumes you can already move around a Linux machine from a terminal and open a file. If you can run pwd, ls, and cd without looking them up, you are ready. Everything after this section is new material.
If any of that is unfamiliar, go pick it up first and then come back. It takes about twenty minutes:
- Terminal Basics covers the prompt, where you are, and how to move: pwd, ls, cd, mkdir, and touch.
- Files and Folders covers reading and moving files: cat, cp, mv, and rm.
The assumed commands, in one table
Four path shortcuts this page leans on
A path is the written route to a file. One that starts with / is absolute and means the same thing from anywhere. One that does not is relative and starts from wherever you are standing.
Linux treats Auth.log and auth.log as two completely different files, and it treats LS as a command that does not exist. Spaces matter too: cd.. is an error while cd .. works. Investigations go sideways when somebody greps for failed and the log actually says Failed, so watch your capitalization all the way through this page.
Where the Logs Live and How to Read Them
On Linux, system logs are collected in one directory: /var/log. Knowing that one path is most of the battle, because it is the first place any responder opens.
/var/log/
├── auth.log logins, sudo use, SSH attempts <- start here
├── syslog general system messages
├── boot.log what happened at startup
├── kern.log messages from the kernel itself
├── dpkg.log software installed or removed
└── nginx/
├── access.log every web request served
└── error.log every web request that failed
Names vary a little between Linux distributions. On some systems the authentication log is called secure instead of auth.log, and web server logs might sit under /var/log/apache2. The idea does not change: one directory, one file per subject, plain text.
Reading a single log line
Log formats differ, but nearly all of them put the same information in the same order. Here is one line from auth.log:
Four ways to open a log, and when to use each
You already know cat, which dumps a whole file to the screen. On a log file that is usually the wrong choice, because a log can be hundreds of thousands of lines long and all of it will scroll past faster than you can read. Pick the right tool instead:
15 auth.log
$ tail -n 3 auth.log # what happened most recently?
Mar 04 21:09:44 lab-07 sshd[2067]: Failed password for invalid user admin from 192.0.2.77 port 50170 ssh2
Mar 04 21:11:03 lab-07 sshd[2070]: Failed password for student from 192.0.2.153 port 41240 ssh2
Mar 04 21:14:20 lab-07 sshd[2073]: Accepted password for student from 192.0.2.41 port 49125 ssh2
wc is short for word count, and -l asks it for a line count instead. Running it first is a habit worth building: it tells you whether you are looking at fifteen lines or fifteen million, which decides everything you do next.
tail -f: watching a log as it is written
Add -f (for follow) and tail does not exit. It prints the end of the file and then sits there, printing each new line the moment the system writes it.
That turns a log file into a live feed. If you are trying to reproduce a problem, or you want to see whether the login attempts are still coming in right now, you start this in one window and work in another. Press Ctrl+C to stop following.
If you cat a photo, a program, or a several-gigabyte archived log, you get a screenful of garbage characters, a terminal that looks frozen, and sometimes a garbled prompt afterward. Use less or head on anything unfamiliar. If a command does run away from you, Ctrl+C stops it.
A server started misbehaving about ten minutes ago and its log file has 400,000 lines. Which command shows you the newest events first?
Logs are written oldest line first, so the most recent events are at the end of the file and tail is what shows them. head would show you events from whenever this log file started, possibly weeks ago. cat would dump all 400,000 lines past you. wc -l only tells you how many lines there are, which is a useful first move but not an answer.
Searching Logs with grep
Reading a log top to bottom does not scale. What you actually do is ask the log a question, and the command that asks questions is grep. Give it a pattern and a file, and it prints every line of that file containing the pattern.
Mar 04 21:03:11 lab-07 sshd[2041]: Failed password for invalid user admin from 192.0.2.77 port 50122 ssh2
Mar 04 21:03:19 lab-07 sshd[2043]: Failed password for invalid user admin from 192.0.2.77 port 50126 ssh2
Mar 04 21:04:02 lab-07 sshd[2050]: Failed password for student from 192.0.2.153 port 41220 ssh2
Quote your pattern any time it contains a space, otherwise the shell splits it into two separate arguments and grep reads the second one as a filename. Quoting always works, so quoting always is a fine habit.
The flags that do the real work
Counting: the fastest way to size up a problem
The first real question in this incident is not "what does the log say," it is "how bad is it." Counting answers that.
11
$ grep -c "Accepted password" auth.log # how many succeeded?
3
$ grep -c "192.0.2.77" auth.log # how many from one address?
8
Eleven failures and three successes in a file this small is already lopsided. Eight of those failures came from a single address. You have not proven anything yet, but you now have a specific thing to look at, which is the entire point of the first ten minutes of an investigation.
Using -v to clear the noise
Logs are mostly boring on purpose. A machine that talks to itself every minute fills its log with routine lines, and those lines hide the interesting ones. -v throws them away.
That prints the system log with every scheduled-job line removed. Stack the idea up and you can subtract several kinds of noise in a row, which you will see in the next section.
By default the pattern is literal characters, not a wildcard. If you need a real pattern (any IP address, any four digit number), add -E for extended regular expressions. Then grep -E "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" auth.log matches any address-shaped text. Adding -o as well prints just the part that matched instead of the whole line, which turns out to be the key to the next section.
You want to know how many times the address 192.0.2.77 appears anywhere in auth.log. Which command answers that in one step?
-c counts matching lines and prints only the number. -n would print every match with its line number, which works but makes you count by eye. -v does the opposite of what you asked and shows every line without that address. find searches for files by name, not for text inside them.
Ranking What You Found with Pipes
Counting one address at a time works when you already suspect one address. Real logs have hundreds. You need the machine to count all of them and hand you a ranked list, and that is what pipes are for.
Every Linux command reads from an input stream and writes to an output stream. By default the input is your keyboard and the output is your screen. The vertical bar |, called a pipe, changes that: it takes whatever the command on the left printed and feeds it straight into the command on the right.
Read it left to right. grep pulls out every failed-login line. Instead of printing them, the pipe hands them to wc -l, which counts lines. What lands on your screen is a single number. You just built a counting tool out of two commands that know nothing about each other.
Everything here is aimed at log analysis. For the general treatment of streams, filters, and chaining commands in any context, work through Pipes and Filters, then come back.
The four filters that rank a log
Building the pipeline one stage at a time
Nobody types a five-stage pipeline from memory in one go. You add a stage, look at the output, and add the next one. Watch it grow:
Mar 04 21:03:11 lab-07 sshd[2041]: Failed password ... from 192.0.2.77 port 50122 ssh2
Mar 04 21:03:19 lab-07 sshd[2043]: Failed password ... from 192.0.2.77 port 50126 ssh2
...11 lines of this...
$ grep "Failed password" auth.log | grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"
192.0.2.77
192.0.2.77
192.0.2.153
...just the addresses now...
$ ... | sort | uniq -c
3 192.0.2.153
8 192.0.2.77
$ ... | sort | uniq -c | sort -nr
8 192.0.2.77
3 192.0.2.153
The finished command is the one every incident responder has typed a thousand times:
Five tiny tools, each doing exactly one job on the output of the last, and together they answer a question none of them could answer alone: which address failed to log in the most, and how many times. The same line works identically whether the log has fifteen entries or fifteen million, which is why it is worth understanding rather than memorizing.
uniq only looks at the line directly above the current one. Give it an unsorted list and the same address scattered in five places counts as five separate groups of one. Sorting first guarantees that every copy of a value is adjacent, so uniq -c can total it in a single pass. That pass is also why this scales: the pipeline never has to hold the whole file in memory at once.
The same shape answers plenty of other questions. Swap the grep and you can rank which usernames were guessed most often, which pages a web server returned a 404 for, or which hour of the night the attempts clustered in.
Finding Files and Saving Evidence
Logs tell you about events. The other half of an investigation is files: what got left behind, and where. grep searches inside files. find searches for files, by name, type, location, and time.
./logs/auth.log
./logs/web.log
$ find /tmp -type f # only files, not directories
$ find /home -name "backup.sh" # where did that script go?
/home/student/scripts/backup.sh
The shape is find where-to-look what-to-look-for, and find always searches downward from the directory you point it at. Two tests do most of the work: -name matches the filename (wildcards allowed, so quote the pattern) and -type f or -type d limits results to files or directories.
Searching by time: what changed recently?
This is the question that turns find into an investigation tool. If something was tampered with on Saturday night, its modification time says so.
That asks: which configuration files on this machine changed in the last day? On a server nobody touched over the weekend, the correct answer is usually "none," and anything that comes back deserves an explanation.
The hidden file trick
Any file whose name begins with a dot is hidden from a plain ls. That is a convenience feature, not a security feature, but it fools a casual glance, so a leading dot is one of the oldest hiding places there is. Investigators run ls -la by reflex.
$ ls -la /tmp
total 36
drwxr-xr-x 2 student student 4096 Mar 04 22:10 .
drwxr-xr-x 2 student student 4096 Mar 04 22:10 ..
-rwxr-xr-x 1 student student 201 Mar 04 21:58 .update-helper
The first command printed nothing at all, which looks like an empty directory. The second one found an executable file with a leading dot, sitting in /tmp. That location matters: /tmp is scratch space that any account on the machine is allowed to write to, which is exactly why unwanted things get dropped there. Note the timestamp too, because it lands in the middle of the login attempts you already counted.
Saving what you found
A finding you cannot show somebody is not worth much. Redirection sends a command's output into a file instead of onto your screen.
$ grep "Failed password" auth.log > evidence/failures.txt
$ echo "Top source: 192.0.2.77, 8 failed attempts" >> evidence/summary.txt
$ ls -la /tmp >> evidence/summary.txt
$ cat evidence/summary.txt # always check what you saved
Notice the last line. Redirection prints nothing when it works, which is the Linux house style: no news is good news. That silence makes it easy to believe you saved something when you saved nothing, so read the file back.
> empties the target file first, without warning you and with no way to get the old contents back. If you have been appending findings all afternoon and you type one > instead of two, your notes are gone. When you are building up a file, use >>.
You have been adding findings to evidence/summary.txt all afternoon. Which command adds one more line without destroying the rest?
Double >> appends. A single > would wipe the file and leave only the new line, with no way to recover the rest. A pipe cannot be used here because summary.txt is a file, not a command, and pipes only feed one command into another.
What Is Running That Should Not Be
Files and logs are the past. A process is the present: a program that is executing right now. Every process has a number called a PID (process ID), an owner, and a share of the machine's memory and CPU time.
This is where the two halves of the investigation meet. A strange file sitting on disk is suspicious. A strange file sitting on disk and currently running as a process is an emergency.
ps: a snapshot of everything running
ps stands for process status. On its own it shows only your own processes in your own terminal, which is rarely what you want. The form you will actually type is ps aux, which shows every process on the machine, for every user.
USER PID %CPU %MEM COMMAND
root 1 0.0 0.1 /sbin/init
root 412 0.0 0.4 /usr/sbin/sshd
student 1902 0.1 1.2 bash
student 2318 96.4 0.3 /tmp/.update-helper
Three things about that last line should bother you, and you have already met all three. It is eating 96 percent of a CPU. It is running out of /tmp. Its name starts with a dot, so a plain ls would not have shown the file. It is the same path you turned up with ls -la /tmp in the last section, which means the file is not just sitting there, it is running.
That is your answer to the slow weekend, and it lines up in time with the login attempts you counted. Three independent pieces of evidence pointing at the same window is what a finding looks like.
Piping ps, and the live view
Everything you learned about pipes works here too, because ps just prints text:
That asks "is the SSH service running, and under what PID," without reading a hundred lines by eye. For a moving picture instead of a snapshot, top prints a table that refreshes every couple of seconds with the heaviest process at the top. It answers "why is this server suddenly slow" in about four seconds. Press q to quit it, the same key that leaves less and man.
kill: stopping a process
Once you have a PID, kill 2318 asks that process to shut down cleanly. The name sounds dramatic, but a plain kill is a polite request, and well-behaved programs use it to save their work first.
If the process ignores you, kill -9 2318 tells the operating system to terminate it outright with no chance to clean up. Try the polite version first, because -9 can leave half-written files behind. To stop something running in your own terminal, press Ctrl+C.
Two reasons. First, plenty of processes with strange names are load-bearing parts of the operating system, and killing the wrong one can log you out, drop the network, or take down a service other people depend on. Look the name up first. Second, a running process holds evidence that exists only in memory, and killing it destroys that evidence permanently. On a real incident, the decision to stop a process belongs to whoever is running the response. Your job is to document it: the PID, the full path, the owner, and the time you saw it.
Investigate It Yourself
You now have every technique this investigation needs: read the log, search it, count, rank, save what you find, and check what is running. Below is a working shell attached to a small pretend Linux machine that lives entirely in your browser. It has the weekend's auth.log on it. Nothing you type here touches your real computer, so break whatever you want.
Click anywhere in the terminal to start typing. Press Enter to run a command, and use the Up and Down arrow keys to walk back through what you have already run. Type help for the full list of what is supported.
Try one of these, then press Enter:
Guided challenge
The file logs/auth.log records every login attempt on this machine over the weekend. Which IP address failed to log in the most times, and how many times did it fail?
A path that works: start with wc -l logs/auth.log to see how big it is, then tail -n 5 logs/auth.log to see the most recent events. Narrow it with grep "Failed password" logs/auth.log, and count with grep -c "Failed password" logs/auth.log. Then let the machine rank the addresses for you: grep "Failed password" logs/auth.log | grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | sort | uniq -c | sort -nr. When you have the answer, save it with >> findings.txt.
192.0.2.77, with 8 failed attempts. The next closest is 192.0.2.153 with 3, and 192.0.2.41 never failed at all, because it is the account owner logging in normally.
Look at the pattern, not just the number. The attempts from 192.0.2.77 come a few seconds apart and cycle through usernames like admin, root, test, guest, and oracle. That is an automated tool guessing at common accounts, not a person who forgot a password. The three failures from 192.0.2.153 are all for one real username, spread over several minutes, which looks much more like somebody mistyping.
Then keep pulling the thread. Run ls -la /tmp and ps aux and check the timestamps against the log. The hidden file in /tmp was written at 21:58, in the same window as the login attempts, and it is running right now at 96 percent CPU. That is the report you would hand to whoever runs the response: what you found, where, when, and the exact commands you ran to find it.
This playground is a simulation, so it only knows the commands listed in help, and the file in /tmp is a harmless placeholder that does nothing. A real shell has thousands of commands.
Run cd nowhere and read the error. Run cat logs on a directory. Run grep failed logs/auth.log with a lowercase f and watch it find nothing, then add -i and watch it find everything. Error messages are how the shell talks to you, and getting comfortable reading them is most of what separates someone who is stuck from someone who is not.
Your Investigation Playbook
Put the whole page in order and it is a short, repeatable routine. When somebody hands you a machine and says "this feels wrong," this is the sequence:
- Size it up. wc -l /var/log/auth.log. Know whether you are reading fifteen lines or fifteen million before you do anything else.
- Look at the most recent events. tail -n 50 /var/log/auth.log, and tail -f if it is still happening.
- Ask a specific question. grep -c "Failed password" /var/log/auth.log. Counts turn a feeling into a number.
- Rank the answers. Pipe into sort | uniq -c | sort -nr and let the machine tell you which value dominates.
- Look for what got left behind. ls -la /tmp and find /etc -mtime -1, and check every timestamp against the log.
- Check what is running now. ps aux, and compare any strange path against what you found on disk.
- Write it down. Redirect the output that supports each finding into a file with >>, and keep the exact commands you ran. That file is the handoff.
Looking things up without leaving the terminal
Nobody memorizes every flag. What professionals memorize is how to look one up in ten seconds. man grep opens the full manual page for grep: scroll with the arrow keys, search with /, quit with q. For a quick reminder of one flag, grep --help prints a short summary straight into your terminal.
Manual pages have a standard shape, and the SYNOPSIS line near the top has its own grammar: square brackets mean optional, and three dots mean "you can repeat this."
That line says: type grep, then as many options as you like, then exactly one pattern, then as many filenames as you like. Once you can read a synopsis, you can teach yourself any command on the system.
A pocket reference
Where this leads
Log investigation is the entry point to defensive security work, and two skills sit right next to it. Linux File Permissions explains who was allowed to write that file in /tmp in the first place, and why the permission bits on a log file decide whether an attacker can edit their own tracks out of it. Network Commands for Security picks up the other end of the question: which machines are actually connected to this one right now, and what is that address you just found.
The fastest way to get good at this is unglamorous. Keep a terminal open, and every time you wonder something about a machine you administer, answer it by typing instead of clicking. Within a couple of weeks these commands stop being something you look up and start being something you think in.