Linux System Administration Questions
Operating and maintaining Linux and Unix systems: filesystems and permissions, process and service management, package management and updates, shell and scripting, storage, and network configuration on the host. Covers day-to-day administration, troubleshooting, monitoring and tuning host resource usage (CPU, memory, swap, and I/O), and hardening of Linux servers that underpin most infrastructure. The Linux operator's core skill set.
You must add a new user for an application operator and configure SSH key-based authentication, sudo access for a limited set of commands, and enforce disabling password authentication. Describe the exact commands and configuration steps (including edits to sshd_config and sudoers.d) to achieve this securely and how to rotate that user's SSH keys.
Sample Answer
Direct answer
Creating a properly locked-down operator account means four things happening in the right order: create the account and its home directory, install their public key for authentication (never generate or transmit their private key yourself), grant sudo for a named, minimal set of commands via a dedicated file under sudoers.d, and only after confirming the key works, disable password authentication so the key becomes the only way in. Rotation later follows the same "add the new, verify it, then remove the old" order in reverse.
Structured elaboration
1. Create the user:
useradd -m -s /bin/bash opuser
-m creates the home directory, -s /bin/bash sets their login shell. (On Debian/Ubuntu, adduser opuser is the friendlier interactive wrapper around the same underlying useradd; on RHEL/CentOS/Fedora, useradd is the standard direct tool either way, so the command above works unchanged across both families.)
2. Set up SSH key-based authentication for that user:
mkdir -p /home/opuser/.ssh
echo "<their-public-key-contents>" > /home/opuser/.ssh/authorized_keys
chmod 700 /home/opuser/.ssh
chmod 600 /home/opuser/.ssh/authorized_keys
chown -R opuser:opuser /home/opuser/.ssh
The permissions matter beyond just tidiness: sshd refuses to trust an authorized_keys file (or its parent .ssh directory) that's group- or world-writable, and silently falls back to rejecting key auth for that user rather than warning you, which is a common source of "I set this up correctly and it still won't let me in" confusion.
3. Grant scoped sudo access via a dedicated sudoers.d file, never by editing /etc/sudoers directly:
echo 'opuser ALL=(root) /usr/bin/systemctl restart myapp, /usr/bin/journalctl -u myapp' > /etc/sudoers.d/opuser
chmod 440 /etc/sudoers.d/opuser
visudo -c
Naming exact command paths (not a wildcard like ALL) is what makes this "limited": opuser can restart and read logs for that one service and nothing else as root. visudo -c validates every file under sudoers.d for syntax errors before it's live; skipping this step risks a typo that either breaks sudo entirely for everyone or, worse, grants broader access than intended.
4. Test key-based login BEFORE disabling password authentication. Only once you've confirmed ssh opuser@host works with the key and no password prompt, edit /etc/ssh/sshd_config (or, cleaner, a fleet-wide drop-in under /etc/ssh/sshd_config.d/ if this policy applies broadly) to set PasswordAuthentication no, then:
sshd -t
systemctl reload sshd
sshd -t validates the config syntax without touching the running daemon; reloading (not restarting) applies it without dropping any currently open sessions, so if something's wrong you still have a way back in through your existing connection.
Rotating this user's SSH key later: append the new public key to authorized_keys alongside the old one first, confirm the new key authenticates successfully, and only then remove the old key line from the file. Never delete the old key before confirming the new one works: that ordering (add, verify, remove) is what prevents a rotation from turning into an accidental lockout.
Worked example
On Ubuntu 24.04: useradd -m -s /bin/bash opuser, set up .ssh/authorized_keys as above, add /etc/sudoers.d/opuser scoped to systemctl restart myapp and journalctl -u myapp, confirm visudo -c passes, test ssh opuser@host with the key succeeds without a password prompt, then set PasswordAuthentication no fleet-wide and reload. On RHEL 9 or CentOS Stream, the sequence is identical except SELinux (Security-Enhanced Linux, a kernel-level mandatory access
control layer that enforces its own permission rules on top of standard Unix file permissions) is
enforcing by default, so after placing authorized_keys, also run restorecon -R -v /home/opuser/.ssh to make sure the SELinux context on that directory matches what sshd's policy expects; without it, sshd can refuse the key even though the Unix permissions (700/600) are perfectly correct, which is a distribution-specific gotcha worth checking explicitly rather than assuming Ubuntu's behavior carries over unchanged.
Trade-offs & pitfalls
- Disabling password authentication before verifying the key works is the single most common way to lock out the very account you just created; always test first.
- A wildcard like
opuser ALL=(root) ALLdefeats the entire point of "limited sudo access"; naming exact command paths is what makes the grant auditable and bounded. - Editing
/etc/sudoersdirectly instead of using a file undersudoers.drisks a syntax error that breakssudofor the whole system, with no safety check;visudo(orvisudo -con asudoers.dfile) exists specifically to catch that before it's live. - Forgetting the SELinux context step on an enforcing RHEL-family host is a real, distro-specific failure mode, not a hypothetical: correct Unix permissions alone don't guarantee
sshdwill accept the key there.
Describe how SSH public key authentication works end-to-end. Include steps to generate a key pair, install the public key on a remote host, secure the private key, and how ssh-agent and agent forwarding work. Mention common pitfalls during setup.
Sample Answer
The end-to-end flow
SSH (Secure Shell) public-key authentication relies on asymmetric cryptography: a key pair where the private key never leaves the machine it was generated on, and the public key can be shared freely because it's mathematically infeasible to derive the private key from it. Authentication works by the server challenging the client to prove possession of the private key, without the private key ever being transmitted.
-
Generate a key pair on the client machine:
bashssh-keygen -t ed25519 -C "alice@laptop"-t ed25519selects a modern elliptic-curve algorithm (shorter keys, fast, and currently considered at least as strong as RSA at commonly used key sizes; RSA with-t rsa -b 4096remains a fine, more universally compatible fallback for older systems that don't support ed25519).-Cattaches a comment (typically an identifying label, not a secret) to make it easy to tell keys apart later. This produces two files by default:~/.ssh/id_ed25519(the private key) and~/.ssh/id_ed25519.pub(the public key). -
Install the public key on the remote host, appending it to that account's authorized-keys list:
bashssh-copy-id -i ~/.ssh/id_ed25519.pub user@remote-hostssh-copy-idconnects (using whatever auth method currently works, typically a password for this one-time setup step), appends the public key's contents to~/.ssh/authorized_keyson the remote account, and fixes the permissions on~/.sshand the file if needed. Doing it by hand is equivalent:cat id_ed25519.pub | ssh user@remote-host 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys'. -
Authentication itself: when the client connects, the server looks up the offered public key in
authorized_keys, and if it's listed, issues a cryptographic challenge; the client's SSH agent (or thesshclient directly) signs it with the matching private key, and the server verifies that signature against the public key it already has on file. The private key itself is never sent over the network at any point.
Securing the private key
- File permissions matter and are enforced by the SSH client itself:
~/.sshshould be700and the private key file600;sshwill refuse to use a private key file with looser permissions (a deliberate protection against an accidentally world-readable key), reporting a "bad permissions" error rather than silently using an insecure key. - Generate the key with a passphrase (
ssh-keygenprompts for one interactively) so that anyone who copies the private key file itself still can't use it without also knowing the passphrase; an unencrypted private key is a single point of failure if the disk it's stored on is ever compromised or backed up somewhere less secure. - Never copy a private key to a remote or shared host "to make things easier"; the whole point of public-key auth is that only the public half needs to travel, and a private key that exists in two places doubles the surface for it to leak.
ssh-agent and agent forwarding
Typing a passphrase on every single connection is impractical, so ssh-agent holds a decrypted copy of the private key in memory for the duration of a session (ssh-add ~/.ssh/id_ed25519 loads it once, after which subsequent ssh connections use the agent-held key transparently without re-prompting). Agent forwarding (ssh -A user@jump-host) extends this further: it lets a private key held by your agent on your laptop be used to authenticate from a second hop (a jump/bastion host) onward to a third host, without the private key itself, or even a copy of it, ever being placed on the jump host; the jump host only relays signing requests back to your agent over the forwarded socket.
Common pitfalls during setup
- Wrong permissions on
~/.sshorauthorized_keyson the remote end (should also be700/600) is one of the most common causes of "I added my key and it still asks for a password," becausesshdon the server side enforces the same strictness and silently falls back to other auth methods rather than erroring clearly. - Agent forwarding (
ssh -A) trusts the jump host's root user (and anyone else with sufficient privilege there) not to abuse the forwarded agent socket while your session is active; on a jump host you don't fully control, this is a real exposure, and a safer alternative for exactly the "hop through a bastion" use case isProxyJump(ssh -J bastion target), which tunnels the connection through the bastion without exposing your agent socket to it at all. - Mixing up which key is which after generating several:
ssh -v(or-vvvfor more detail) shows exactly which key the client is offering and why the server accepted or rejected it, which is the fastest way to debug "why isn't this working" instead of guessing.
Trade-offs and pitfalls (setup-wide)
- A passphrase-protected key held in
ssh-agentis a reasonable balance between security and usability, but an agent with a loaded key is itself a resource: if your laptop is compromised while the agent is running and unlocked, an attacker can use the loaded key (via the agent) without ever needing the passphrase, since the agent has already done the decryption. ProxyJumpis generally the safer default over agent forwarding for bastion-hop scenarios specifically because it never extends trust to the intermediate host's ability to request signatures from your key.
Configure auditd rules to log all sudo executions and failed SSH login attempts with minimal performance impact. Provide sample auditctl or /etc/audit/rules.d rules and explain how to query these entries using ausearch or aureport and how to correlate with journalctl.
Sample Answer
Direct answer
Write persistent rules under /etc/audit/rules.d/ (loaded automatically by augenrules, the supported,
reboot-safe path, rather than transient auditctl commands that vanish on reboot), scoped tightly to the
sudo binary and the sudoers files, and rely on SSH's own PAM (pluggable authentication modules)-integrated
logging, correlated through the same audit trail, for failed login attempts, since a failed password
doesn't correspond to one clean syscall event auditd can key on the way a file open does.
Structured elaboration
Rule for sudo executions (syscall-based, since "someone ran sudo" is best captured at execution time):
-a always,exit -F arch=b64 -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=4294967295 -k sudo_exec
-a always,exit -F arch=b32 -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=4294967295 -k sudo_exec
-a always,exit generates a record at syscall exit, the point where the full outcome, including
success or failure, is known. Both arch=b64 and arch=b32 variants are needed, a 64-bit-only rule
silently misses a 32-bit invocation of the same binary on a system where that's still possible. -F path=/usr/bin/sudo -F perm=x scopes this to executions of sudo specifically, a broad, path-less
execve rule would log every program launch fleet-wide, a serious log-volume and performance cost for
little extra signal beyond watching this one binary. auid>=1000 -F auid!=4294967295 filters to real,
interactively logged-in users: auid (the audit user ID, set once at login and unlike the UID a process
might later switch to, never changes for that login session) is the correct field for "which human actually
triggered this" even after a privilege change; UIDs below 1000 are conventionally system accounts, and
4294967295 is the sentinel value meaning "no login at all".
Watching the sudoers files themselves, since auditing executions is only half the picture, someone
editing WHO CAN sudo matters just as much:
-w /etc/sudoers -p wa -k sudoers_changes
-w /etc/sudoers.d/ -p wa -k sudoers_changes
(-w is a simpler, cheaper path-watch for files that rarely change; -p wa logs writes and
attribute changes.)
Failed SSH login attempts: these aren't captured via a syscall rule at all, the authoritative record is
sshd's own log through PAM, in /var/log/secure or /var/log/auth.log depending on distribution, or
centrally via journalctl -u sshd. Where auditd adds real value here is PAM's own audit integration: pam_unix
and similar modules emit USER_AUTH/USER_LOGIN records when compiled with audit support, and ausearch -m USER_AUTH,USER_LOGIN -su failed surfaces those failures alongside sudo executions and sudoers edits in ONE
unified, searchable trail, the real value here is correlation into the same place, not a new detection
mechanism.
Minimizing performance impact: avoid unscoped -S execve or -S open,openat rules with no path or auid
filter, they fire on nearly everything the kernel does and can measurably slow a busy host, since every
matching syscall round-trips through the audit subsystem before returning. Prefer -w path-watches for
rarely-changing files and narrow, path-and-auid-filtered -a rules for anything execution-based, and size
the kernel's audit backlog (auditctl -b 8192 or higher on a busy host) so a burst of matching events
doesn't overflow it and either drop records or, if configured to panic on overflow, affect the system.
Querying: ausearch -k sudo_exec -ts today pulls today's tagged records; ausearch -k sudoers_changes -i (-i interprets numeric UIDs and syscall numbers back into names) for readability; aureport --summary
or aureport -au (authentication report) for a rolled-up overview instead of reading raw records one at a
time.
Correlating with journalctl: ausearch's output timestamp can be cross-referenced against
journalctl --since "<time>" --until "<time>" for the same narrow window, lining a suspicious sudo
execution up against what else was happening on the host (a login, a cron job firing, an application
restart), since neither log alone usually tells the full story of an incident.
Worked example
A persistent rules file, /etc/audit/rules.d/sudo-and-auth.rules, containing the two sudo-exec rules
(b64 and b32) and the two sudoers watches above, loaded with augenrules --load and confirmed present via
auditctl -l. Querying after a suspicious sudo invocation:
ausearch -k sudo_exec -ts today -i
returns records in the standard auditd format (illustrative, field values will differ per event):
type=SYSCALL msg=audit(1699999999.123:456): arch=x86_64 syscall=execve success=yes exit=0
auid=jdoe uid=jdoe gid=jdoe euid=root exe="/usr/bin/sudo" key="sudo_exec"
The auid=jdoe field is what answers "who", even though euid=root shows the process's effective
privilege after sudo did its job.
Trade-offs and pitfalls
A rule that filters by -F uid=0 instead of auid misses the entire point: by the time sudo has done its
job the EFFECTIVE uid is already 0 regardless of who invoked it, auid (fixed at login) is what actually
answers "who", not uid/euid at execution time. Rules added transiently with a bare auditctl -a ...
command survive only until reboot, a common on-call mistake where a rule is added live to catch something
in progress, the incident resolves, the host reboots for an unrelated patch, and the rule silently vanishes
with no record it ever existed, /etc/audit/rules.d/ plus augenrules is what makes a rule permanent.
Describe how you would use strace to diagnose a program that fails with 'Permission denied' when opening a config file. Include the strace invocation, how to capture output across forks, how to filter to file-related syscalls, and what specific return values you'll look for in the trace.
Sample Answer
Direct answer
Run the failing program under strace, filter to the file-related syscalls, and read the specific syscall's
return value and its error number (errno), since a "Permission denied" surfacing at the application level is
really the LAST in a sequence of file-related syscalls the kernel may have rejected, and strace shows
exactly which call, on exactly which path, with exactly which errno, the actual ground truth for what the
kernel refused and why.
Structured elaboration
Basic invocation:
strace -f -e trace=open,openat,stat,fstat,access -o trace.out <command>
-f (follow forks) matters for anything that forks or execs a child before the actual open() happens,
shell wrappers and many daemons do exactly this, without -f you'd only see the parent's syscalls and miss
the real one entirely. -e trace=<syscalls> filters the noise so you're reading the relevant handful of
lines instead of thousands of unrelated syscalls. -o writes to a file rather than interleaving with the
program's own output, keeping the trace clean to search afterward.
Capturing output across forks: add -ff alongside -f to write one trace file per process
(trace.out.<pid>) instead of interleaving every forked process into one file, useful when many children
are involved and you want to isolate one specifically. -tt adds microsecond timestamps to every line, so
you can correlate exact syscall timing against application-log timestamps.
What to look for: a line such as openat(AT_FDCWD, "/etc/myapp/config.conf", O_RDONLY|O_CLOEXEC) = -1 EACCES (Permission denied). The arguments show the EXACT path actually resolved (catching, for example, a
symlink resolving somewhere unexpected, or a relative path resolving against a different working directory
than assumed), and the return value plus errno pair is the ground truth for what the kernel rejected. If the
trace instead shows the open succeeding but a LATER read or write failing, that points away from basic
file permissions entirely (toward something like a quota, a stale NFS handle, or a security-module check
that gates specific operations differently from the open itself), so read the whole relevant sequence, not
just the first hit.
Attaching to an already-running process instead of launching fresh: strace -f -p <pid> -e trace=open,openat,access, for a failure buried deep inside an already-running long-lived service rather
than at simple startup.
Worked example
A non-root user's Python process attempts open("/etc/myapp/config.conf") on a file chmod'd to 000 (no
permission bits for anyone). The trace shows:
openat(AT_FDCWD, "/etc/myapp/config.conf", O_RDONLY|O_CLOEXEC) = -1 EACCES (Permission denied)
and Python's own traceback confirms PermissionError: [Errno 13] Permission denied, the same EACCES
(errno 13) the kernel returned, simply re-surfaced through the language runtime. This trace line is what
actually PROVES the cause is the Unix permission bits themselves, rather than, for example, the path not
existing at all (which would show ENOENT instead) or a mandatory-access-control denial such as SELinux
(which produces the identical EACCES at this syscall level, and only the audit log, not strace,
distinguishes the two).
Trade-offs and pitfalls
strace adds real overhead, each traced syscall round-trips through the kernel's ptrace mechanism (the
same facility strace itself is built on: the kernel stops the traced process at every syscall entry and
exit so strace can inspect and log it before letting it continue), so attaching it broadly (especially
-f across many threads or children) to a busy, latency-sensitive production process can itself cause
visible latency or timeouts. Scope the syscall filter as tightly as possible and detach as soon as the one
relevant event has been captured, rather than leaving a broad trace running. A genuinely intermittent
permission failure (works most of the time, fails occasionally) is much better caught by attaching with
-p and a narrow filter left running briefly than by trying to reproduce it fresh each time, since a
"works on retry" bug is often a race (a config file briefly holding the wrong permissions during a deploy,
for example) that a single fresh invocation won't reliably hit.
Explain basic Linux firewall concepts: netfilter hooks, the iptables chains INPUT/OUTPUT/FORWARD, default policies, and how firewalld maps zones to rules. Show commands to list current rules and how to temporarily allow a port for debugging.
Sample Answer
Direct answer
Netfilter is the packet-filtering framework built into the Linux kernel; it defines five fixed points (hooks) a packet passes through on its way in, out, or through the box, and both iptables and firewalld are just user-space tools for placing rules at those hooks, not separate filtering engines of their own. iptables's filter table exposes three of those hooks as chains you actually write rules against day to day: INPUT (packets destined for this host), OUTPUT (packets originating from this host), and FORWARD (packets passing through this host to somewhere else, relevant on a router or NAT gateway). firewalld sits a layer above either iptables or the newer nftables backend and lets you think in terms of named zones (trust levels assigned to interfaces or sources) instead of raw chains and rules directly.
The hooks, the chains, and how firewalld maps onto them
flowchart TD
A[Packet arrives on NIC] --> B[PREROUTING hook]
B --> C{For this host,<br/>or passing through?}
C -->|for this host| D[INPUT hook]
D --> E[Local process]
C -->|passing through| F[FORWARD hook]
E -->|reply sent| G[OUTPUT hook]
F --> H[POSTROUTING hook]
G --> H
H --> I[Packet leaves NIC]
- The kernel's netfilter framework defines all five hooks shown above; the
iptablesfiltertable (the default table, used for allow/deny decisions) only attaches toINPUT,OUTPUT, andFORWARD. Thenattable attaches toPREROUTINGandPOSTROUTINGinstead (DNAT rewrites the destination inPREROUTING, before the routing decision; SNAT andMASQUERADErewrite the source inPOSTROUTING, after it;natalso has anOUTPUTchain for packets the host itself generates), which is why NAT and filtering rules live in conceptually different tables even though they ride the same underlying hooks. - Each chain has a default policy (
ACCEPT,DROP, orREJECT) applied when no rule in the chain matches the packet:iptables -P INPUT DROPsets theINPUTchain's fallback to silently drop anything not explicitly allowed, which is the standard posture for a host you want locked down by default. firewalldmaps interfaces or source addresses to zones (public,internal,trusted,drop, and others), each zone carrying its own set of allowed services and ports; adding an interface to thetrustedzone effectively opens everything on it, whiledropsilently discards everything with no reply at all. Underneath,firewalldtranslates zone and service configuration into actualnftablesrules (the default backend on current Fedora/RHEL) oriptablesrules on older systems; you are still ultimately configuring the same netfilter hooks, just through a higher-level vocabulary aimed at "which network is this interface on" rather than "which chain and rule."
Listing rules and temporarily allowing a port for debugging
Listing current rules:
iptables -L -n -v
(-n avoids slow DNS lookups on every address, -v adds packet and byte counters per rule, useful for confirming a rule is actually being hit at all.)
With firewalld:
firewall-cmd --list-all
shows the active zone's services, ports, and any rich rules in one summary.
Temporarily allowing a port for debugging (not surviving a reboot or firewall reload):
iptables -I INPUT -p tcp --dport 8080 -j ACCEPT
(-I inserts at the top of the chain, so it is evaluated before any earlier DROP rule that would otherwise match first.)
firewall-cmd --add-port=8080/tcp
(without --permanent, this only affects the current runtime configuration and reverts on the next firewall-cmd --reload or service restart, which is exactly the point for a debugging-only change you do not want to accidentally leave in place.)
Trade-offs and pitfalls
- A rule added with plain
iptables -I/-A(without also saving it through the distribution's persistence mechanism, such asiptables-savepiped into a startup script, ornetfilter-persistent) is gone on the next reboot; this is a feature when you are debugging, and a trap if you meant it to be permanent and forgot the second step. - Inserting with
-I(top of chain) versus appending with-A(bottom of chain) matters a great deal on a chain that already has aDROPrule partway through: append a newACCEPTrule after an existingDROPfor the same traffic and it will never be reached, sinceiptablesevaluates rules in order and stops at the first match. - Mixing manual
iptablesrules withfirewalldrunning on the same host is a common source of confusing, hard-to-reproduce behavior, sincefirewalldperiodically reconciles the actual ruleset against its own configuration and can silently remove rules it does not recognize as its own; pick one management layer for a given host and stay with it.
Unlock Full Question Bank
Get access to all 17 Linux System Administration interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.