Skip to content

Introduction to the Open-Source Operating System

This article provides an introductory overview of Linux, an open-source operating system renowned for its stability and security. Covering basic concepts and commands, it offers a foundational understanding for cybersecurity professionals leveraging Linux-based tools in their security operations. Whether delving into penetration testing, digital forensics, or network security, Linux serves as a fundamental platform for cybersecurity endeavors.

/ ARTICLE
[ FIG. 1 ]
A Complete Roadmap to Linux OS

Introduction to the Open-Source Operating System: Linux

Every machine on the TOP500 supercomputer list runs Linux. So does most of the public cloud, the majority of web-facing servers, every Android handset, and the router in the corner of your office that nobody has logged into since it was installed. For most people that is invisible plumbing. For anyone doing security work it is the actual job: the thing you attack, the thing you defend, and the thing your tooling runs on.

The reason Linux ended up at the centre of security work is not that it is inherently safe — it isn’t, and a default install exposed to the internet will be found and probed within the hour. It is that you can read it. The kernel source is public, you can compile a build with the modules you need and nothing else, and you can verify what a binary does rather than take a vendor’s word for it. That auditability is the whole argument, and it comes with a bill: nobody is accountable to you for what you compile, and “the community will patch it” is a hope, not a support contract.

Linux is a kernel, not an operating system. What you install is that kernel plus a userland — GNU utilities, an init system, a package manager, a libc — assembled by a distribution. Knowing where that seam sits saves you a lot of confusion later, because most of what people call “a Linux problem” is a distribution decision.

Almost every security control on the box lives at the boundary between user space and kernel space. A process asks the kernel to do something via a system call; the kernel decides whether to allow it. Mandatory access control frameworks such as SELinux and AppArmor sit exactly on that path, which is why they can stop a compromised web server from reading /etc/shadow even when the file permissions would otherwise permit it. The diagram below shows the two halves and the checkpoint between them.

%%{init: {'theme': 'dark', 'themeVariables': { 'background': '#0d1117', 'primaryColor': '#1e293b', 'primaryTextColor': '#e2e8f0' }}}%% graph TD classDef space fill:#1e293b,stroke:#88c0d0,stroke-width:2px,color:#eceff4; classDef component fill:#0f172a,stroke:#3b4252,stroke-width:2px,color:#eceff4; classDef security fill:#7f1d1d,stroke:#88c0d0,stroke-width:1px,color:#eceff4; subgraph UserSpace ["User Space (Restricted Privileges)"] App["User Applications
(Web Browser, Shell, Server)"]:::component Lib["System Libraries
(glibc)"]:::component end subgraph KernelSpace ["Kernel Space (Full Privileges)"] Syscall["System Call Interface
(sys_read, sys_write, etc.)"]:::component LSM["Linux Security Modules (LSM)
(AppArmor, SELinux)"]:::security KernelCore["Kernel Core Services
(Process, Memory, Network, VFS)"]:::component Drivers["Device Drivers & Hardware"]:::component end App --> Lib Lib -->|System Calls| Syscall Syscall --> LSM LSM -->|Access Decision| KernelCore KernelCore --> Drivers style UserSpace fill:#1e293b,stroke:#4c566a,stroke-width:2px,color:#88c0d0 style KernelSpace fill:#0f172a,stroke:#4c566a,stroke-width:2px,color:#88c0d0

Understanding the Linux Directory Structure

Linux organises everything under a single root directory, /. There are no drive letters; a second disk appears as a directory somewhere in the same tree. The layout is standardised by the Filesystem Hierarchy Standard, so a path you learn on Debian mostly transfers to Rocky — mostly, because /bin and /sbin are now symlinks into /usr on nearly every current distribution, and forensic tooling that assumes otherwise will hand you duplicate results.

The reason this matters for security is that the tree tells you where to look. Persistence lives in a small number of predictable places, and so does evidence.

DirectoryStandard PurposeSecurity & Auditing Context
/The root directory that anchors the entire filesystem tree.Every path originates here. Unauthorised write access to root is a critical risk.
/binEssential user binaries required in single-user mode.Contains core commands like ls, cp, and bash. Audit for unauthorised modifications.
/sbinEssential system binaries reserved for administrative tasks.Contains utilities like iptables, reboot, and fdisk. Restricted to root or sudoers.
/bootBootloader configurations, kernel images (vmlinuz), and initramfs.Critical for boot integrity. Write-protect to prevent evil maid attacks and bootkits.
/devDevice nodes representing physical and virtual hardware.Contains devices like /dev/sda (raw storage) and /dev/urandom. Raw drive access must be restricted.
/etcSystem-wide configuration files and databases.Houses credentials (/etc/shadow), user lists (/etc/passwd), and service configs. A primary audit target.
/homeHome directories for standard users (e.g., /home/alice).Holds user files, shell history, and SSH keys. Often monitored for indicators of compromise.
/rootDedicated home directory for the superuser (root).Separated from /home to remain accessible if user storage partitions fail. Strictly privileged.
/lib & /lib64Shared libraries required by system binaries.Contains shared objects (.so files). Must be protected against library preloading and hijacking.
/media & /mntMount points for removable media and manual filesystem mounts.Used when mounting external drives during incident response or forensic analysis.
/optAdd-on application software packages.Third-party tools install here. Check regularly for unpatched binaries.
/procVirtual filesystem exposing kernel state and process details.Exists only in memory. Security tools query /proc/<PID>/ to inspect process memory and arguments.
/sysVirtual filesystem exposing hardware and driver parameters.Used to query and modify kernel configurations and security settings at runtime.
/tmpTemporary directory accessible by all users.Uses the Sticky Bit to limit deletion. Watch for staging files during exploitation or malware execution.
/usrUser binaries, libraries, documentation, and source code.Contains /usr/bin and /usr/share. Kept read-only on hardened systems.
/varVariable files such as mail queues, databases, and logs.Contains /var/log (syslog, auth logs). Forward logs off-host to prevent tampering.

Discretionary Access Control: File Permissions

Linux’s default model is discretionary: the owner of a file decides who else may touch it, and root may ignore the decision entirely. That is the whole security model on most boxes, and it is weaker than people assume — a single world-writable script in a cron job is all it takes. Every file and directory is assigned to an owner and a group, and the kernel checks three tiers in order, stopping at the first that matches:

  1. User (u): The user who owns the file.
  2. Group (g): Members of the group associated with the file.
  3. Others (o): Everyone else on the system.

Running ls -l shows permissions as a character string like this:

-rwxr-xr-x 1 webadmin developers 1234 May 31 10:00 deploy.sh

Breaking it down:

  • The first character is the file type (- for regular file, d for directory, l for symlink).
  • The next nine characters are three permission triplets:
    • rwx (Owner): webadmin can read, write, and execute.
    • r-x (Group): The developers group can read and execute.
    • r-x (Others): Everyone else can read and execute.

That ordering catches people out. If you are webadmin and you strip your own write bit, being a member of developers does not give it back — the kernel matched on owner and stopped. It is also why “the file is 640 but I still can’t read it” is almost always a directory problem: you need execute on every directory in the path before the file’s own bits are ever consulted.

For a full guide covering octal notation, special bits (SUID, SGID, Sticky Bit), and Access Control Lists (ACLs), see our dedicated post on Linux File Permissions and Ownership Management .


Essential Linux Commands

Serious Linux work happens at the command line, and not out of nostalgia — a shell session is scriptable, loggable, and works identically over a 200 ms satellite link to a machine with no display attached. Commands follow this general format:

command [options] [arguments]

These are the ones you will type thousands of times. Learn them properly rather than half-remembering them, because the difference between rm -rf /tmp/staging and rm -rf /tmp/staging / is one character and no confirmation prompt:

CommandPurposeBasic Example
lsLists directories and file details. Use -la to show hidden files and permissions.ls -la /var/log
cdChanges the current working directory.cd /etc/ssh
pwdPrints the absolute path of the current directory.pwd
touchCreates an empty file or updates timestamps of an existing file.touch honeypot.log
rmRemoves files or directories. Use -r for recursive and -f to force.rm -rf /tmp/malicious_payload
chmodModifies access permissions on a file or directory.chmod 600 ~/.ssh/id_rsa
nano / vimTerminal-based text editors for editing configuration files.sudo vim /etc/hosts
manOpens the manual page for any command.man iptables

Advertisement

Why Choose Linux? A Cybersecurity Perspective

Each of these is a real advantage. Each of them also costs something, and the honest version says so:

  • Auditable source code. Anyone can inspect the kernel, which is how subtle bugs get found by people the vendor never hired. It is not a guarantee: Heartbleed and Shellshock both sat in widely read open-source code for years. “Many eyes” only works where eyes are actually looking, and that is unevenly distributed across the tree.
  • Minimal attack surface. A server install with no desktop, no printing stack and no unused daemons has far fewer things listening than a consumer OS. The cost is that you own the decision about what to remove, and stripping a module that something needed six months later produces a failure nobody connects back to the hardening ticket.
  • Granular privilege control. sudo gives you delegated administration with an audit trail, per-command rules, and no shared root password. It is also routinely undermined by a single ALL=(ALL) NOPASSWD: ALL line added to unblock a deployment, which is the first thing any local privilege-escalation check looks for.
  • Native hardening frameworks. SELinux and AppArmor confine a process to the files and operations its policy allows, which is what turns a web-server compromise into a contained nuisance rather than a whole-host loss. The trade-off is denials that surface as inexplicable application errors, and the reason setenforce 0 remains the most-followed piece of advice on the internet.
  • Stability and long uptime. Linux will happily run for years without a reboot, which matters for firewalls and IDS sensors. Long uptime is also a tell: it means you are running a kernel with known CVEs unless you are live-patching. Uptime is not a trophy.

Linux vs. Windows: The Enterprise Security Battle

FeatureLinuxWindows
Security ArchitectureDiscretionary Access Control (DAC) with optional MAC via SELinux or AppArmor. Low kernel footprint.Discretionary Access Control (DAC) with Mandatory Integrity Control (MIC) and Active Directory integration.
Attack Surface & VectorsPrimarily targeted via web application exploits, unpatched network services, misconfigured permissions, and container breakouts.Historically targeted by user-focused malware, phishing, macro scripts, Active Directory credential harvesting, and local privilege escalation.
Patching OperationsSoftware repositories allow seamless system updates. Supports live-patching to update a running kernel without reboots.Windows Update handles OS patches, but major security updates often require reboots, causing downtime.
Transparency & AuditabilityOpen-source. Enables binary verification, reproducible builds, and deep code inspection by anyone.Closed-source. Relies on vendor trust and third-party EDR integrations for visibility.
CustomisabilityHighly customisable — unused kernel modules, libraries, and utilities can be removed to reduce the attack surface.Monolithic design makes stripping core components difficult, leaving a larger software footprint.

The table flatters Linux, so here is the correction: Windows in an enterprise has centralised policy, a mature EDR ecosystem, and Group Policy that actually reaches every endpoint. Linux fleets frequently have none of that, and “we manage it with Ansible” often means three people manage it with Ansible and everything else drifted years ago. The platform is more securable; whether it is more secure in your estate is a question about your operations, not about the kernel.


A distribution is a set of decisions: which kernel version, which init system, which libc, which package manager, and — the one that actually matters in production — how long they will keep shipping security patches for the release you installed. Pick on the support lifecycle first and the desktop theme never. What you’re doing narrows it further:

  • Ubuntu & Debian: Ubuntu LTS is the default for cloud images and the one with the most third-party install instructions written against it; the standard LTS security window is five years, extended further under Ubuntu Pro. Debian stable updates conservatively, which is exactly what you want under a database and exactly what frustrates you under an application that needs a package two versions newer than the archive has.
  • Red Hat Enterprise Linux (RHEL), Fedora & Rocky Linux: The enterprise default, with SELinux enforcing out of the box and a long support lifecycle. RHEL buys you someone contractually obliged to answer the phone; Rocky gives you the same package base without that. Fedora is the upstream proving ground — useful for seeing what RHEL will look like in two years, unsuitable for anything you need to leave alone.
  • Arch Linux: Rolling release, no installer decisions made for you, and a wiki better than most vendors’ paid documentation. Rolling means you get security fixes fast and you also get a breaking change on a Tuesday. Excellent workstation, poor choice for a fleet you patch unattended.
  • Kali Linux & Parrot OS: Debian-based, preloaded with several hundred offensive and forensics tools. Both are testing platforms, not hardened hosts — Kali historically ran as root by default and is built to run tools, not to survive being attacked. Do not use one as a jump box.
  • Alpine Linux: A roughly 5 MB base built on BusyBox and musl libc, which is why so many container images start FROM alpine. The catch is musl: anything expecting glibc behaviour — DNS resolution edge cases, some Python wheels, several proprietary agents — may misbehave in ways that only show up under load.
  • Tails & Qubes OS: Tails runs from RAM and forces traffic through Tor, leaving nothing on disk by design; that also means nothing persists unless you deliberately configure it. Qubes isolates each activity in its own Xen VM, giving you the strongest desktop compartmentalisation available at the cost of GPU acceleration, battery life, and fussy hardware compatibility.

Modern Networking and Connectivity Commands

The single most useful command in an early triage is ss -tulpn. It answers the question everything else depends on: what is listening on this box, and which process owns it. Run it without sudo and the process column comes back empty for anything you don’t own — no error, just blanks — which is how people conclude a port has no owner.

[!NOTE] Legacy tools like ifconfig and netstat are deprecated in modern distributions and are frequently not installed at all on minimal images and containers. They have been replaced by the iproute2 utilities, which are faster and read kernel state through netlink rather than parsing /proc.

Modern UtilityLegacy ReplacementDescriptionCommon Usage
ip addrifconfigDisplays IP addresses, MAC addresses, and network interface configurations.ip a or ip addr show
ssnetstatInvestigates active sockets and shows listening network ports.ss -tulpn (TCP/UDP listeners with PIDs)
pingN/ASends ICMP echo requests to test connectivity to a host.ping -c 4 10.0.0.1
tracerouteN/AMaps the routing path packets take to reach a destination.traceroute 8.8.8.8
curl / wgetN/ACommand-line HTTP clients for downloading files or querying APIs.curl -I https://example.com
sshN/AOpens encrypted interactive sessions and port forwards to remote hosts.ssh -i key.pem user@host
# Identify listening ports and the processes behind them
sudo ss -tulpn

Frequently Asked Questions

Q: Is Linux inherently more secure than Windows?

No. It is more securable, which is a different claim. Privilege separation is strict, patches arrive quickly, and you can strip the system to almost nothing. None of that survives a server with password SSH on port 22, a five-year-old WordPress install, and no log forwarding — and that describes a great many Linux boxes on the internet right now. The compromises we get called about are almost never kernel bugs. They are exposed services, reused credentials, and a sudoers entry someone added at 6 p.m. to make a deploy work.

Q: Can Linux systems be infected by malware?

Yes, and the interesting cases are all server-side. Expect ELF backdoors, LD_PRELOAD and kernel-module rootkits, web shells dropped through an application flaw, cryptominers that show up first as a cloud bill, and IoT botnets in the Mirai lineage. Ransomware crews have spent years building Linux and ESXi lockers specifically, because encrypting a hypervisor’s datastores takes out every guest at once. The reason desktop antivirus signatures feel irrelevant here is that the payload usually is not a file sitting still — it is a process, a cron entry, and a systemd unit.

Q: Is Linux harder to learn than Windows?

Steeper at the start, flatter forever after. The first week is genuinely worse: no obvious place to click, error messages that assume you know what a file descriptor is, and documentation that answers a question adjacent to yours. What you get for it is a system where every action is expressible as text, which means it can be scripted, reviewed, version-controlled and run across a thousand hosts. That is the whole payoff, and it does not arrive until you stop trying to use the terminal as a slower file manager.


Additional Resources


Advanced Linux Concepts

Commands get you through a single box. Scripting and process management are what let you handle a hundred, and they are also where most self-inflicted outages originate.

Shell Scripting and Automation

A shell script is a program that runs as root, was written in ten minutes, and is never reviewed. Treat it accordingly. The example below is a backup routine with the two checks that people habitually skip — privilege verification and source validation — because a backup script that silently archives a directory that no longer exists produces a tidy 45-byte tarball every night and nobody notices until the restore.

#!/bin/bash
# Backup Script with basic input validation and logging

SOURCE_DIR="/var/www/html"
BACKUP_DIR="/opt/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
LOG_FILE="/var/log/backup_service.log"

# Verify execution as root or sudo
if [[ $EUID -ne 0 ]]; then
   echo "[CRITICAL] This backup script must be run as root." >&2
   exit 1
fi

# Validate source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
    echo "[ERROR] Source directory $SOURCE_DIR not found. Aborting." >> "$LOG_FILE"
    exit 1
fi

mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"

# Execute backup using tar archiving
BACKUP_FILE="$BACKUP_DIR/backup_$TIMESTAMP.tar.gz"
tar -czf "$BACKUP_FILE" "$SOURCE_DIR" 2>> "$LOG_FILE"

if [ $? -eq 0 ]; then
    echo "[SUCCESS] Backup of $SOURCE_DIR saved to $BACKUP_FILE on $(date)" >> "$LOG_FILE"
    chmod 600 "$BACKUP_FILE"
else
    echo "[FAILED] Backup execution failed on $(date)" >> "$LOG_FILE"
fi

[!WARNING] Shell Scripting Security Best Practices:

  1. Never hardcode secrets. Keep API keys, database passwords, and private keys out of scripts. Use environment variables or a secrets manager like HashiCorp Vault.
  2. Restrict execution permissions. Run chmod 700 script.sh so only the owner can read and execute it.
  3. Quote all variables. Use "$VAR" to prevent word splitting, globbing, and command injection vulnerabilities. An unquoted $DIR containing a space turns one argument into two, and rm -rf $DIR/* with DIR unset expands to rm -rf /*.
  4. Fail loudly. Add set -euo pipefail near the top. Without it a script carries on cheerfully after a failed command, which is how half a backup gets uploaded and marked successful.

Managing Processes and Signals

The kernel tracks every running application by Process ID (PID), and process state is where an intrusion usually becomes visible before anything else does — a bash with a parent of nginx, an outbound connection from a process whose binary has been deleted from disk, a miner politely renamed [kworker/0:2]. Processes run either in the foreground, holding your terminal, or in the background.

  • Background Execution: Append & to run a command without locking up your terminal:
    nmap -sV -p- 10.0.0.1 > scan_results.txt &
    
  • Signal Transmission: Processes respond to signals sent via the kill command:
    • SIGTERM (Signal 15): The default signal. Asks the process to clean up and exit gracefully.
    • SIGKILL (Signal 9): Cannot be caught or ignored. The kernel stops the process where it stands, so open files are not flushed and locks are not released — which is why reaching for -9 first is how you corrupt a database rather than restart it. It also will not help against a process stuck in uninterruptible sleep on failed I/O; that one needs the storage fixed, not a bigger signal.
CommandDescription
topShows live system resource usage and process tables.
htopAn interactive, colourised process viewer with filtering.
ps auxSnapshot of all active processes on the system.
kill -15 <PID>Requests graceful termination of a process.
kill -9 <PID>Forces immediate termination of a process.
nice / reniceSets or adjusts the CPU scheduling priority of a process.

Package Management Systems

A package manager is a supply-chain control, not a convenience. It resolves dependencies, verifies GPG signatures against keys you already trust, and gives you an inventory of what is installed and at what version — which is the only reason you can answer “are we affected?” on a CVE morning. Every curl … | sudo bash install you run steps outside that inventory, and those are precisely the packages nobody patches.

Distro FamilyPrimary ManagerInstall CommandUpdate System
Debian / Ubuntuaptsudo apt install ufwsudo apt update && sudo apt upgrade
RHEL / Rocky / Fedoradnf (formerly yum)sudo dnf install firewalldsudo dnf upgrade
Arch Linuxpacmansudo pacman -S nmapsudo pacman -Syu

[!IMPORTANT] Package managers verify integrity using GPG (GNU Privacy Guard) keys. If a signature cannot be verified, the manager aborts rather than installing a tampered file. This protection is only as good as the keys you have imported: adding a third-party repository means adding its signing key, and from that moment its maintainer can install anything on your system at root. Audit /etc/apt/sources.list.d/ and /etc/yum.repos.d/ on any host you inherit.


Advertisement

Linux in Cybersecurity and Server Management

Linux dominates backend infrastructure, so security teams end up needing both halves: ordinary server administration, and the tooling built on top of it.

Tools for Security Operations and Pentesting

Security distributions ship these preconfigured. Knowing what each one is actually good at saves you from the common mistake of reaching for the heaviest tool first:

  • Nmap: Port scanning, service version detection, and OS fingerprinting. Version detection (-sV) is what makes it useful and also what makes it noisy — it opens full connections and talks to services, which fragile embedded devices sometimes do not survive.
  • Metasploit Framework: Modular exploitation, primarily valuable for validating that a finding is real rather than theoretical. Running an exploit module against production is a decision with a blast radius; the memory-corruption ones can and do leave services dead.
  • Wireshark: A graphical packet analyser with dissectors for hundreds of protocols. Excellent for reading a capture, poor for taking one on a busy server — the GUI and the full dissection cost you memory you may not have.
  • tcpdump: The right tool for capture on a headless box. Take the pcap with a tight BPF filter and a -C/-W ring buffer, then read it in Wireshark somewhere else. Capturing unfiltered on a gigabit link fills the disk faster than most people expect.
  • John the Ripper / Hashcat: Password auditing against a hash dump you already have. Hashcat is GPU-driven and dramatically faster; John is more flexible about odd formats. Both are for offline cracking — pointing either at a live login service is a different, much louder activity.

Linux as a Secure Server OS

One box, one role, is the rule worth keeping. Every additional service on a host is another set of credentials, another log source nobody reads, and another way for a compromise of the least important thing on the machine to reach the most important:

  • Web servers: Apache (httpd) or Nginx for static content and reverse proxying. Bind the application itself to 127.0.0.1 and let the proxy be the only thing on a public port — otherwise the app is reachable directly and your proxy’s security headers and rate limits are decorative.
  • File servers: Samba for Windows interoperability, NFS for Unix-to-Unix. Neither belongs on an internet-facing interface; SMB in particular has a long history of being exactly the port worms travel over.
  • Database servers: PostgreSQL, MySQL, or MongoDB. Every one of these has shipped a version that listened on all interfaces by default at some point, and internet-wide scans still find thousands of them. Check the bind address before you check anything else.
  • Reverse proxies and load balancers: HAProxy, Nginx or Traefik in front of your application tier. They also become the point where TLS terminates, which means they hold the private keys and see every request in plaintext — treat them as your highest-value host, not as plumbing.

Enterprise-Grade Security Hardening Best Practices

A fresh cloud instance with a public IP will see its first SSH login attempt within minutes of the address being allocated — the scanning is continuous and entirely automated. None of it is targeted at you; it does not need to be. These five steps get you past the automated layer, which is the overwhelming majority of what will ever knock on the door:

1. Enable Automated Updates

Unpatched known vulnerabilities beat novel exploits in every breach report, year after year. Automate the patching. The trade-off is real — an unattended upgrade can restart a service at 3 a.m. or pull in a package change you did not test — so restrict it to the security pocket, and pair it with monitoring rather than pretending the risk is zero. On Ubuntu or Debian, use unattended-upgrades:

sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades

2. Configure a Host Firewall

Default-deny inbound, then allow the three ports you actually serve. One warning worth internalising: if Docker is installed, publishing a container port writes rules into the DOCKER chain that bypass UFW entirely, so a port you believe is firewalled may be answering the internet. Verify by scanning the host from another machine, not by reading ufw status.

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp comment 'SSH Access'
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'
sudo ufw enable

3. Harden the SSH Daemon

Turning off password authentication removes the entire brute-force category in one line — the scanners keep knocking, but there is nothing to guess. Edit /etc/ssh/sshd_config. Note that on current distributions a drop-in file under /etc/ssh/sshd_config.d/ may override whatever you write in the main file, which is the usual reason a change appears to have no effect:

# Disable root logins over SSH
PermitRootLogin no

# Enforce SSH public key authentication
PasswordAuthentication no

# Limit login access to specific users
AllowUsers security_admin sysop

Keep a second session open while you do this, and test the configuration before restarting. sshd -t catches syntax errors; it does not catch you having disabled password auth on a host where your key was never installed. That one you find out about immediately and permanently:

sudo sshd -t && sudo systemctl restart sshd

4. Monitor Log Files

Local logs are evidence right up until the moment someone owns the box, at which point they are whatever the intruder left behind. Watch them, but ship them off-host as well — a remote copy is the only version an attacker cannot edit:

  • Systemd Journal: Query active logs with journalctl:
    sudo journalctl -u ssh -g "Failed password" -f
    
  • Fail2Ban: Automatically block IPs that exceed login failure thresholds:
    sudo apt install fail2ban
    sudo systemctl enable --now fail2ban
    

5. Audit Local SUID Binaries

A SUID binary runs as its owner regardless of who launched it, which makes an unexpected one a straight path to root. Take this inventory on a freshly built host and keep it — the value is in the diff later, not the list today. Cross-check anything unfamiliar against GTFOBins, which catalogues exactly how ordinary utilities become escalation primitives once they carry the SUID bit:

find / -perm -4000 -type f 2>/dev/null

Take Your Linux Skills Further

  • “The Linux Command Line” by William Shotts — An excellent introduction to terminal usage for all skill levels.
  • “Linux Basics for Hackers” by OccupyTheWeb — Perfect for understanding Linux through a security and offensive tooling lens.
  • “How Linux Works” by Brian Ward — A deep dive into kernel internals, the boot process, and device drivers.

Online Training


100 Essential Linux Commands

The following reference covers 100 commands organised by function. Don’t memorise it — skim it once so you know a tool exists, then come back when you need it. Recognising the right command is the hard part; the flags are in man.

1. File and Directory Operations

CommandDescriptionUsage Example
lsLists files and directories in the current folder.ls -lh
cdChanges the current working directory.cd /var/log
pwdDisplays the absolute path of the current directory.pwd
mkdirCreates a new empty directory.mkdir -p /opt/data/scripts
rmdirRemoves an empty directory.rmdir /tmp/empty_dir
rmDeletes files or directories.rm -rf /tmp/staging_area
cpCopies files or folders to a new destination.cp config.conf config.conf.bak
mvMoves or renames files and directories.mv temp_file.txt /var/www/
touchCreates an empty file or updates access timestamps.touch access.log
lnCreates symbolic links to files or folders.ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/
findSearches for files by name, size, or permissions.find /etc -name "*.conf"
locateSearches files quickly using a pre-indexed database.locate shadow
statShows detailed filesystem metadata about a file.stat /etc/shadow
fileIdentifies the file type and encoding.file /bin/bash
treeDisplays directory contents in a nested tree structure.tree -d /var/log
CommandDescriptionUsage Example
catPrints file contents to the terminal.cat /etc/hostname
lessOpens file contents in an interactive pager.less /var/log/syslog
moreOlder, simple file pager for reading in the console.more /var/log/messages
headDisplays the first lines of a file (default: 10).head -n 20 /etc/passwd
tailDisplays the last lines of a file.tail -f /var/log/auth.log
grepSearches text using patterns or regular expressions.grep -i "failed" /var/log/auth.log
awkText scanning and processing language.awk -F: '{print $1}' /etc/passwd
sedStream editor for filtering and transforming text.sed -i 's/PermitRootLogin yes/PermitRootLogin no/g' sshd_config
cutExtracts sections from each line of a file.cut -d',' -f1 users.csv
sortSorts lines of text alphabetically or numerically.sort -n numbers.txt
uniqFilters duplicate lines from a sorted file.uniq -c sorted_ips.txt
wcCounts lines, words, and characters in a file.wc -l access.log
diffCompares two files and shows the differences.diff config.old config.new
teeRedirects stdin to both stdout and a file simultaneously.`echo “baseline”
xargsPasses output from one command as arguments to another.`find /tmp -name “*.log”

3. System Information and Hardware

CommandDescriptionUsage Example
unamePrints OS and kernel release information.uname -a
hostnameDisplays or sets the system hostname.hostname -f
uptimeShows how long the system has been running and CPU load.uptime
whoamiDisplays the effective user ID of the current shell.whoami
whoLists users currently logged into the system.who
wShows who is logged in and what they are running.w
lastDisplays a historical record of logged-in users.last -n 10
dmesgPrints messages from the kernel ring buffer.`dmesg -T
lshwShows detailed system hardware information.sudo lshw -short
lspciLists PCI buses and attached devices.lspci

4. Disk Management and Filesystems

CommandDescriptionUsage Example
dfReports filesystem disk space usage.df -h
duEstimates directory and file sizes.du -sh /var/www/*
lsblkLists block devices (hard drives, partitions).lsblk
mountMounts a physical or network filesystem.mount /dev/sdb1 /mnt/backup
umountUnmounts a mounted filesystem.umount /mnt/backup
fdiskModifies partition tables on block devices.sudo fdisk -l
partedModern partition tool supporting GPT.sudo parted /dev/sda print
mkfsFormats a partition with a filesystem type.sudo mkfs.ext4 /dev/sdb1
fsckChecks and repairs filesystem errors.sudo fsck /dev/sdb1
blkidDisplays UUIDs and properties of block devices.sudo blkid

5. Process Management and Performance

CommandDescriptionUsage Example
psLists a snapshot of active processes.`ps aux
topReal-time process monitoring.top
htopInteractive, user-friendly process viewer.htop
killSends a signal to a process.kill -15 1234
killallKills processes by name.killall apache2
pkillSends signals to processes matching a search string.pkill -u www-data
pgrepLists PIDs of processes matching a name.pgrep sshd
bgSends a suspended process to the background.bg %1
fgPulls a background process to the foreground.fg %1
jobsLists active jobs in the current terminal session.jobs

6. User, Group, and Privilege Management

CommandDescriptionUsage Example
sudoRuns a command with elevated root privileges.sudo apt update
suSwitches the session to another user.su - admin
idDisplays UID, GID, and group memberships for a user.id webadmin
passwdChanges passwords or locks user accounts.passwd alice
useraddCreates a new user on the system.sudo useradd -m bob
userdelRemoves a user and their home directory.sudo userdel -r bob
usermodModifies user settings and group memberships.sudo usermod -aG sudo bob
groupaddCreates a new user group.sudo groupadd pentesting
groupdelDeletes a user group.sudo groupdel pentesting
chageManages password expiration policies.sudo chage -l alice

7. Networking and Connectivity

CommandDescriptionUsage Example
pingSends ICMP echo requests to verify connectivity.ping -c 5 google.com
ipManages interface configurations and routing.ip route show
ssShows active socket connections (replaces netstat).ss -antp
tracerouteMaps network hops to a destination.traceroute 1.1.1.1
nslookupQueries DNS servers to resolve hostnames.nslookup target.local
digAdvanced DNS lookup tool (preferred over nslookup).dig MX google.com
curlCommand-line HTTP client for requests and downloads.curl -O https://example.com/payload.txt
wgetStandard file downloader over HTTP/FTP.wget -c https://example.com/iso.img
sshOpens secure encrypted sessions on remote hosts.ssh sysop@192.168.1.50
scpCopies files securely between hosts over SSH.scp local_file.txt user@host:/var/www/
rsyncEfficient incremental directory sync tool.rsync -avz /src/ /backup/
netstatLegacy network analysis tool.netstat -an
ifconfigLegacy network interface manager.ifconfig eth0
nmapPort scanner and network security mapper.nmap -sS -p 22,80,443 192.168.1.0/24
tcpdumpCaptures raw packet traffic on an interface.sudo tcpdump -i eth0 port 80 -w web.pcap

8. Package Management

CommandDescriptionUsage Example
aptPackage manager for Debian and Ubuntu.sudo apt install fail2ban
dnfPackage manager for Fedora, Rocky, and RHEL.sudo dnf install httpd
pacmanPackage manager for Arch Linux.sudo pacman -Syu
dpkgInstalls or removes local .deb packages.sudo dpkg -i package.deb
rpmInstalls or removes local .rpm packages.sudo rpm -ivh package.rpm

9. Compression and Archiving

CommandDescriptionUsage Example
tarArchives files (-c create, -x extract).tar -czvf backup.tar.gz /var/www
gzipCompresses a file using GNU zip.gzip logs.txt
gunzipDecompresses gzip files.gunzip logs.txt.gz
zipCompresses files into a zip archive.zip -r web.zip /var/www/html
unzipExtracts a zip archive.unzip web.zip -d /opt/web

10. Shell Builtins and Command History

CommandDescriptionUsage Example
echoPrints text to terminal output.echo $PATH
historyLists previously typed commands.history 15
aliasDefines shortcuts for commands.alias ll='ls -la'
clearClears the terminal display.clear
exitCloses the current shell session.exit

Pro tip: man <command> is the authoritative reference for the exact version installed on the box in front of you, which a web search is not. When the man page is dense, man 5 <file> covers configuration file formats and apropos <keyword> finds the command when you only remember what it does.

The way this knowledge actually sticks is by breaking something you can afford to break. Build a VM, harden it using the five steps above, then scan it from another machine and see what still answers. The gap between what you configured and what the scan reports is the entire lesson. ✨


Share article

Subscribe to my newsletter

Receive my case study and the latest articles on my WhatsApp Channel.

Warning

Ask CyberROX AI