Skip to content

Linux_Practical_Interview_251 500

Linux Practical Interview Questions (251-500)

Section titled “Linux Practical Interview Questions (251-500)”

Q251: How do you configure packet filtering?

Section titled “Q251: How do you configure packet filtering?”

What it is: iptables builds a packet filter rule set for the INPUT chain: accept established connections, SSH, HTTP, HTTPS and loopback traffic, then a final rule drops everything else, saved with iptables-save.

Why it is used: To firewall a host so only needed services are reachable from the network.

Terminal window
# Basic iptables rules
# Allow established connections
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow localhost
iptables -A INPUT -i lo -j ACCEPT
# Drop everything else
iptables -A INPUT -j DROP
# Save rules
iptables-save > /etc/iptables/rules.v4

Interview talking point: “Rules are appended in order and the blanket -A INPUT -j DROP sits last, so earlier ACCEPT rules decide what passes, and conntrack ESTABLISHED lets replies back in without opening a symmetric rule.”

Q252: How do you configure packet filtering?

Section titled “Q252: How do you configure packet filtering?”

What it is: iptables packet filtering builds an ordered INPUT rule list allowing loopback, established connections, SSH, and web ports, then drops everything else.

Why it is used: To firewall a host so only intended services are reachable from the network.

Terminal window
# Basic filter rules
# Allow loopback
iptables -A INPUT -i lo -j ACCEPT
# Allow established
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Drop everything else
iptables -A INPUT -j DROP
# Forward rules
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
# Rate limiting
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

Interview talking point: “Rule order decides fate because the first matching rule wins, so the final DROP only catches what earlier accepts missed, and the recent module caps SSH attempts per minute.”

What it is: UFW is a simplified firewall frontend. It sets default deny incoming and allow outgoing, then adds rules for services, ports, or source ranges, with numbered rules you can delete.

Why it is used: To open firewall access quickly on Debian or Ubuntu hosts while keeping a default-deny posture.

Terminal window
# Install
apt install ufw
# Enable
ufw enable
ufw default deny incoming
ufw default allow outgoing
# Rules
ufw allow ssh
ufw allow 80/tcp
ufw allow from 192.168.1.0/24 to any port 5432
# Status
ufw status numbered
ufw delete 1
# Logging
ufw logging on
ufw logging low

Interview talking point: “ufw status numbered gives each rule a number so ufw delete 1 removes exactly that rule, and logging can be set to on or low. Default deny incoming with default allow outgoing means only explicitly allowed entries such as ssh and 80/tcp are reachable.”

Q254: How do you implement IPTables firewall?

Section titled “Q254: How do you implement IPTables firewall?”

What it is: An iptables firewall flushes old rules, sets DROP policies on INPUT and FORWARD, accepts loopback, established traffic and chosen ports, then saves with iptables-save.

Why it is used: To restrict inbound network access to only the services a host actually offers.

Terminal window
# Flush existing rules
iptables -F
iptables -X
iptables -t nat -F
iptables -t mangle -F
# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Loopback
iptables -A INPUT -i lo -j ACCEPT
# Established connections
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# SSH
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
# HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Rate limiting
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
# Save rules
iptables-save > /etc/iptables/rules.v4

Interview talking point: “Rules are evaluated in order within a chain, so the ESTABLISHED,RELATED accept comes before new connections, and the recent module rate-limits SSH to four new connections per sixty seconds.”

What it is: firewalld is a zone-based firewall daemon managed with firewall-cmd. It lists and adds services or ports, exposes zones, applies rich rules for a source, and saves runtime state.

Why it is used: To manage firewall rules dynamically on Red Hat style systems without hand-editing rules files.

Terminal window
# Install
apt install firewalld
# Services
firewall-cmd --list-services
firewall-cmd --add-service=http
firewall-cmd --add-port=8080/tcp
# Zones
firewall-cmd --get-zones
firewall-cmd --zone=public --list-all
# Permanent
firewall-cmd --runtime-to-permanent
# Rich rules
firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" accept'

Interview talking point: “firewall-cmd changes are runtime only until you run —runtime-to-permanent, so a reboot loses them otherwise. Scoping matters too: —zone=public —list-all queries one zone, and —add-service=http differs from opening a raw port with —add-port=8080/tcp.”

What it is: Layer 7 matching with ipp2p and layer7 inspects beyond ports, such as protocol signatures; the shown rules drop forwarded P2P traffic and bittorrent flows in the FORWARD chain.

Why it is used: Blocks application traffic that plain port rules cannot reliably identify.

Terminal window
# Install
apt install ipp2p
# Block P2P
iptables -A FORWARD -m ipp2p --ipp2p -j DROP
# With conntrack
iptables -A FORWARD -m layer7 --l7proto bittorrent -j DROP

Interview talking point: “The contrast with conntrack matching is depth: stateful rules decide by connection state, while these inspect payload to name the application, which is more precise but needs extra match modules installed on the host.”

What it is: nftables builds rules from tables and chains: an inet filter input hook accepts established connections, and a separate ip nat table with a postrouting hook applies masquerade on eth0.

Why it is used: Firewalling and NAT on modern Linux through one unified rules engine.

Terminal window
# Create table
nft add table inet filter
# Add chain
nft add chain inet filter input { type filter hook input priority 0; }
# Add rule
nft add rule inet filter input ct state established,related accept
# NAT
nft add table ip nat
nft add chain ip nat postrouting { type nat hook postrouting priority 100; }
nft add rule ip nat postrouting oifname "eth0" masquerade

Interview talking point: “The hook and priority decide where a chain sits in the packet path, and masquerade needs a nat-type table with a postrouting hook, which is why that rule cannot live inside the filter table.”

What it is: nftables is the successor framework to iptables. A ruleset file starts with flush ruleset, defines an inet filter table with input, forward and output chains, each with a hook and a policy, and nft -f loads it.

Why it is used: To filter traffic with one declarative ruleset file loaded in one pass with nft -f.

Terminal window
# Install
apt install nftables
# Create ruleset
cat > /etc/nftables.conf <<EOF
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
iif lo accept
tcp dport ssh accept
tcp dport http accept
tcp dport https accept
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy accept;
}
}
EOF
# Reload
nft -f /etc/nftables.conf
systemctl enable nftables

Interview talking point: “Each chain declares its hook and a default policy, so input and forward fall through to policy drop unless a rule matches, while output keeps policy accept; the whole file is reloaded with nft -f /etc/nftables.conf.”


Q259: How do you configure Dovecot with SASL?

Section titled “Q259: How do you configure Dovecot with SASL?”

What it is: Dovecot supplies SASL authentication for Postfix. It creates a unix listener inside Postfix’s spool owned by user and group postfix with mode 0660, and allows the plain and login mechanisms backed by system accounts.

Why it is used: To centralize mail password checking in Dovecot while Postfix stays focused on SMTP.

/etc/dovecot/10-master.conf
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}
# /etc/dovecot/10-auth.conf
auth_mechanisms = plain login
!include auth-system.conf.ext

Interview talking point: “Postfix does not check passwords itself; it hands off over the private/auth unix socket, whose 0660 mode and postfix ownership grant exactly that process access and nobody else.”

What it is: Dovecot is the IMAP and POP3 server that lets clients read mail. dovecot.conf enables imap and pop3, 10-auth.conf disables plaintext auth, 10-mail.conf sets maildir storage, and 10-user.conf reads users from the passwd database.

Why it is used: To give mail clients remote access to mailboxes once a mail transfer agent handles delivery.

/etc/dovecot/dovecot.conf
# Install
apt install dovecot-core dovecot-imapd dovecot-pop3d
protocols = imap pop3
listen = *
# /etc/dovecot/10-auth.conf
disable_plaintext_auth = yes
auth_mechanisms = plain login
# /etc/dovecot/10-mail.conf
mail_location = maildir:~/Maildir
# Configure userdb
# /etc/dovecot/10-user.conf
userdb {
driver = passwd
}
systemctl restart dovecot

Interview talking point: “Postfix and Dovecot split the job: Postfix moves mail and Dovecot serves it, and with mail_location set to maildir each message is a file, while disable_plaintext_auth keeps credentials off unencrypted connections.”

What it is: Dovecot is a mail server providing IMAP and POP3. dovecot.conf selects protocols, 10-auth.conf controls authentication, and 10-mail.conf sets maildir storage under each user’s home directory.

Why it is used: To give users mailbox access while Postfix handles sending and relaying.

/etc/dovecot/dovecot.conf
# Install
apt install dovecot-core dovecot-imapd
protocols = imap pop3
listen = *
# /etc/dovecot/10-auth.conf
disable_plaintext_auth = yes
auth_mechanisms = plain login
# /etc/dovecot/10-mail.conf
mail_location = maildir:~/Maildir
# Userdb (PAM)
# /etc/dovecot/10-auth.conf
!include auth-system.conf.ext
systemctl restart dovecot

Interview talking point: “disable_plaintext_auth = yes refuses password login before encryption is negotiated, so it pairs with TLS on the same service. mail_location shows mail is stored per user in a Maildir, and including auth-system.conf.ext means PAM system accounts do the authentication.”


What it is: Dovecot is a mail retrieval server speaking IMAP and POP3. Its config sets authentication mechanisms, Maildir storage location, PAM password checks, and mandatory TLS with certificate and key paths.

Why it is used: To let users read mail securely from a Postfix-hosted mailbox over IMAP or POP3.

/etc/dovecot/dovecot.conf
# Install
apt install dovecot-imapd dovecot-pop3d
protocols = imap pop3
listen = *
base_dir = /var/run/dovecot/
# Authentication
# /etc/dovecot/conf.d/10-auth.conf
disable_plaintext_auth = yes
auth_mechanisms = plain login
# User database
# /etc/dovecot/conf.d/10-mail.conf
mail_location = maildir:~/Maildir
# PAM
passdb {
driver = pam
args = session_failure_delay=finite_secs
}
# SSL
# /etc/dovecot/conf.d/10-ssl.conf
ssl = required
ssl_cert = </etc/ssl/certs/dovecot.pem
ssl_key = </etc/ssl/private/dovecot.pem

Interview talking point: “Requiring SSL refuses plaintext logins, and the mail location must match what Postfix wrote, here Maildir under the home directory, or users authenticate but see empty mailboxes.”

What it is: A Postfix relay forwards all mail to a smarthost given by relayhost, authenticating with SASL credentials stored in a password map compiled by postmap. A transport file can route only selected domains elsewhere.

Why it is used: To let a server send mail through an authenticated provider, for example from a cloud instance without port 25 access.

/etc/postfix/main.cf
# Postfix relay configuration
relayhost = [smtp.example.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_tls_security_level = encrypt
smtp_tls_security_level = encrypt
smtp_tls_wrappermode = no
# /etc/postfix/sasl_passwd
[smtp.example.com]:587 username:password
# Secure the password file
chmod 600 /etc/postfix/sasl_passwd
postmap /etc/postfix/sasl_passwd
# Relay for specific domains
# /etc/postfix/transport
example.com :[smtp.example.com]
* smtp:relay.other.com
# Test
echo "Test email" | sendmail -v user@example.com

Interview talking point: “sasl_passwd must be chmod 600 and then converted with postmap, since Postfix reads the generated database file rather than the plain text file you edit.”

What it is: A mail server pairs Postfix, configured in main.cf for SMTP with SASL and Maildir delivery, with Dovecot serving IMAP from the same Maildir.

Why it is used: To send and receive email for an organization on your own infrastructure.

Terminal window
# Install Postfix
apt install postfix
# Configure main.cf
# /etc/postfix/main.cf
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost, localhost.localdomain
home_mailbox = Maildir/
smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions = permit_sasl_authenticated, reject
# Install Dovecot
apt install dovecot-imapd
# Configure /etc/dovecot/conf.d/10-auth.conf
disable_plaintext_auth = yes
auth_mechanisms = plain login
# Configure /etc/dovecot/conf.d/10-mail.conf
mail_location = maildir:~/Maildir
# Create mail user
useradd -m -s /bin/bash mailuser
passwd mailuser

Interview talking point: “Postfix handles SMTP relay while Dovecot provides IMAP access, and smtpd_recipient_restrictions permit_sasl_authenticated, reject means only authenticated senders may relay before everyone else is refused.”

Q265: How do you configure Postfix mail server?

Section titled “Q265: How do you configure Postfix mail server?”

What it is: Postfix is a mail transfer agent that relays outbound mail. main.cf sets hostname, domains accepted locally, networks allowed to relay, and a relayhost with SASL authentication using a password map compiled by postmap.

Why it is used: To send alert and notification email from servers through an authenticated provider relay.

/etc/postfix/main.cf
# Install
apt install postfix mailutils
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
mydestination = $myhostname, localhost, localhost.localdomain
mynetworks = 192.168.1.0/24 127.0.0.0/8
relayhost = [smtp.provider.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_security_level = encrypt
# Create password map
echo "[smtp.provider.com]:587 username:password" > /etc/postfix/sasl_passwd
postmap /etc/postfix/sasl_passwd
systemctl restart postfix

Interview talking point: “mynetworks decides who may relay, so an open relay risk comes from getting that line wrong, and postmap must be run after editing sasl_passwd because Postfix reads the compiled hash map, not the plain file.”

Q266: How do you configure Postfix with LDAP?

Section titled “Q266: How do you configure Postfix with LDAP?”

What it is: postfix-ldap lets Postfix look up mail routing in an LDAP directory. virtual_alias_maps.cf names the server, the search base, the query filter mail=%s, and the result attribute used for forwarding.

Why it is used: To resolve virtual mailbox and alias addresses from a central directory instead of local map files.

/etc/postfix/ldap/virtual_alias_maps.cf
# Install
apt install postfix-ldap
server_host = ldap.example.com
search_base = ou=people,dc=example,dc=com
query_filter = mail=%s
result_attribute = mailForwardingAddress

Interview talking point: “query_filter mail=%s means the recipient address is substituted into the search, and result_attribute mailForwardingAddress supplies the replacement value. Keeping routing in LDAP means address changes do not require editing Postfix configuration files.”

Q267: How do you configure Postfix with SMTP auth?

Section titled “Q267: How do you configure Postfix with SMTP auth?”

What it is: Postfix configured to require SASL authentication. main.cf points SMTP authentication at Dovecot through a private auth socket with anonymous logins disabled, and master.cf switches SASL on only for the submission service with authenticated-client restrictions.

Why it is used: To make clients prove who they are before the server relays mail for them.

/etc/postfix/main.cf
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname
# /etc/postfix/master.cf
submission inet n - - - - smtpd
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject

Interview talking point: “The submission line overrides main.cf by enabling SASL there and setting client restrictions to permit authenticated then reject, which is what prevents the server being used as an open relay.”

What it is: Postfix is a mail transfer agent. main.cf sets the hostname, accepted domains, relay host, and SASL and TLS settings for an upstream relay; postmap compiles the password file into a hashed map.

Why it is used: To relay outgoing mail through a provider or run a local mail server.

/etc/postfix/main.cf
# Install
apt install postfix mailutils
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
mydestination = $myhostname, localhost, localhost.localdomain
mynetworks = 192.168.1.0/24 127.0.0.0/8
relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_security_level = encrypt
# Create credentials
echo "[smtp.gmail.com]:587 username:password" > /etc/postfix/sasl_passwd
postmap /etc/postfix/sasl_passwd

Interview talking point: “After editing /etc/postfix/sasl_passwd you must run postmap to build the hashed lookup file, or Postfix cannot read the credentials. smtp_tls_security_level = encrypt forces TLS, and mydestination defines which domains Postfix treats as locally delivered.”

What it is: Postfix is a mail transfer agent configured in main.cf, covering hostname, domains, mailbox format, and SASL authentication via Dovecot. master.cf defines service entries like submission, and postfix check plus reload validate and apply changes.

Why it is used: To send and receive email for a domain, optionally requiring authenticated submission.

/etc/postfix/main.cf
# Install
apt install postfix
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost, localhost.localdomain
home_mailbox = Maildir/
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions = permit_sasl_authenticated, reject
# Virtual aliases
# /etc/postfix/virtual
admin@example.com admin
support@example.com support@company.com
# Master.cf
submission inet n - y - - smtpd
-o syslog_name=postfix/submission
# Test
postfix check
postfix reload

Interview talking point: “mydestination says which domains this host accepts final delivery for, while the submission entry in master.cf is where you enable authenticated sending on port 587 with its own log name.”

Q270: How do you configure spam filtering?

Section titled “Q270: How do you configure spam filtering?”

What it is: SpamAssassin scores messages for spam indicators and can rewrite subjects or add headers. Postfix pipes mail through spamc via a content filter, and sa-learn trains the Bayesian classifier on known spam and ham samples.

Why it is used: To score and tag unwanted mail automatically so junk is filtered before delivery.

Terminal window
# Install SpamAssassin
apt install spamassassin spamc
# Configure Postfix
# /etc/postfix/master.cf
spamassassin unix - n n - - pipe
user=spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}
# /etc/postfix/main.cf
content_filter = spamassassin
# Configure SpamAssassin
# /etc/spamassassin/local.cf
required_score 5.0
rewrite_header Subject [SPAM]
report_safe 0
# Add headers
add_header all Status _YESNO_, score=_SCORE_ required=_REQD_ tests=_TESTS_
add_header all Reply-To _ADDR_
# Train bayes
sa-learn --spam /var/virusmails/*
sa-learn --ham /var/mail/*

Interview talking point: “The required score threshold decides when a message counts as spam, and training the Bayes classifier with sa-learn on real spam and ham sharply improves accuracy over the default rules.”

What it is: vsftpd is an FTP server configured in vsftpd.conf to reject anonymous users, allow local writes, enable SSL and restrict logins via a user list.

Why it is used: To provide file transfer to users while keeping the service jailed and encrypted.

Terminal window
# Install vsftpd
apt install vsftpd
# Configure
# /etc/vsftpd.conf
listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
dirmessage_enable=YES
xferlog_enable=YES
connect_from_port_20=YES
# Enable SSL
ssl_enable=YES
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
# Chroot users
chroot_local_user=YES
allow_writeable_chroot=YES
# User list
userlist_enable=YES
userlist_file=/etc/vsftpd.userlist
userlist_deny=NO
# Start service
systemctl start vsftpd
systemctl enable vsftpd

Interview talking point: “chroot_local_user jails users inside their home directory, and allow_writeable_chroot is set because vsftpd refuses to start when the chroot root itself is writable.”

Q272: How do you configure Samba as domain controller?

Section titled “Q272: How do you configure Samba as domain controller?”

What it is: Samba can serve as an Active Directory domain controller. samba-tool domain provision creates the realm and domain with an admin password and server role, then the samba service runs it.

Why it is used: To provide AD-style domains, logins, and policy for Windows clients without Microsoft server software.

Terminal window
# Install
apt install samba krb5-user
# Provision
samba-tool domain provision --realm=EXAMPLE.COM --domain=EXAMPLE --adminpass=Password123 --server-role=dc
# Start
systemctl start samba
# Add user
useradd -M -s /sbin/nologin administrator
smbpasswd -a administrator
# Join domain
net ads join -U administrator

Interview talking point: “Provisioning sets realm EXAMPLE.COM, after which member machines run net ads join -U administrator to join. The local account is created with useradd -M -s /sbin/nologin and then smbpasswd -a gives that account a Samba password.”

What it is: Samba shares directories to Windows clients over SMB. The global section sets workgroup, user-level security, and guest mapping, while the shared share serves /srv/samba/shared, is browsable and writable, refuses guests, and admits only smbgroup members.

Why it is used: To share folders with Windows machines using the native SMB protocol instead of NFS.

/etc/samba/smb.conf
[global]
workgroup = WORKGROUP
security = user
map to guest = Bad User
[shared]
path = /srv/samba/shared
browsable = yes
writable = yes
guest ok = no
valid users = @smbgroup

Interview talking point: “security user means each connection maps to a local account, and valid users at sign limits the share to smbgroup, so membership in that group is what actually grants access.”

What it is: vsftpd is an FTP server. vsftpd.conf turns on local user login and uploads while disabling anonymous access, enables transfer logging and SSL with a certificate, and the example adds an ftpuser with nologin as its shell.

Why it is used: To provide file upload and download to users, or to legacy applications that speak FTP.

/etc/vsftpd.conf
# Install
apt install vsftpd
listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=YES
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
secure_chroot_dir=/var/run/vsftpd/empty
# Enable SSL
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_enable=YES
# Create user
useradd -m -s /usr/sbin/nologin ftpuser
passwd ftpuser
systemctl restart vsftpd

Interview talking point: “anonymous_enable=NO is the first setting to check on a public host, and giving the account /usr/sbin/nologin keeps the FTP user from also getting an interactive shell.”


What it is: Squid is a caching and access-control proxy: squid.conf sets the listening port, a cache directory, ACL lines allowing localnet and denying others, refresh_pattern rules controlling cache lifetime, and squid -k parse validates the config.

Why it is used: To cut outbound bandwidth and latency by serving repeated objects from local cache.

/etc/squid/squid.conf
# Install Squid
apt install squid
# Basic config
http_port 3128
cache_dir ufs /var/spool/squid 1000 16 256
# Access control
acl localnet src 192.168.0.0/16
http_access allow localnet
http_access deny all
# Cache rules
refresh_pattern -i \.jpg$ 10080 90% 43200
refresh_pattern -i \.html$ 1440 90% 3600
refresh_pattern -i \.css$ 10080 90% 43200
refresh_pattern -i \.js$ 10080 90% 43200
# Transparent proxy
http_port 3128 transparent
# Test
squid -k parse
systemctl restart squid

Interview talking point: “http_access is evaluated in order and the final deny all makes policy explicit, and squid -k parse should run before a restart because a broken config stops the proxy.”

Q276: How do you configure caching server?

Section titled “Q276: How do you configure caching server?”

What it is: Varnish is an HTTP caching server configured in VCL: the backend block defines the origin plus a health probe, vcl_recv passes admin and POST requests through uncached, vcl_backend_response sets a 24h TTL for static files, and varnishstat and varnishlog observe it.

Why it is used: To serve high traffic from cache in front of a slower application.

/etc/varnish/default.vcl
# Install Varnish
apt install varnish
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = "8080";
.probe = {
.url = "/health";
.timeout = 5s;
.interval = 10s;
}
}
sub vcl_recv {
# Don't cache admin pages
if (req.url ~ "^/admin") {
return (pass);
}
# Don't cache POST requests
if (req.method == "POST") {
return (pass);
}
}
sub vcl_backend_response {
# Cache static files
if (bereq.url ~ "\.(jpg|jpeg|png|gif|ico|css|js)$") {
set beresp.ttl = 24h;
}
}
# Commands
varnishd -F -f /etc/varnish/default.vcl
varnishstat
varnishlog

Interview talking point: “return pass on POST and admin URLs is the safeguard against caching dynamic or privileged responses, and the backend probe lets Varnish mark a dead origin and avoid it.”

What it is: Squid is a caching HTTP proxy listening on port 3128. squid.conf defines an ACL for the local network, allows it and denies the rest, sets a cache directory and object size, and can require basic proxy authentication.

Why it is used: To share outbound web traffic, cache repeat downloads, and control or log which clients reach the internet.

/etc/squid/squid.conf
# Install
apt install squid
http_port 3128
acl localnet src 192.168.1.0/24
http_access allow localnet
http_access deny all
# Cache configuration
cache_dir ufs /var/spool/squid 10000 16 256
maximum_object_size 4096 MB
# Authentication
auth_param basic program /usr/lib/squid/ncsa_auth /etc/squid/passwd
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Reload
systemctl reload squid

Interview talking point: “ACLs are evaluated in order and the explicit http_access deny all after allow localnet means anything not matching is refused, and systemctl reload squid applies config changes without dropping active connections.”

What it is: Squid is a caching HTTP proxy listening on port 3128. It defines an ACL for the local source network, allows it and denies all others, sets a disk cache directory and object size limit, and can require basic authentication.

Why it is used: To share and govern outbound web access while caching repeated downloads to save bandwidth.

/etc/squid/squid.conf
http_port 3128
acl localnet src 192.168.1.0/24
http_access allow localnet
http_access deny all
cache_dir ufs /var/spool/squid 10000 16 256
maximum_object_size 4096 MB
# Authentication
auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwd
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Interview talking point: “http_access rules are evaluated in order, so allow localnet must appear before deny all, otherwise the broader deny would win and the local network would be blocked.”

What it is: Logical database backups use mysqldump for MySQL and pg_dump or pg_dumpall for PostgreSQL, optionally piped through gzip. A cron.d entry schedules the dump nightly with a date-stamped filename.

Why it is used: To protect data against corruption or accidental deletion with point-in-time SQL exports.

Terminal window
# MySQL
mysqldump -u root -p --all-databases > all_databases.sql
mysqldump -u root -p mydb | gzip > mydb.sql.gz
# PostgreSQL
pg_dumpall -U postgres > all.sql
pg_dump -U myuser mydb | gzip > mydb.sql.gz
# Automate
# /etc/cron.d/backup
0 2 * * * root mysqldump -u root -psecret mydb | gzip > /backup/mydb-$(date +\%Y\%m\%d).sql.gz

Interview talking point: “Piping dumps through gzip compresses on the fly so no intermediate file exists, and in a cron.d file percent signs must be escaped or cron treats them as line breaks. Naming files with the date builds a retention history for restores.”

What it is: Database backup script: mysqldump with single-transaction, routines, and triggers piped to gzip, pg_dump in custom format, retention by deleting files older than seven days, and verification by decompressing and reading the first lines.

Why it is used: To take consistent, restorable snapshots of MySQL and PostgreSQL data.

backup-mysql.sh
#!/bin/bash
DB_NAME="mydb"
DB_USER="backup"
DB_PASS="password"
BACKUP_DIR="/backup/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
# MySQL backup
mysqldump -u$DB_USER -p$DB_PASS --single-transaction --routines --triggers $DB_NAME | gzip > $BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz
# PostgreSQL backup
pg_dump -U $DB_USER -F c -b -v -f $BACKUP_DIR/${DB_NAME}_${DATE}.dump $DB_NAME
# Retention
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
find $BACKUP_DIR -name "*.dump" -mtime +7 -delete
# Verify
zcat $BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz | head -5
# Restore
# mysql -u$DB_USER -p$DB_PASS $DB_NAME < backup.sql
# pg_restore -U $DB_USER -d $DB_NAME backup.dump

Interview talking point: “—single-transaction gives an InnoDB consistent snapshot without locking tables, and zcat piping to head verifies the dump is readable before the retention window deletes the original.”

Q281: How do you handle database migrations?

Section titled “Q281: How do you handle database migrations?”

What it is: Schema changes without downtime: add a nullable column, dual-write, backfill, then enforce constraints and drop the old column. CREATE INDEX CONCURRENTLY and pt-online-schema-change avoid long locks.

Why it is used: To change table structure while the application keeps reading and writing.

Terminal window
# Zero-downtime migrations
# 1. Add new column (nullable)
ALTER TABLE users ADD COLUMN new_field VARCHAR(255);
# 2. Write to both columns
# Application code change
# 3. Backfill data
UPDATE users SET new_field = old_field;
# 4. Make new column NOT NULL
ALTER TABLE users MODIFY COLUMN new_field VARCHAR(255) NOT NULL;
# 5. Remove old column
ALTER TABLE users DROP COLUMN old_field;
# For PostgreSQL
# Use pg_online
# Create index concurrently
CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
# For MySQL
# Use pt-online-schema-change
pt-online-schema-change D=t,s=users --alter "ADD COLUMN new_field VARCHAR(255)" \
--execute
# Rollback plan
# Keep old column
# Dual write
# Test thoroughly

Interview talking point: “A plain CREATE INDEX locks writes for its duration, CONCURRENTLY builds without that lock. The backfill and dual-write order keeps the old column usable, which doubles as your rollback path.”

Q282: How do you configure database replication?

Section titled “Q282: How do you configure database replication?”

What it is: Replication gives the master server-id 1 with binary logging for mydb and the slave server-id 2 with a relay log; the slave points at the master with CHANGE MASTER and starts.

Why it is used: Read scaling and failover capacity for a database.

Terminal window
# Master config
[mysqld]
server-id = 1
log_bin = /var/log/mysql/mysql-bin
binlog_do_db = mydb
# Slave config
[mysqld]
server-id = 2
relay-log = /var/log/mysql/mysql-relay-bin
# On master
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY 'password';
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
# On slave
CHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=xxx;
START SLAVE;
SHOW SLAVE STATUS\G;

Interview talking point: “SHOW MASTER STATUS returns the log file and position that go into CHANGE MASTER TO, and SHOW SLAVE STATUS with the G option prints results vertically so wide status rows stay readable.”

What it is: MySQL NDB Cluster runs a management node, data nodes holding the storage engine, and SQL nodes fronting it, each identified by a node-id in my.cnf.

Why it is used: To run MySQL on replicated storage that survives losing a node.

Terminal window
# MySQL NDB Cluster
# Install
apt install mysql-cluster-community-server
# Management node config
# /etc/mysql/my.cnf
[ndb_mgmd]
node-id=1
hostname=192.168.1.10
datadir=/var/lib/mysql-cluster
# Data nodes
# /etc/mysql/my.cnf
[ndbd]
node-id=2
hostname=192.168.1.11
datadir=/var/lib/mysql-cluster
[ndbd]
node-id=3
hostname=192.168.1.12
datadir=/var/lib/mysql-cluster
# SQL node
# /etc/mysql/my.cnf
[mysqld]
node-id=4
# Start management node
ndb_mgmd -f /etc/mysql/config.ini
# Start data nodes
ndbd --initial
# Start SQL node
mysqld --ndbcluster
# Check status
ndb_mgm -e show

Interview talking point: “ndb_mgm -e show reports cluster status from the command line, and data nodes start with —initial, which reinitializes their data directory rather than resuming it.”

Q284: How do you configure MySQL group replication?

Section titled “Q284: How do you configure MySQL group replication?”

What it is: MySQL Group Replication uses GTID-based, row-format replication with a consensus group for distributed state.

Why it is used: Achieve high availability with automatic failover and conflict detection.

/etc/mysql/mysql.conf.d/mysqld.cnf
# MySQL 8.0 Group Replication
[mysqld]
server-id=1
gtid_mode=ON
enforce_gtid_consistency=ON
binlog_checksum=NONE
log_slave_updates=ON
relay_log=relay-bin
binlog_format=ROW
transaction_write_set_extraction=XXHASH64
# Group Replication plugin
plugin_load_add='group_replication.so'
group_replication_group_name="aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
group_replication_start_on_boot=OFF
group_replication_local_address="127.0.0.1:33061"
group_replication_group_seeds="127.0.0.1:33061,127.0.0.1:33062,127.0.0.1:33063"
group_replication_bootstrap_group=ON
# Start group replication
SET GLOBAL group_replication_group_name = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
START GROUP_REPLICATION;

Interview talking point: “All nodes share group identity and seeds; bootstrapping initializes the first node to form the replication group.”

Q285: How do you configure MySQL replication?

Section titled “Q285: How do you configure MySQL replication?”

What it is: MySQL replication uses a binary log on the master and a relay log on the slave. After granting a replication user and locking tables, SHOW MASTER STATUS gives the position the slave connects with.

Why it is used: To keep a standby copy of data for read load, failover, or durability.

# Master
[mysqld]
server-id = 1
log_bin = /var/log/mysql/mysql-bin
binlog_do_db = mydb
# Slave
[mysqld]
server-id = 2
relay-log = /var/log/mysql/mysql-relay-bin
# Commands
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY 'password';
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;
CHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=xxx;
START SLAVE;

Interview talking point: “FLUSH TABLES WITH READ LOCK freezes writes so SHOW MASTER STATUS captures a consistent file and position, and those exact values go into CHANGE MASTER TO. Distinct server-id values are mandatory or the replication link will not come up.”

What it is: MHA, MySQL Master High Availability, handles automatic master failover for a replication setup. Its config sets manager work and log directories and marks server1 as a candidate master with server2 as a peer.

Why it is used: To promote a new MySQL master quickly with minimal lost transactions when the primary fails.

Terminal window
# MHA
# Install
apt install mha4mysql-node mha4mysql-manager
# Configure
# /etc/app1.cnf
[server default]
manager_workdir=/var/log/masterha/app1
manager_log=/var/log/masterha/app1.log
remote_workdir=/var/log/masterha
[server1]
hostname=192.168.1.10
candidate_master=1
[server2]
hostname=192.168.1.11

Interview talking point: “candidate_master marks which replicas are eligible for promotion, so MHA narrows the failover choice in advance instead of picking a target blindly at failure time.”

What it is: MySQL or MariaDB installs as mysql-server or mariadb-server, then a database, a user scoped to a host, and privileges are created and flushed.

Why it is used: To stand up a database, grant least-privilege access to an application, and take backups.

Terminal window
# Install
apt install mysql-server
# or
yum install mariadb-server
# Secure installation
mysql_secure_installation
# Create database and user
mysql -u root -p
CREATE DATABASE myapp;
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON myapp.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
# Configuration
# /etc/mysql/mariadb.conf.d/50-server.cnf
# key_buffer_size = 256M
# max_connections = 200
# Backup
mysqldump -u root -p myapp > backup.sql
mysql -u root -p myapp < backup.sql

Interview talking point: “The user is created for localhost only, so an application connecting from another host needs its own account. mysqldump redirecting into backup.sql produces a plain SQL file that the mysql client replays on restore.”

Q288: How do you configure PostgreSQL high availability?

Section titled “Q288: How do you configure PostgreSQL high availability?”

What it is: PostgreSQL high availability uses streaming replication from a primary to a standby built with pg_basebackup, plus pgBouncer to pool client connections.

Why it is used: To keep a read replica ready for failover and to cap connection churn.

/etc/postgresql/14/main/postgresql.conf
# Streaming replication
wal_level = replica
max_wal_senders = 3
wal_keep_size = 1GB
hot_standby = on
# Master: /etc/postgresql/14/main/pg_hba.conf
host replication replicator 192.168.1.0/24 md5
# Create replication user
psql -c "CREATE USER replicator REPLICATION LOGIN PASSWORD 'secret';"
# Backup on replica
pg_basebackup -h master -D /var/lib/postgresql/14/main -U replicator -P -Xs
# Replica: /etc/postgresql/14/main/postgresql.conf
hot_standby = on
# Replica: /etc/postgresql/14/main/recovery.conf
standby_mode = on
primary_conninfo = 'host=master port=5432 user=replicator password=secret'
trigger_file = /tmp/promote
# pgBouncer for connection pooling
# /etc/pgbouncer/pgbouncer.ini
[databases]
mydb = host=127.0.0.1 port=5432 dbname=mydb
[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20

Interview talking point: “pool_mode = transaction hands out a backend only for the duration of one transaction, so max_client_conn can far exceed default_pool_size without exhausting PostgreSQL.”

Q289: How do you configure PostgreSQL replication?

Section titled “Q289: How do you configure PostgreSQL replication?”

What it is: Streaming replication needs wal_level = replica plus sender and slot limits on the primary, and hot_standby with primary_conninfo on the replica. pg_basebackup takes the initial physical copy with -R for standby config.

Why it is used: To build and maintain a hot standby for read scaling or failover.

# Master
wal_level = replica
max_wal_senders = 3
max_replication_slots = 3
# Slave
hot_standby = on
primary_conninfo = 'host=master_ip port=5432 user=repl password=password'
# Commands
pg_basebackup -h master_ip -D /var/lib/postgresql/14/main -P -Xs -R

Interview talking point: “The -R flag in pg_basebackup writes the standby configuration and connection string into the data directory so the copy boots straight into standby mode, while -Xs ships the WAL needed for a consistent copy. hot_standby = on allows read queries on the replica.”

Q290: How do you configure PostgreSQL replication?

Section titled “Q290: How do you configure PostgreSQL replication?”

What it is: PostgreSQL streaming replication copies WAL from a master to a standby server using a replication user.

Why it is used: Provide a hot standby for failover and offload read queries from the primary.

/etc/postgresql/14/main/postgresql.conf
# Master configuration
wal_level = replica
max_wal_senders = 3
max_replication_slots = 3
wal_keep_size = 1GB
# /etc/postgresql/14/main/pg_hba.conf
host replication replicator 192.168.1.0/24 md5
# Create replication user
psql -U postgres
CREATE USER replicator REPLICATION LOGIN PASSWORD 'password';
# Backup for replica
pg_basebackup -h master -D /var/lib/postgresql/14/main -U replicator -P -X stream
# Replica configuration
# /etc/postgresql/14/main/postgresql.conf
hot_standby = on
# Create recovery.conf
# /etc/postgresql/14/main/recovery.conf
standby_mode = 'on'
primary_conninfo = 'host=master port=5432 user=replicator password=password'

Interview talking point: “wal_level must be set to replica on the master, and the standby connects via primary_conninfo in recovery configuration.”

What it is: PostgreSQL installs from the distribution packages and is first reached by switching to the postgres account to run psql, whose meta-commands list databases, tables, and roles.

Why it is used: Creating databases and roles, and taking logical backups.

Terminal window
# Install
apt install postgresql
# Connect
sudo -u postgres psql
# Commands
\list # list databases
\dt # list tables
\du # list users
# Create database
CREATE DATABASE mydb;
CREATE USER myuser WITH PASSWORD 'secret';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
# Backup
pg_dump -U user dbname > backup.sql
# Restore
psql -U user dbname < backup.sql

Interview talking point: “sudo -u postgres psql is the standard way in before creating roles, pg_dump dbname > backup.sql exports the data, and psql dbname < backup.sql restores it.”

What it is: PostgreSQL installs as postgresql, needs an explicit initdb step, then users and databases are created through psql as the postgres account with privileges granted.

Why it is used: To initialize a cluster, create least-privilege roles, and back up a database.

Terminal window
# Install
apt install postgresql
# or
yum install postgresql-server
# Initialize
postgresql-setup --initdb
# or
pg_ctl -D /var/lib/pgsql/data initdb
# Create user and database
sudo -u postgres createuser myuser
sudo -u postgres createdb mydb
sudo -u postgres psql
ALTER USER myuser WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
# Configuration
# /var/lib/pgsql/data/postgresql.conf
# max_connections = 100
# shared_buffers = 128MB
# Backup
pg_dump -U myuser mydb > backup.sql

Interview talking point: “Unlike MySQL, PostgreSQL must be initialized with postgresql-setup —initdb or pg_ctl initdb before it will start, and admin commands run as the postgres OS user through sudo -u postgres.”

What it is: Redis Cluster distributes data across multiple nodes with replica nodes for high availability.

Why it is used: Scale read and write capacity while providing automatic failover.

Terminal window
# Create cluster
redis-cli --cluster create 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 \
127.0.0.1:7004 127.0.0.1:7005 127.0.0.1:7006 \
--cluster-replicas 1
# Check cluster
redis-cli -c -p 7001 cluster nodes
redis-cli -c -p 7001 cluster info
# Connect to cluster
redis-cli -c -p 7001
# Operations
CLUSTER INFO
CLUSTER SLOTS
CLUSTER NODES
# Failover
# Master election
redis-cli -p 7001 cluster failover
# Reshard
redis-cli --cluster reshard 127.0.0.1:7001

Interview talking point: “Data is split into hash slots across masters; cluster mode requires the -c flag to route requests to the correct node.”

Q294: How do you configure Redis Sentinel?

Section titled “Q294: How do you configure Redis Sentinel?”

What it is: Redis Sentinel monitors a named master, declares it down after a timeout, and promotes a replica automatically. Clients ask Sentinel for the current master address.

Why it is used: To get automatic failover for Redis without performing a manual switch.

/etc/redis/sentinel.conf
# Sentinel configuration
port 26379
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 180000
sentinel parallel-syncs mymaster 1
# Start sentinel
redis-sentinel /etc/redis/sentinel.conf
# Client connection
# Python example
from redis.sentinel import Sentinel
sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
master = sentinel.master_for('mymaster', socket_timeout=0.1)
slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
# Commands
redis-cli -p 26379 INFO SENTINEL
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
# Failover
# Sentinel automatically promotes replica to master
# Old master becomes replica when back online

Interview talking point: “The quorum value of 2 means two sentinel instances must agree the master is down, and a majority of sentinels must then elect the one running failover.”

What it is: Redis is an in-memory store configured in redis.conf with a bind address, port, maxmemory, an eviction policy, and appendonly persistence, all driven via redis-cli.

Why it is used: To cache data with bounded memory and durable persistence while avoiding an unbounded heap.

Terminal window
# Install
apt install redis-server
# or
yum install redis
# Configuration
# /etc/redis/redis.conf
bind 127.0.0.1
port 6379
maxmemory 256mb
maxmemory-policy allkeys-lru
appendonly yes
# Commands
redis-cli PING
redis-cli SET mykey "value"
redis-cli GET mykey
redis-cli KEYS "*"
# Cluster mode
redis-cli --cluster create 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 --cluster-replicas 1

Interview talking point: “maxmemory 256mb with allkeys-lru means Redis evicts least-recently-used keys of any kind once full, so data loss is by design at the limit, while appendonly yes records writes for restart recovery.”

Q296: How do you implement database sharding?

Section titled “Q296: How do you implement database sharding?”

What it is: Database sharding picks a shard key, routes queries in the application, plans rebalancing, minimizes cross-shard queries, and monitors performance.

Why it is used: To scale a database past a single node by splitting data across them.

Terminal window
# Database sharding
# 1. Key strategy
# Choose shard key
# 2. Routing
# Application
# 3. Rebalancing
# Plan
# 4. Cross-shard
# Minimize
# 5. Monitoring
# Performance

Interview talking point: “Shard key choice drives everything downstream, because a poor key forces cross-shard queries and painful rebalancing later when data distribution turns out uneven.”

Q297: How do you implement database sharding?

Section titled “Q297: How do you implement database sharding?”

What it is: Database sharding splits data across multiple instances based on a shard key.

Why it is used: It scales horizontally when a single database can no longer handle load or storage.

Terminal window
# Key strategy
# Choose shard key
# Routing
# Application
# Rebalancing
# Plan
# Cross-shard
# Minimize
# Monitoring
# Performance

Interview talking point: “Choosing the right shard key is critical — poor choices lead to hotspots and make cross-shard operations complex.”

What it is: MariaDB is installed and hardened with mysql_secure_installation, then accessed with mysql -u root -p for SQL such as CREATE DATABASE; mysqldump writes a backup and mysql reads one back.

Why it is used: Operating the database day to day and taking portable backups.

Terminal window
# Install
apt install mariadb-server
# Secure installation
mysql_secure_installation
# Connect
mysql -u root -p
# Common commands
SHOW DATABASES;
CREATE DATABASE dbname;
USE dbname;
SHOW TABLES;
DESCRIBE tablename;
# Backup
mysqldump -u root -p dbname > backup.sql
# Restore
mysql -u root -p dbname < backup.sql

Interview talking point: “mysqldump dbname > backup.sql creates the dump and mysql dbname < backup.sql restores it, so backup and recovery share the same pipeline of shell redirection.”

What it is: MySQL basics: mysql_secure_installation hardens the install, the mysql client connects to a server, and SQL statements create databases, users, and grants. mysqldump exports a database as SQL for later import.

Why it is used: To provision application databases, grant least-privilege access, and back up or restore data.

Terminal window
# Install
apt install mysql-server
# Secure
mysql_secure_installation
# Connect
mysql -u root -p
# Create database
CREATE DATABASE mydb;
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
# Backup
mysqldump -u root -p mydb > backup.sql
# Restore
mysql -u root -p mydb < backup.sql

Interview talking point: “mysqldump writes to stdout so its output is redirected into a file, while restore feeds a file back into the mysql client. GRANT is scoped to mydb.* and a host, so the same username can exist for different hosts with different rights.”

What it is: PostgreSQL is managed with the psql client, typically run as the postgres system user via sudo -u. SQL creates roles and databases, pg_dump exports one database, and psql imports a dump file.

Why it is used: To provision databases and users, and to take and restore logical backups.

Terminal window
# Install
apt install postgresql
# Connect
sudo -u postgres psql
# Create user/database
CREATE USER myuser WITH PASSWORD 'password';
CREATE DATABASE mydb OWNER myuser;
# Backup
pg_dump -U myuser mydb > backup.sql
# Restore
psql -U myuser mydb < backup.sql
# Roles
ALTER USER myuser WITH SUPERUSER;

Interview talking point: “Connections use sudo -u postgres psql because the postgres OS user is trusted by default, unlike MySQL root login. The database is created with an OWNER so myuser owns it, and pg_dump -U selects the role used for the dump.”

What it is: MongoDB is a document database accessed through the mongosh shell. A database is selected with use, and collections support insertOne, find with query operators, updateOne with update operators, and deleteOne.

Why it is used: To store semi-structured documents and query them without a fixed schema.

Terminal window
# Install
apt install mongodb
# Connect
mongosh
# Commands
use mydb
db.users.insertOne({name: "John", age: 30})
db.users.find()
db.users.find({age: {$gt: 25}})
db.users.updateOne({name: "John"}, {$set: {age: 31}})
db.users.deleteOne({name: "John"})

Interview talking point: “find with a query document such as an age greater than 25 shows MongoDB operators rather than SQL syntax, and updateOne pairs a filter with $set so only matching fields change. Data is organized as database, then collection, then document.”

What it is: Redis Sentinel monitors a Redis master and performs failover. It names the master and a quorum of 2, sets failure detection after 5000 ms, a failover timeout, and parallel syncs, then runs as its own process.

Why it is used: To detect Redis master failure and elect a replacement automatically without operator action.

# sentinel.conf
sentinel monitor mymaster 192.168.1.10 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 180000
sentinel parallel-syncs mymaster 1
# Start
redis-sentinel /etc/redis/sentinel.conf
# Client
JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels);

Interview talking point: “The quorum of 2 requires at least two sentinels to agree the master is down before failover begins, which stops one sentinel’s bad view triggering a false takeover.”

What it is: Redis is an in-memory key-value store. redis.conf binds it to localhost, caps memory at 2GB with an allkeys-lru eviction policy, disables saving, and redis-cli runs SET, GET, DEL, and KEYS.

Why it is used: For caching, sessions, and queues where sub-millisecond reads matter.

Terminal window
# Install
apt install redis-server
# Configure /etc/redis/redis.conf
bind 127.0.0.1
port 6379
maxmemory 2gb
maxmemory-policy allkeys-lru
save ""
# Commands
redis-cli
SET key value
GET key
DEL key
KEYS pattern

Interview talking point: “maxmemory-policy allkeys-lru means any key can be evicted to make room, which suits a cache but is dangerous for durable data. save "" disables persistence entirely, so this setup treats Redis as pure cache rather than a source of truth.”

Q304: How do you test database performance?

Section titled “Q304: How do you test database performance?”

What it is: Database performance testing combines query plans from EXPLAIN ANALYZE, benchmark tools like pgbench, mysqlslap, and sysbench, plus pt-query-digest for slow logs.

Why it is used: To find slow queries and measure throughput under realistic concurrency.

Terminal window
# PostgreSQL
# EXPLAIN ANALYZE
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';
# pgbench
pgbench -i -s 100 mydb
pgbench -c 10 -j 2 -t 1000 mydb
# MySQL
# EXPLAIN
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
# mysqlslap
mysqlslap --user=root --password --auto-generate-sql \
--concurrency=10 --iterations=5
# sysbench
sysbench /usr/share/sysbench/oltp_read_write.lua \
--mysql-host=localhost \
--mysql-db=test \
--threads=10 \
--time=60 \
run
# pt-query-digest
pt-query-digest slow-query.log

Interview talking point: “EXPLAIN ANALYZE actually runs the query and reports real timing, so the plan includes execution costs that plain EXPLAIN can only estimate.”

Q305: How do you tune database performance?

Section titled “Q305: How do you tune database performance?”

What it is: Database performance tuning adjusts memory, I/O, and planner settings based on workload characteristics.

Why it is used: Improve query throughput and reduce latency for PostgreSQL and MySQL databases.

Terminal window
# PostgreSQL tuning
# postgresql.conf
shared_buffers = 256MB
effective_cache_size = 768MB
maintenance_work_mem = 64MB
checkpoint_completion_target = 0.9
wal_buffers = 16MB
default_statistics_target = 100
random_page_cost = 1.1
effective_io_concurrency = 200
work_mem = 4MB
min_wal_size = 1GB
max_wal_size = 4GB
# MySQL tuning
# my.cnf
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
key_buffer_size = 256M
query_cache_size = 0
tmp_table_size = 64M
max_connections = 200
# Analyze queries
EXPLAIN ANALYZE SELECT * FROM table WHERE condition;
SHOW PROCESSLIST;

Interview talking point: “effective_cache_size informs the query planner about OS cache, while work_mem affects memory for sorts and joins.”

What it is: slapcat exports the database to LDIF while ldapsearch does the same over the protocol. Restoring stops slapd, clears the database, runs slapadd with the file, fixes ownership, and restarts the service.

Why it is used: To preserve directory contents and rebuild the database after corruption or host loss.

Terminal window
# Backup database
slapcat -n 1 > backup.ldif
# or using ldapsearch
ldapsearch -x -LLL -b "dc=example,dc=com" > backup.ldif
# Restore
# Stop slapd
systemctl stop slapd
# Remove database
rm -rf /var/backups/ldap/*
# Restore
slapadd -l backup.ldif
# Set permissions
chown -R openldap:openldap /var/lib/ldap/
# Start slapd
systemctl start slapd
# Automate backup
#!/bin/bash
DATE=$(date +%Y%m%d)
slapcat -n 1 > /backup/ldap-$DATE.ldif
gzip /backup/ldap-$DATE.ldif
find /backup -mtime +30 -delete

Interview talking point: “slapcat and slapadd operate on the database offline, so slapd must be stopped before restore, whereas ldapsearch exports through a running server and suits a live scheduled backup.”

Q307: How do you integrate Linux with LDAP?

Section titled “Q307: How do you integrate Linux with LDAP?”

What it is: A Linux LDAP client uses NSS to decide where user and group lookups come from and PAM for authentication. nsswitch.conf puts ldap after compat, and pam_mkhomedir creates home directories on first login.

Why it is used: To let one directory server provide logins and group membership across many machines.

Terminal window
# Install client
apt install libnss-ldap libpam-ldap ldap-utils
# Configure NSS
# /etc/nsswitch.conf
passwd: compat ldap
group: compat ldap
shadow: compat ldap
hosts: files dns ldap
networks: files ldap
# Configure PAM
# /etc/pam.d/common-session
session optional pam_mkhomedir.so skel=/etc/skel umask=077
# Configure LDAP client
# /etc/ldap.conf
base dc=example,dc=com
uri ldap://ldap.example.com
ldap_version 3
rootbinddn cn=admin,dc=example,dc=com
# Test
getent passwd john
id john

Interview talking point: “nsswitch order matters because sources listed before ldap are consulted first, and pam_mkhomedir is what makes a fresh LDAP user home directory appear on first login rather than needing manual creation.”

Q308: How do you integrate with Active Directory?

Section titled “Q308: How do you integrate with Active Directory?”

What it is: Joining a host to Active Directory with realmd, using adcli and sssd behind the scenes, then checking with realm list and id, and logging in as user@EXAMPLE.COM.

Why it is used: Centralizing Linux access in the same Windows domain that manages corporate accounts and passwords.

Terminal window
# Install
apt install realmd sssd adcli
# Join domain
realm join --user=admin example.com
# Check
realm list
id user@EXAMPLE.COM
# Login
login user@EXAMPLE.COM

Interview talking point: “realm join configures sssd for you, and the UPN form user@DOMAIN in id and login is what distinguishes a domain account from a local one.”

Q309: How do you configure LDAP replication?

Section titled “Q309: How do you configure LDAP replication?”

What it is: LDAP replication uses a syncprov overlay on the master and a syncrepl statement on the replica. The replica binds to the provider with refreshAndPersist and retries on a schedule, keeping its own copy current.

Why it is used: To keep a read-only replica available for queries and as a fallback if the master fails.

/etc/ldap/slapd.conf
# Master (provider) configuration
overlay syncprov
syncprov-checkpoint 100 10
syncprov-sessionlog 100
# Enable syncprov module
modulepath /usr/lib/ldap
moduleload syncprov
# Consumer (replica) configuration
# /etc/ldap/slapd.conf
syncrepl rid=123
provider=ldap://master.example.com:389
type=refreshAndPersist
searchbase="dc=example,dc=com"
bindmethod=simple
binddn="cn=admin,dc=example,dc=com"
credentials=secret
retry="60 +"
# Or use LDAP URL
syncrepl rid=123
provider=ldap://master.example.com:389
searchbase="dc=example,dc=com"
binddn="cn=syncuser,dc=example,dc=com"
credentials=password

Interview talking point: “refreshAndPersist means the replica holds a connection and receives changes as they happen instead of polling, and the retry parameter controls how long it keeps trying when the master is unreachable.”

What it is: slapd is an LDAP server and ldap-utils provides the clients. LDAP stores directory entries in a hierarchy, and ldapadd, ldapsearch, ldapmodify, and ldapdelete operate on entries using a bind DN and password.

Why it is used: To serve a shared directory of users and groups that applications query for lookup or authentication.

Terminal window
# Install
apt install slapd ldap-utils
# Configure
dpkg-reconfigure slapd
# Add entries
ldapadd -x -D "cn=admin,dc=example,dc=com" -W -f entries.ldif
# Search
ldapsearch -x -b "dc=example,dc=com" "(objectclass=*)"
# Modify
ldapmodify -x -D "cn=admin,dc=example,dc=com" -W -f modify.ldif
# Delete
ldapdelete -x -D "cn=admin,dc=example,dc=com" "uid=user,ou=people,dc=example,dc=com"

Interview talking point: “The commands share the -x simple bind with -D as the admin DN and -W for a password prompt, and searches take a base DN plus a filter such as objectclass. LDIF files feed ldapadd and ldapmodify.”

What it is: OpenLDAP slapd stores directory entries in a hierarchy of distinguished names. After dpkg-reconfigure, entries are added from LDIF files with ldapadd using the admin bind DN, and ldapsearch queries by filter or base.

Why it is used: To hold shared user and organizational data that many systems can query centrally.

Terminal window
# Install
apt install slapd ldap-utils
# Reconfigure
dpkg-reconfigure slapd
# Add entries
# add_user.ldif
dn: uid=john,ou=people,dc=example,dc=com
objectClass: inetOrgPerson
objectClass: posixAccount
uid: john
cn: John Doe
sn: Doe
givenName: John
uidNumber: 1000
gidNumber: 1000
homeDirectory: /home/john
mail: john@example.com
# Add entry
ldapadd -x -D "cn=admin,dc=example,dc=com" -W -f add_user.ldif
# Search
ldapsearch -x -b "dc=example,dc=com" "(uid=john)"
ldapsearch -x -H ldap://localhost -D "cn=admin,dc=example,dc=com" -W

Interview talking point: “ldapadd needs the full DN of the admin bind, and the entries must list objectClass values that permit each attribute, otherwise the add fails with a constraint violation.”

What it is: Installing libnss-ldap and libpam-ldap, pointing passwd, group, and shadow at compat ldap in /etc/nsswitch.conf, and adding pam_mkhomedir in common-session so home directories appear on first login.

Why it is used: Resolve accounts from a directory server so one identity works across many Linux hosts.

Terminal window
# Install
apt install libnss-ldap libpam-ldap
# Configure
# /etc/nsswitch.conf
passwd: compat ldap
group: compat ldap
shadow: compat ldap
# PAM
# /etc/pam.d/common-session
session optional pam_mkhomedir.so skel=/etc/skel umask=077

Interview talking point: “nsswitch.conf decides where names are looked up and its order matters, while the pam_mkhomedir line is what creates the home directory the first time a directory user logs in.”

What it is: syncrepl in slapd.conf configures replication, with a replica id, provider URL, simple bind DN and credentials, search base, and type refreshAndPersist so the consumer stays continuously in sync.

Why it is used: Keep a second LDAP server current so directory services survive a master failure.

/etc/ldap/slapd.conf
# Master config
serverID 1
syncrepl rid=001
provider=ldap://ldap2.example.com
bindmethod=simple
binddn="cn=admin,dc=example,dc=com"
credentials=secret
searchbase="dc=example,dc=com"
type=refreshAndPersist

Interview talking point: “refreshAndPersist means the consumer holds a persistent connection and receives updates as they happen rather than refreshing on an interval, so it depends on the provider being reachable.”


What it is: sshd_config hardening disables root login and password authentication, rejects empty passwords, caps MaxAuthTries, adds a keepalive interval, and disables X11 and TCP forwarding. Keys come from ssh-keygen.

Why it is used: To reduce the attack surface of an internet-facing SSH service.

/etc/ssh/sshd_config
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
MaxAuthTries 3
ClientAliveInterval 300
X11Forwarding no
AllowTcpForwarding no
ForceCommand none
# Restart
systemctl restart sshd
# Generate keys
ssh-keygen -t ed25519 -C "admin@host"

Interview talking point: “PasswordAuthentication no means only key holders get in, and ClientAliveInterval 300 drops idle sessions, but none of this applies until sshd is restarted.”

What it is: SSH hardening edits sshd_config to disable root and password logins, cap authentication attempts, and allow key-based access for named users, backed by fail2ban.

Why it is used: To stop brute-force logins and limit which accounts can reach the server.

/etc/ssh/sshd_config
Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
AllowUsers user1 user2
# Generate key pair
ssh-keygen -t ed25519 -C "work laptop"
# Copy key
ssh-copy-id user@server
# Fail2ban
apt install fail2ban
# or
yum install fail2ban

Interview talking point: “PasswordAuthentication no only takes effect after the sshd service is reloaded, and ssh-copy-id is what actually installs the public key. ClientAliveInterval 300 drops idle sessions so stale connections do not pile up.”

What it is: SSH hardening in sshd_config disables root login and password authentication, keeps key authentication, moves the port, limits MaxAuthTries, sets ClientAliveInterval, then restarts sshd.

Why it is used: Cutting brute-force and credential-stuffing exposure on reachable servers.

Terminal window
# Edit /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
Port 2222
MaxAuthTries 3
ClientAliveInterval 300
# Restart
systemctl restart sshd

Interview talking point: “PasswordAuthentication no with PubkeyAuthentication yes means keys are the only way in, and ClientAliveInterval 300 drops idle sessions; every sshd_config edit needs systemctl restart sshd to take effect.”

Q317: How do you configure network segmentation?

Section titled “Q317: How do you configure network segmentation?”

What it is: Segmentation uses VLANs added to an interface with vconfig add, firewalled tiers like DMZ and database, and Kubernetes NetworkPolicies applied through kubectl.

Why it is used: To isolate workloads and limit lateral movement if one tier or pod is compromised.

Terminal window
# VLANs
vconfig add eth0 100
vconfig add eth0 200
# Firewalls
# DMZ, internal, database tiers
# Kubernetes
# NetworkPolicies
kubectl apply -f network-policy.yaml

Interview talking point: “vconfig add eth0 100 and 200 splits one physical link into separate broadcast domains, while NetworkPolicies restrict pod to pod traffic inside the cluster.”

Q318: How do you implement API rate limiting?

Section titled “Q318: How do you implement API rate limiting?”

What it is: API rate limiting uses a token bucket or leaky bucket per user key, publishes rate limit headers, returns HTTP 429, and degrades gracefully through throttling.

Why it is used: To protect services from overload while allocating capacity fairly.

Terminal window
# API rate limiting
# 1. Token bucket
# Leaky bucket
# 2. Per-user
# By key
# 3. Headers
# Rate limit
# 4. Response
# 429
# 5. Throttling
# Graceful

Interview talking point: “The 429 response together with rate limit headers tells clients exactly when to retry, which is the difference between controlled throttling and clients hammering a struggling endpoint.”

Q319: How do you implement API rate limiting?

Section titled “Q319: How do you implement API rate limiting?”

What it is: API rate limiting controls request rates to protect services from overload or abuse.

Why it is used: It ensures fair usage and maintains service availability under high demand.

Terminal window
# Token bucket
# Leaky bucket
# Per-user
# By key
# Headers
# Rate limit
# Response
# 429
# Throttling
# Graceful

Interview talking point: “Algorithms like token bucket and leaky bucket allow controlled bursts while enforcing steady rate limits, returning 429 when exceeded.”

Q320: How do you implement network segmentation in K8s?

Section titled “Q320: How do you implement network segmentation in K8s?”

What it is: Network segmentation in Kubernetes is implemented using NetworkPolicy resources that define ingress and egress rules to control traffic between pods.

Why it is used: Default-deny network policies limit lateral movement by restricting which pods can communicate with each other in the cluster.

# Network policies
# Deny all by default
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress

Interview talking point: “A default-deny policy with explicit allow rules follows zero trust principles, ensuring pods only receive traffic from explicitly permitted sources.”

Q321: How do you implement network segmentation?

Section titled “Q321: How do you implement network segmentation?”

What it is: Network segmentation across layers: VLANs 100 and 200 added to eth0 for DMZ and internal traffic, tiered firewalls, and a labeled Kubernetes production namespace.

Why it is used: Isolates zones so a breach in one segment cannot reach another.

Terminal window
# VLANs
vconfig add eth0 100 # DMZ
vconfig add eth0 200 # Internal
# Firewalls
# Perimeter
# Application
# Database
# Kubernetes namespaces
kubectl create namespace production
kubectl label namespace production env=production

Interview talking point: “Segmentation happens at two levels here, VLANs for the physical network and namespaces for workloads, but both only help when firewall or policy rules enforce the boundaries.”

Q322: How do you implement network segmentation?

Section titled “Q322: How do you implement network segmentation?”

What it is: Network segmentation techniques: VLAN subinterfaces via ip link, iptables chains acting as zones, network namespaces created with ip netns for isolation, cgroups limiting CPU and memory, and AppArmor or SELinux for mandatory access control.

Why it is used: To contain blast radius by separating workloads and trust levels.

Terminal window
# VLAN isolation
ip link add link eth0 name eth0.100 type vlan id 100
ip addr add 192.168.100.1/24 dev eth0.100
# iptables zones
iptables -N DMZ
iptables -A DMZ -j DROP
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
# Network namespaces for isolation
ip netns add isolated
ip netns exec isolated ip link set lo up
# Cgroups for process isolation
# /etc/cgconfig.conf
group web {
cpu {
cpu.shares=512;
}
memory {
memory.limit_in_bytes=512M;
}
}
# AppArmor/SELinux
apparmor_parser -r /etc/apparmor.d/*

Interview talking point: “ip netns creates a fully separate network stack with its own interfaces and routes, which is stronger isolation than a VLAN tag on a shared host.”

Q323: How do you implement network segmentation?

Section titled “Q323: How do you implement network segmentation?”

What it is: Network segmentation using isolated network namespaces, VLAN interfaces, custom iptables zone chains, and bridges with forwarding blocked between zones.

Why it is used: To separate untrusted and trusted traffic so a compromise cannot cross freely.

Terminal window
# Create isolated network namespace
ip netns add isolated
ip netns exec isolated ip link set lo up
# Configure VLAN
ip link add link eth0 name eth0.100 type vlan id 100
ip addr add 192.168.100.1/24 dev eth0.100
ip link set eth0.100 up
# iptables zones
# DMZ
iptables -N DMZ-ZONE
iptables -A DMZ-ZONE -j DROP
# Internal
iptables -N INT-ZONE
iptables -A INT-ZONE -j ACCEPT
# Bridge isolation
ip link add name br0 type bridge
ip link set eth0 master br0
ip link set eth1 master br0
# Prevent forwarding
iptables -A FORWARD -i br0 -o br0 -j DROP
# AppArmor namespaces
apparmor_parser -r /etc/apparmor.d/*

Interview talking point: “Creating a VLAN sub-interface like eth0.100 puts traffic on a separate broadcast domain with its own subnet, while the FORWARD drop between bridge ports contains lateral movement.”

Q324: How do you implement network segmentation?

Section titled “Q324: How do you implement network segmentation?”

What it is: Segmentation splits a network into isolated zones using network namespaces, VLAN sub-interfaces, bridges, and named iptables chains dedicated to each zone.

Why it is used: To keep untrusted traffic like a DMZ away from internal systems and limit lateral movement.

Terminal window
# Create network namespaces
ip netns add dmz
ip netns add internal
# Configure VLANs
ip link add link eth0 name eth0.100 type vlan id 100
ip addr add 192.168.100.1/24 dev eth0.100
ip link set eth0.100 up
# Bridge isolation
ip link add name br-dmz type bridge
ip link set eth1 master br-dmz
ip link set eth2 master br-dmz
# iptables zone-based firewall
iptables -N DMZ-ZONE
iptables -N INTERNAL-ZONE
iptables -N EXTERNAL-ZONE
# DMZ rules
iptables -A DMZ-ZONE -p tcp --dport 80 -j ACCEPT
iptables -A DMZ-ZONE -p tcp --dport 443 -j ACCEPT
iptables -A DMZ-ZONE -j REJECT
# Internal rules
iptables -A INTERNAL-ZONE -j ACCEPT
iptables -A INTERNAL-ZONE -o eth0 -j MASQUERADE

Interview talking point: “Custom chains such as DMZ-ZONE keep zone rules organized, and the DMZ chain ends with REJECT while internal traffic gets MASQUERADE for outbound access.”

Q325: How do you implement network segmentation?

Section titled “Q325: How do you implement network segmentation?”

What it is: Network segmentation using VLANs for isolation, firewall zones, zero trust micro-segmentation, traffic monitoring, and compliance auditing.

Why it is used: Limits how far an attacker or a misbehaving workload can move laterally.

Terminal window
# Network segmentation
# 1. VLANs
# Isolation
# 2. Firewalls
# Zones
# 3. Zero trust
# Micro-segmentation
# 4. Monitoring
# Traffic
# 5. Compliance
# Audit

Interview talking point: “VLANs segment at layer 2 while firewall zones and micro-segmentation enforce policy at higher layers, so the outline combines both. Traffic monitoring then confirms the boundaries actually hold rather than just existing on paper.”

Q326: How do you implement network segmentation?

Section titled “Q326: How do you implement network segmentation?”

What it is: Network segmentation implementation uses VLANs for isolation, firewall zones, zero trust micro-segmentation, traffic monitoring, and compliance auditing.

Why it is used: To contain breaches and enforce least privilege across network boundaries.

Terminal window
# VLANs
# Isolation
# Firewalls
# Zones
# Zero trust
# Micro-segmentation
# Monitoring
# Traffic
# Compliance
# Audit

Interview talking point: “Micro-segmentation and zero trust limit lateral movement, while traffic monitoring and audits verify that boundaries remain effective.”

What it is: NGINX Ingress applies rate limits through annotations: limit-rps caps requests per second and limit-connections caps concurrent connections per client.

Why it is used: To protect backends from traffic spikes and abuse.

# NGINX Ingress rate limiting
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: myapp
annotations:
nginx.ingress.kubernetes.io/limit-rps: "100"
nginx.ingress.kubernetes.io/limit-connections: "50"
spec:
rules:
- host: myapp.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: myapp
port:
number: 80

Interview talking point: “limit-rps and limit-connections address different bottlenecks, request rate versus open connections, so a service can be throttled on either dimension without changing the Ingress rules themselves.”

What it is: Rate limiting at several layers: iptables recent-module counters, nginx limit_req zones with burst, HAProxy request-rate denials, and application-level limits.

Why it is used: To protect services from abuse, scraping, or overload while keeping legit users served.

Terminal window
# iptables rate limit
iptables -A INPUT -p tcp --dport 80 -m state --state NEW \
-m recent --set
iptables -A INPUT -p tcp --dport 80 -m state --state NEW \
-m recent --update --seconds 60 --hitcount 10 -j DROP
# Nginx rate limiting
# nginx.conf
http {
limit_req_zone $binary_remote_addr zone=limit:10m rate=10r/s;
server {
location / {
limit_req zone=limit burst=20 nodelay;
}
}
}
# HAProxy rate limiting
# haproxy.cfg
http-request deny deny_status 429 if { sc_http_req_rate(10) gt 10 }
# Application rate limiting
# Python example
from flask import Flask, request, jsonify
from flask_limiter import Limiter
app = Flask(__name__)
limiter = Limiter(app, key_func=get_remote_address)
@app.route("/api")
@limiter.limit("10 per minute")
def api():
return jsonify({"status": "ok"})

Interview talking point: “burst=20 nodelay lets a short burst through immediately while still enforcing the 10 requests per second average, so genuine spikes do not see spurious failures.”

What it is: Rate limiting caps how many requests a key, such as a client IP, may make inside a time window, shown here as an in-process timestamp list and a Redis counter with expiry.

Why it is used: To protect APIs from abuse, floods, and noisy neighbors while keeping service fair per client.

import time
from collections import defaultdict
class RateLimiter:
def __init__(self, max_requests, time_window):
self.max_requests = max_requests
self.time_window = time_window
self.requests = defaultdict(list)
def is_allowed(self, key):
now = time.time()
# Remove old requests
self.requests[key] = [
req_time for req_time in self.requests[key]
if now - req_time < self.time_window
]
if len(self.requests[key]) >= self.max_requests:
return False
self.requests[key].append(now)
return True
# Usage (Flask)
limiter = RateLimiter(100, 60)
@app.route('/api')
def api():
if not limiter.is_allowed(request.remote_addr):
return "Too many requests", 429
# Process request
return "OK"
# Redis-based (distributed)
import redis
class RedisRateLimiter:
def __init__(self, redis_client, max_requests, time_window):
self.redis = redis_client
self.max_requests = max_requests
self.time_window = time_window
def is_allowed(self, key):
current = self.redis.incr(key)
if current == 1:
self.redis.expire(key, self.time_window)
return current <= self.max_requests

Interview talking point: “The in-memory version keeps timestamps per key so the window slides, while the Redis version uses incr plus expire for one shared counter across instances. The Flask example answers 429 Too Many Requests.”

What it is: fail2ban watches logs and bans IPs that exceed a retry threshold. Jail settings define maxretry, bantime, and findtime, and fail2ban-client checks status, lifts bans, or shows ban timing.

Why it is used: To automatically block brute-force attackers, especially against SSH and web logins.

/etc/fail2ban/jail.local
# Install
apt install fail2ban
[sshd]
enabled = true
port = ssh
maxretry = 3
bantime = 3600
findtime = 600
[nginx-http-auth]
enabled = true
# Commands
fail2ban-client status
fail2ban-client set sshd unbanip 192.168.1.10
fail2ban-client get sshd ban Time
# Logs
tail -f /var/log/fail2ban.log

Interview talking point: “findtime is the window in which maxretry failures must occur and bantime is the ban duration in seconds, so maxretry 3 with findtime 600 means three failures within ten minutes.”

What it is: fail2ban monitors log files and bans IP addresses that match defined filter patterns through configured actions.

Why it is used: Automatically block brute force and abuse attempts against services.

Terminal window
# Install
apt install fail2ban
# Configure
# /etc/fail2ban/jail.local
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
destemail = admin@example.com
sender = fail2ban@example.com
action = %(action_mwl)s
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
# Custom filter
# /etc/fail2ban/filter.d/myapp.conf
[Definition]
failregex = <HOST> - .* "GET /admin
ignoreregex =
# Test
fail2ban-regex /var/log/nginx/error.log /etc/fail2ban/filter.d/nginx-http-auth
# Commands
fail2ban-client status
fail2ban-client set sshd unbanip 192.168.1.100

Interview talking point: “bantime, findtime, and maxretry define detection windows and ban duration; custom filters target application-specific attacks.”

What it is: fail2ban scans logs with regex filters and bans clients that exceed maxretry inside findtime, holding bans for bantime across jails like sshd and nginx.

Why it is used: To block brute-force SSH and web login attempts automatically without a firewall rule per attacker.

Terminal window
# Install fail2ban
apt install fail2ban
# Configure
# /etc/fail2ban/jail.local
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
[apache2]
enabled = true
port = http,https
# Custom filter
# /etc/fail2ban/filter.d/custom.conf
[Definition]
failregex = <HOST> - .* "GET /admin
# Start service
systemctl start fail2ban
# Check status
fail2ban-client status
fail2ban-client status sshd

Interview talking point: “findtime is the window in which maxretry failures must occur to trigger the bantime ban, and fail2ban-client status sshd shows live jail counts while fail2ban-client status lists all jails.”

What it is: fail2ban watches log files and bans repeat offenders; jail.local enables an sshd jail with maxretry 3 and bantime 3600, and fail2ban-client reports overall and per-jail status.

Why it is used: Automatically blocking brute-force SSH attacks without manual firewall edits.

Terminal window
# Install
apt install fail2ban
yum install fail2ban
# Configure
cat /etc/fail2ban/jail.local
[sshd]
enabled = true
port = ssh
maxretry = 3
bantime = 3600
# Check status
fail2ban-client status
fail2ban-client status sshd

Interview talking point: “maxretry 3 with bantime 3600 means three failures earn a one hour ban, and fail2ban-client status sshd lists which IPs that jail is currently banning.”

Q334: How do you implement DDoS protection?

Section titled “Q334: How do you implement DDoS protection?”

What it is: DDoS protection layers Nginx rate limiting at 100 requests per second per address, Fail2ban blocking repeat offenders, and cloud services such as AWS Shield or Cloudflare.

Why it is used: To absorb or shed malicious traffic before it overwhelms the origin servers.

Terminal window
# Rate limiting
# Nginx
limit_req_zone $binary_remote_addr zone=ddos:10m rate=100r/s;
# Fail2ban
# Block repeated offenders
# Cloud protection
# AWS Shield, Cloudflare, Akamai

Interview talking point: “Rate limiting and Fail2ban handle abusive clients at the host, but volumetric attacks need upstream scrubbing, which is why cloud protection sits alongside them.”

Q335: How do you implement DDoS protection?

Section titled “Q335: How do you implement DDoS protection?”

What it is: DDoS defense layers iptables rate limiting with the recent and hashlimit modules, kernel settings like syncookies, and web server request rate limits.

Why it is used: To keep a service answering during floods of new connections, ICMP, or HTTP requests.

Terminal window
# Rate limiting with iptables
# Limit connections per IP
iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW \
-m recent --set
iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW \
-m recent --update --seconds 60 --hitcount 20 -j DROP
# Limit ICMP
iptables -A INPUT -p icmp --icmp-type echo-request \
-m hashlimit --hashlimit-above 1/sec --hashlimit-burst 4 \
--hashlimit-htable-size 100000 --hashlimit-mode srcip \
--hashlimit-name icmp_limit -j DROP
# SYN flood protection
# /etc/sysctl.conf
net.ipv4.tcp_syncookies=1
net.ipv4.tcp_syn_retries=2
net.ipv4.tcp_max_syn_backlog=4096
# Application layer
# Nginx rate limiting
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
limit_req zone=general burst=20 nodelay;

Interview talking point: “Nginx limit_req_zone defines a rate per client address while the burst setting absorbs short spikes with nodelay, so brief bursts pass and sustained floods are throttled.”

Q336: How do you configure SELinux policies?

Section titled “Q336: How do you configure SELinux policies?”

What it is: An SELinux policy module declares allow rules in a .te file, compiled with checkmodule and loaded into the kernel policy with semodule -i.

Why it is used: To grant a confined domain the exact access it needs instead of disabling SELinux.

Terminal window
# Install policy tools
apt install policycoreutils-devel selinux-policy-dev
# Create module
# myapp.te
module myapp 1.0;
require {
type http_t;
type var_t;
class file { read write };
}
allow http_t var_t:file { read write };
# Compile
checkmodule -M -m -o myapp.mod myapp.te
# Install
semodule -i myapp.pp

Interview talking point: “The rule grants read and write from http_t to var_t for file objects, showing SELinux matches are written per object class rather than as broad permissions.”

What it is: SELinux is a mandatory access control system; getenforce and sestatus report its mode, setenforce switches enforcing and permissive now, and /etc/selinux/config sets the boot mode.

Why it is used: Confining processes so a compromised service cannot reach unrelated files.

Terminal window
# Check status
getenforce
sestatus
# Set mode
setenforce 0 # permissive
setenforce 1 # enforcing
# Persistently
# Edit /etc/selinux/config
SELINUX=enforcing
# Manage contexts
chcon -t httpd_sys_content_t /var/www/html
semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"

Interview talking point: “setenforce 0 puts SELinux in permissive, logging denials without blocking, which is ideal for diagnosis; chcon relabels one file temporarily while semanage fcontext -a writes a rule that survives a relabel.”

What it is: SELinux is mandatory access control that labels files, ports, and processes. getenforce and sestatus report mode, setenforce switches between permissive and enforcing at runtime, and chcon or semanage set context.

Why it is used: To confine services so a compromised process cannot touch unrelated resources.

Terminal window
# Status
getenforce
sestatus
# Set mode
setenforce 0 # permissive
setenforce 1 # enforcing
# Make persistent
# /etc/selinux/config
SELINUX=enforcing
# Context
chcon -t httpd_sys_content_t /var/www/html
semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
restorecon -Rv /web
# Boolean
setsebool -P httpd_can_network_connect 1
getsebool -a | grep httpd

Interview talking point: “setenforce 0 changes only the running mode while /etc/selinux/config makes it persistent, and semanage fcontext plus restorecon survives a relabel whereas a chcon change is lost after one.”

What it is: SELinux enforces mandatory access control through security contexts and booleans on top of Unix permissions, running in either enforcing or permissive mode.

Why it is used: To confine services so a compromised process cannot reach files it should not.

Terminal window
# Check SELinux status
getenforce
sestatus
# Set mode
setenforce 1 # Enforcing
setenforce 0 # Permissive
# Configure /etc/selinux/config
# SELINUX=enforcing
# SELINUXTYPE=targeted
# Manage contexts
chcon -t httpd_sys_content_t /var/www/html/index.html
semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
restorecon -Rv /web
# Boolean values
getsebool -a
setsebool -P httpd_can_network_connect on

Interview talking point: “setenforce 1 and 0 switch enforcing and permissive at runtime, but /etc/selinux/config decides the boot default. setsebool -P persists a boolean across reboots, while chcon changes a label that a later restorecon can overwrite.”

What it is: SELinux is a mandatory access control system checked with getenforce and sestatus, set between enforcing and permissive with setenforce, and tuned via contexts, booleans and modules.

Why it is used: To confine services so a compromised web server cannot touch unrelated files or sockets.

Terminal window
# Check status
getenforce
sestatus
# Set mode
setenforce 1 # Enforcing
setenforce 0 # Permissive
# Configure
# /etc/selinux/config
SELINUX=enforcing
SELINUXTYPE=targeted
# Manage contexts
chcon -t httpd_sys_content_t /var/www/html/index.html
# Make persistent
semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
restorecon -Rv /web
# Boolean values
getsebool -a
setsebool -P httpd_can_network_connect on
# Create module
# myapp.te
module myapp 1.0;
require { type httpd_t; }
allow httpd_t self:tcp_socket { accept listen };
# Compile and install
checkmodule -M -m -o myapp.mod myapp.te
semodule_package -o myapp.pp -m myapp.mod
semodule -i myapp.pp

Interview talking point: “chcon changes a file context temporarily and is lost on a relabel, while semanage fcontext plus restorecon makes the httpd_sys_content_t label permanent across restores.”

Q341: How do you implement SELinux policies?

Section titled “Q341: How do you implement SELinux policies?”

What it is: SELinux is mandatory access control where processes and files carry security contexts checked against policy. It is managed with context tools, booleans, and loadable policy modules.

Why it is used: To restrict what services can reach even when they run as root, and to satisfy compliance requirements.

Terminal window
# Check SELinux status
getenforce
sestatus
# SELinux contexts
# View file contexts
ls -Z /var/www/html
ls -Zd /var/www/html
# View process contexts
ps auxZ | grep nginx
# Change context
chcon -t httpd_sys_content_t /var/www/html/file.html
semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
restorecon -Rv /web
# Boolean values
getsebool -a
setsebool -P httpd_can_network_connect on
# Create custom policy module
# 1. Generate Type Enforcement file
# myapp.te
module myapp 1.0;
require {
type httpd_t;
type myapp_log_t;
class file { read write };
}
allow httpd_t myapp_log_t:file { read write };
# 2. Compile and install
checkmodule -M -m -o myapp.mod myapp.te
semodule_package -o myapp.pp -m myapp.mod
semodule -i myapp.pp

Interview talking point: “chcon changes a file context directly, while semanage fcontext plus restorecon writes the rule so the label survives a relabel, which is the durable approach.”

What it is: AppArmor restricts a program with a profile of allowed paths. aa-status reports profile status, aa-complain and aa-enforce select the profile mode, and the example profile grants read on /etc/myapp and read-write on /var/log/myapp.

Why it is used: To limit what files a service can touch so a compromised daemon cannot read or modify everything.

Terminal window
# Install
apt install apparmor apparmor-profiles
# Check status
aa-status
# Enable modes
aa-complain /usr/bin/nginx
aa-enforce /usr/bin/nginx
# Create profile
cat /etc/apparmor.d/usr.bin.myapp
#include <tunables/global>
/usr/bin/myapp {
# Allow read
/etc/myapp/** r,
# Allow write
/var/log/myapp/** rw,
}
# Reload
apparmor_parser -r /etc/apparmor.d/usr.bin.myapp

Interview talking point: “Profile rules are path-based and end in r or rw, and after editing a profile you run apparmor_parser -r to reload it rather than restarting the whole service.”

What it is: AppArmor confines programs with per-binary profiles allowing file and network access. aa-status shows loaded profiles, aa-complain and aa-enforce switch mode, and apparmor_parser reloads a profile.

Why it is used: To limit what a service can access even if it is exploited.

Terminal window
# Status
aa-status
aa-enabled
# Modes
aa-complain /usr/bin/nginx
aa-enforce /usr/bin/nginx
# Profile
cat /etc/apparmor.d/usr.bin.nginx
#include <tunables/global>
/usr/bin/nginx {
# Allow read
/etc/nginx/** r,
# Allow write
/var/log/nginx/** wa,
# Network
network inet stream,
}
# Reload
apparmor_parser -r /etc/apparmor.d/usr.bin.nginx

Interview talking point: “Complain mode logs violations without blocking, so it is used to build a profile, then aa-enforce makes those same rules deny access, and parser -r applies edits without a reboot.”

What it is: AppArmor confines programs with path-based profiles generated by aa-genprof and stored in /etc/apparmor.d, switchable between enforce and complain modes.

Why it is used: To limit what files and network a service can touch even if it is compromised.

Terminal window
# Install AppArmor
apt install apparmor apparmor-utils
# Check status
aa-status
# Create profile
aa-genprof /usr/bin/myapp
# Profile example
# /etc/apparmor.d/usr.bin.myapp
#include <tunables/global>
/usr/bin/myapp {
#include <abstractions/base>
/etc/myapp/** r,
/var/log/myapp/* rw,
network inet stream,
}
# Enforce mode
aa-enforce /usr/bin/myapp
# Complain mode (testing)
aa-complain /usr/bin/myapp
# Reload profile
apparmor_parser -r /etc/apparmor.d/usr.bin.myapp

Interview talking point: “complain mode only logs violations without blocking, so you test a new profile there first, then aa-enforce turns on denials and apparmor_parser -r reloads an edited profile.”

What it is: AppArmor is a mandatory access control system that restricts process access using per-application profiles.

Why it is used: Contain applications and limit potential damage from exploits or misconfigurations.

Terminal window
# Install
apt install apparmor apparmor-utils
# Status
aa-status
apparmor_status
# Disable/enable profiles
aa-disable /usr/sbin/named
aa-enable /usr/sbin/named
# Create profile
aa-genprof /usr/bin/myapp
# Edit profile
vim /etc/apparmor.d/usr.bin.myapp
# Example profile
#include <tunables/global>
/usr/bin/myapp {
#include <abstractions/base>
#include <abstractions/bash>
/etc/myapp/** r,
/var/log/myapp/* rw,
/run/myapp.sock rw,
# Deny
deny /etc/shadow r,
}
# Reload
apparmor_parser -r /etc/apparmor.d/usr.bin.myapp
# Change to enforce/complain mode
aa-complain /usr/bin/myapp
aa-enforce /usr/bin/myapp

Interview talking point: “Profiles run in enforce or complain mode; aa-genprof helps generate profiles by observing application behavior.”

Q346: How do you configure AppArmor profiles?

Section titled “Q346: How do you configure AppArmor profiles?”

What it is: AppArmor is mandatory access control that confines programs with path-based profiles listing allowed reads, writes, and network access. Profiles live in /etc/apparmor.d and load with apparmor_parser.

Why it is used: To limit a service to only the files and network it needs, reducing damage from compromise.

Terminal window
# Install AppArmor
apt install apparmor apparmor-utils
# View profiles
aa-status
ls /etc/apparmor.d/
# Create profile
aa-genprof /usr/bin/myapp
# Profile syntax
# /etc/apparmor.d/usr.bin.myapp
#include <tunables/global>
/usr/bin/myapp {
#include <abstractions/base>
#include <abstractions/bash>
# Allow read /etc
/etc/** r,
# Allow write to log
/var/log/myapp/* w,
# Deny access
deny /etc/shadow r,
deny /var/log/secure w,
# Network
network inet stream,
}
# Enable/disable
aa-disable /usr/bin/myapp
aa-enforce /usr/bin/myapp
aa-complain /usr/bin/myapp
# Reload
apparmor_parser -r /etc/apparmor.d/usr.bin.myapp

Interview talking point: “aa-complain logs violations without enforcing while aa-enforce blocks them, so you run a fresh profile in complain mode first to see real usage before tightening it.”

Q347: How do you create AppArmor profiles?

Section titled “Q347: How do you create AppArmor profiles?”

What it is: AppArmor profiles are generated for a binary with aa-genprof, then set to enforce or complain mode and inspected with aa-status.

Why it is used: To restrict a program’s file and network access, and to test rules before enforcing them.

Terminal window
# Generate profile
aa-genprof /usr/bin/myapp
# Enforce
aa-enforce /usr/bin/myapp
# Monitor in complain
aa-complain /usr/bin/myapp
# Check status
aa-status

Interview talking point: “aa-complain logs policy violations without blocking them, so you can shape a profile on a working system, then switch with aa-enforce to actually deny.”

Q348: How do you implement Linux capabilities?

Section titled “Q348: How do you implement Linux capabilities?”

What it is: Linux capabilities split the all-powerful root account into discrete privileges such as cap_net_raw. File capabilities attach a privilege to a binary, and a process current capabilities appear in its status file.

Why it is used: To grant a program one needed privilege without handing it full root, following least privilege.

Terminal window
# View capabilities
# File capabilities
getcap -r /usr/bin/
# Process capabilities
cat /proc/$$/status | grep Cap
# Set file capabilities
setcap 'cap_net_raw+ep' /usr/bin/ping
getcap /usr/bin/ping
# Remove capabilities
setcap -r /usr/bin/ping
# Run with specific capabilities
# Using run helper
# /etc/security/capability.conf
# none root
# cap_net_raw user1
# cap_net_admin user2
# Use setcap in code
# In C
#include <sys/capability.h>
cap_t caps;
caps = cap_get_proc();
cap_set_flag(caps, CAP_EFFECTIVE, CAP_NET_RAW, 1);
cap_set_proc(caps);

Interview talking point: “setcap gives a binary a single capability like cap_net_raw instead of making it setuid root, so ping can open raw sockets without being a fully privileged program.”

What it is: Capabilities split root privilege into units such as cap_net_raw. getcap lists a binary’s capabilities, setcap grants one like cap_net_raw+ep, and setcap -r removes it.

Why it is used: To give a program only the privilege it needs instead of running it fully as root.

Terminal window
# Check capabilities
getcap -r /usr/bin
# Add capability
setcap cap_net_raw+ep /usr/bin/ping
# Check specific
getcap /usr/bin/ping
# Remove
setcap -r /usr/bin/ping

Interview talking point: “The +ep suffix means effective and permitted, and getcap -r /usr/bin scans an entire tree rather than one file. The practical point is that ping runs with cap_net_raw instead of blanket root, so capabilities replace setuid root.”

What it is: Capabilities split root privileges into named units such as cap_net_raw; setcap grants one to a binary and getcap reads it back.

Why it is used: To let tools such as ping work without running them as full root.

Terminal window
# Check capabilities
getcap -r /usr/bin
# Add capability
setcap cap_net_raw+ep /usr/bin/ping
# Check
getcap /usr/bin/ping
# Remove
setcap -r /usr/bin/ping
# Check process
cat /proc/PID/status | grep Cap

Interview talking point: “Rather than sudo, ping holds cap_net_raw+ep on disk, and grep Cap in /proc/PID/status shows what a running process actually holds.”

What it is: Kerberos issues time-limited tickets after installing krb5-user, setting the default realm, KDC, and admin server in /etc/krb5.conf, then using kinit to get a ticket, klist to view it, and kdestroy to purge it.

Why it is used: Single sign-on so services authenticate with a short-lived ticket instead of sending a password repeatedly.

/etc/krb5.conf
# Install
apt install krb5-user
[libdefaults]
default_realm = EXAMPLE.COM
[realms]
EXAMPLE.COM = {
kdc = kdc.example.com
admin_server = kdc.example.com
}
# Get ticket
kinit admin@EXAMPLE.COM
klist
kdestroy

Interview talking point: “Tickets expire and clocks must be in sync, so when authentication suddenly fails, an expired ticket from kinit or a skewed clock is the first thing to check.”

What it is: SSSD sits between the system and the directory, configured in /etc/sssd/sssd.conf with services nss and pam, a domain section naming the ldap id and auth providers, URI, and search base, then enabled as a service.

Why it is used: Caching directory lookups and handling authentication so logins still work when the server is briefly unreachable.

Terminal window
# Install
apt install sssd realmd
# Configure
# /etc/sssd/sssd.conf
[sssd]
services = nss, pam
domains = LDAP
[domain/LDAP]
id_provider = ldap
auth_provider = ldap
ldap_uri = ldap://ldap.example.com
ldap_search_base = dc=example,dc=com
# Enable
systemctl enable sssd

Interview talking point: “SSSD replaces separate nss and pam LDAP wiring by providing both services from one daemon, and its built-in cache is what keeps logins working during a directory outage.”

What it is: MFA implementation uses multiple factors, methods such as TOTP or push, a gradual rollout, recovery codes as backup, and policy enforcement.

Why it is used: To block account takeover even when passwords have already leaked.

Terminal window
# MFA implementation
# 1. Factors
# Multiple
# 2. Methods
# TOTP/Push
# 3. Rollout
# Gradual
# 4. Backup
# Recovery codes
# 5. Enforcement
# Policy

Interview talking point: “Recovery codes are part of the design because enforcing MFA without a backup path locks users out permanently when they lose their device.”

What it is: MFA adds multiple verification factors to strengthen authentication.

Why it is used: It significantly reduces the risk of account compromise from stolen credentials.

Terminal window
# Factors
# Multiple
# Methods
# TOTP/Push
# Rollout
# Gradual
# Backup
# Recovery codes
# Enforcement
# Policy

Interview talking point: “Gradual rollout with backup recovery codes ensures adoption while providing fallback options for users.”

Q355: How do you implement two-factor authentication?

Section titled “Q355: How do you implement two-factor authentication?”

What it is: TOTP-based two-factor authentication is implemented for SSH using the Google Authenticator PAM module.

Why it is used: Add a second authentication factor to strengthen SSH access security.

Terminal window
# Install Google Authenticator PAM module
apt install libpam-google-authenticator
# Configure PAM
# /etc/pam.d/sshd
# Add before @include common-auth
auth required pam_google_authenticator.so
# Configure SSH
# /etc/ssh/sshd_config
ChallengeResponseAuthentication yes
AuthenticationMethods password,keyboard-interactive
# For user
su - username
google-authenticator
# TOTP configuration
# Add to user .google_authenticator
# Store secret securely
# Test
ssh username@server
# Enter password
# Enter 6-digit code

Interview talking point: “PAM requires ChallengeResponseAuthentication enabled in SSH, and each user generates a TOTP secret with google-authenticator.”

Q356: How do you implement user authentication with PAM?

Section titled “Q356: How do you implement user authentication with PAM?”

What it is: PAM stacks pluggable modules under /etc/pam.d per service to enforce password history, resource limits, and time-based login rules.

Why it is used: To apply one password or access policy across every service without rewriting each program.

Terminal window
# PAM configuration files
ls -la /etc/pam.d/
# Example: password policy
# /etc/pam.d/common-password
password required pam_pwhistory.so remember=5
password [default=1] pam_permit.so
# Limit resources
# /etc/security/limits.conf
username soft nofile 4096
username hard nofile 8192
# Time-based login
# /etc/security/time.conf
login;ts001;users;Al0900-1700

Interview talking point: “Each line’s control flag, such as required or the default value, decides whether failure blocks the whole stack, so module order matters. limits.conf sets per-user file descriptor ceilings while time.conf gates when logins are allowed.”

Q357: How do you implement user authentication?

Section titled “Q357: How do you implement user authentication?”

What it is: PAM configuration enforces login rules: pam_tally2 locks after failures, pam_cracklib and pam_pwhistory set password policy, and login.defs sets expiry days.

Why it is used: To harden authentication and enforce a password lifecycle across the fleet.

/etc/pam.d/common-auth
# PAM configuration
auth required pam_tally2.so deny=3 unlock_time=600
# Password policy
# /etc/pam.d/common-password
password required pam_pwhistory.so remember=5
password requisite pam_cracklib.so try_first_pass retry=3 minlen=12
# Account expiry
# /etc/login.defs
PASS_MAX_DAYS 90
PASS_MIN_DAYS 1
PASS_WARN_AGE 14
# User expiry
passwd -x 90 -w 14 -n 1 username

Interview talking point: “deny=3 unlock_time=600 blocks an account for 600 seconds after three failed logins, remember=5 blocks reuse of the last five passwords, and PASS_MAX_DAYS 90 expires them quarterly.”

What it is: authconfig updates authentication configuration in one shot, enabling shadow and md5 along with an LDAP server and base DN, or enabling Kerberos with a realm and KDC, applying everything with —update.

Why it is used: Point a machine at LDAP or Kerberos without hand-editing nsswitch, PAM, and related files.

Terminal window
# Configure authentication
authconfig --enableshadow --enablemd5 \
--ldapserver=ldap.example.com \
--ldapbasedn="dc=example,dc=com" \
--update
# With Kerberos
authconfig --enablekrb5 \
--krb5realm=EXAMPLE.COM \
--krb5kdc=kdc.example.com \
--update

Interview talking point: “The —update flag writes the changes immediately, so the same invocation is repeatable across a fleet instead of editing configuration files by hand on every host.”

What it is: SSSD cache settings in sssd.conf with cache_credentials true and entry_cache_timeout 600 seconds, cleared with sss_cache -E, debugging raised with sss_debuglevel 9, and results verified through getent passwd.

Why it is used: Speed up directory lookups and keep logins working when the directory server is down.

/etc/sssd/sssd.conf
# Configure
[sssd]
cache_credentials = true
entry_cache_timeout = 600
# Clear cache
sss_cache -E
# Debug
sss_debuglevel 9
# Check
getent passwd user@domain

Interview talking point: “entry_cache_timeout sets how long entries stay fresh before a refresh is needed, sss_cache -E forces an immediate re-read after a directory change, and getent confirms what the cache is actually returning.”

Q360: How do you implement user authentication security?

Section titled “Q360: How do you implement user authentication security?”

What it is: PAM stacks modules under /etc/pam.d to enforce login rules such as lockouts after failed attempts and password complexity. Expiry defaults and per-user aging come from login.defs, passwd, and chage.

Why it is used: To enforce one org-wide password policy across services without editing each service code.

/etc/pam.d/common-auth
# Configure PAM
auth required pam_tally2.so deny=3 unlock_time=600 onerr=fail
# Password policy
# /etc/pam.d/common-password
password required pam_pwhistory.so remember=5
password [default=1] pam_permit.so
password requisite pam_cracklib.so try_first_pass retry=3 minlen=12 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1
# Set password expiry
# /etc/login.defs
PASS_MAX_DAYS 90
PASS_MIN_DAYS 1
PASS_WARN_AGE 14
# For user
passwd -x 90 -w 14 -n 1 username
chage -M 90 -W 14 username
# View aging
chage -l username

Interview talking point: “chage -l shows aging data while chage -M and -W set maximum days and warning window, and pam_tally2 locks an account after repeated failures for a set unlock time.”

What it is: auditd logs file access; auditctl -w adds a watch with permissions such as wa or r plus a key, ausearch searches by that key, and aureport summarizes events.

Why it is used: Proving who touched sensitive files like /etc/passwd for audits and incidents.

Terminal window
# Install audit
apt install auditd
# Configure rules
auditctl -w /etc/passwd -p wa -k passwd_changes
auditctl -w /var/www/html -p r -k web_access
# View logs
ausearch -k passwd_changes
aureport -f

Interview talking point: “-p selects which operations trigger the watch, so the wa on /etc/passwd records writes and attribute changes, while the -k key is what makes later ausearch queries fast and specific.”

Q362: How do you configure audit logging in K8s?

Section titled “Q362: How do you configure audit logging in K8s?”

What it is: Kubernetes audit logging uses a Policy file that sets a log level per resource, wired to the API server with the audit-policy-file and audit-log-path flags.

Why it is used: To record who did what in the cluster for security and compliance.

/etc/kubernetes/audit-policy.yaml
# Enable audit
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: RequestResponse
resources:
- group: ""
resources: ["pods"]
- level: Metadata
resources:
- group: ""
resources: ["pods/log", "pods/status"]
# Configure API server
# --audit-policy-file=/etc/kubernetes/audit-policy.yaml
# --audit-log-path=/var/log/kubernetes/audit

Interview talking point: “RequestResponse records full request and response bodies for pods while Metadata logs only object headers elsewhere, so the chosen level directly controls log volume and detail.”

What it is: auditd configuration writing to /var/log/audit/audit.log with 100 MB rotation, plus watch rules flagging write and attribute changes on passwd, shadow, and sudoers with search keys.

Why it is used: Records who modifies critical system files for forensics and alerting.

/etc/audit/auditd.conf
log_file = /var/log/audit/audit.log
max_log_file = 100
max_log_file_action = ROTATE
# /etc/audit/rules.d/audit.rules
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes

Interview talking point: “The -p wa flag watches both writes and attribute changes, and the -k key tags events so entries can be pulled from audit.log by keyword during an investigation.”

What it is: auditd records file and syscall events; rules in audit.rules watch /etc/passwd, shadow, and sudoers for write or attribute changes, log execve of wget and curl with keys, and aureport summarizes the results.

Why it is used: To prove who changed critical files or ran certain commands.

Terminal window
# Install
apt install auditd
# Configure rules
# /etc/audit/audit.rules
# Watch files
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes
# Watch commands
-a always,exit -F arch=b64 -S execve -F path=/usr/bin/wget -k network-download
-a always,exit -F arch=b64 -S execve -F path=/usr/bin/curl -k network-download
# Watch directories
-w /etc/httpd/conf/ -p wa -k httpd_conf
# Services
-w /usr/sbin/service -p x -k service_management
# Generate report
aureport --summary
aureport --file
aureport --terminal

Interview talking point: “The -k tag keys every event so aureport and ausearch can find related records later, and -p wa on a watch means write plus attribute changes, not reads.”

Q365: How do you configure Linux audit for compliance?

Section titled “Q365: How do you configure Linux audit for compliance?”

What it is: Compliance audit rules watch sensitive files such as /etc/passwd, /etc/sudoers, and /var/log, tagging each with keys like pci_passwd.

Why it is used: To produce evidence for PCI-DSS and CIS reviews of who changed critical files.

Terminal window
# PCI-DSS requirements
auditctl -w /etc/passwd -p wa -k pci_passwd
auditctl -w /etc/shadow -p wa -k pci_shadow
auditctl -w /var/log/ -p wa -k pci_logs
auditctl -w /etc/sudoers -p wa -k pci_sudoers
# CIS benchmarks
auditctl -w /etc/group -p wa -k group_change
auditctl -w /etc/hosts -p wa -k hosts_change
auditctl -w /etc/sysctl.conf -p wa -k sysctl_change

Interview talking point: “The same auditctl -w watch pattern serves both standards, and the -k key such as pci_sudoers is what makes audit records searchable when an auditor asks.”

Q366: How do you configure Linux audit rules?

Section titled “Q366: How do you configure Linux audit rules?”

What it is: auditctl adds file watches, with -p selecting the permissions watched such as wa or x, and -k tagging each rule for later search.

Why it is used: To record who writes to /etc/passwd or runs rm, then prove it later.

Terminal window
# Monitor file changes
auditctl -w /etc/passwd -p wa -k passwd_change
auditctl -w /etc/shadow -p wa -k shadow_change
# Monitor directory
auditctl -w /var/www/html -p r -k web_access
# Monitor commands
auditctl -w /usr/bin/rm -p x -k rm_command
# List rules
auditctl -l
# Search
ausearch -k passwd_change
aureport -f

Interview talking point: “The -k key ties rule to evidence: auditctl -l lists active rules, ausearch -k passwd_change finds those events, and aureport -f summarizes file access reports.”

Q367: How do you configure system auditing?

Section titled “Q367: How do you configure system auditing?”

What it is: auditd is the Linux auditing daemon. Rules in /etc/audit/audit.rules watch files and syscalls, and ausearch and aureport query the recorded events.

Why it is used: To track who changed critical files or ran privileged commands, for compliance and forensics.

Terminal window
# Install auditd
apt install auditd
# Configure rules
# /etc/audit/audit.rules
# Monitor file changes
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/ssh/sshd_config -p wa -k sshd_config
# Monitor commands
-w /usr/bin/sudo -p x -k sudo_commands
-w /usr/bin/su -p x -k su_commands
# Monitor network
-a always,exit -F arch=b64 -S socket -k network_connections
# View logs
ausearch -k passwd_changes
aureport -f
aureport -u
# Real-time monitoring
auditctl -w /etc/passwd -p wa -k passwd_changes

Interview talking point: “auditctl -w adds a watch that lasts until reboot, while rules written into audit.rules survive restarts, and the -k key lets ausearch pull every event tagged passwd_changes.”

What it is: auditd records security events through file watches with write and attribute permissions, syscall rules for execve and setuid, and searchable keys.

Why it is used: To prove who changed critical files or when privileged commands ran.

/etc/audit/audit.rules
# Configure auditd
# Watch files
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes
-w /etc/ssh/sshd_config -p wa -k sshd_config
# Watch directories
-w /etc/httpd/conf -p wa -k httpd_conf
-w /etc/nginx/nginx.conf -p wa -k nginx_conf
# System calls
-a always,exit -F arch=b64 -S execve -F path=/usr/bin/wget -k network_download
-a always,exit -F arch=b64 -S execve -F path=/usr/bin/curl -k network_download
-a always,exit -F arch=b64 -S setuid -k privilege_escalation
# Commands
-w /usr/bin/sudo -p x -k sudo_commands
-w /usr/bin/su -p x -k su_commands
# View logs
ausearch -k passwd_changes
aureport -f
aureport -u

Interview talking point: “The -k key tags related events so ausearch -k passwd_changes returns exactly that trail, and a -p x watch on sudo logs executions rather than file writes.”

What it is: auditd watches paths via auditctl -w, flagging write and attribute changes on /etc/passwd, /etc/shadow and /var/log with keys, then ausearch and aureport query those records.

Why it is used: To prove which user or process modified sensitive files, which compliance and forensics work requires.

Terminal window
# Configure auditd
auditctl -w /etc/passwd -p wa -k identity
auditctl -w /etc/shadow -p wa -k identity
auditctl -w /var/log/ -p wa -k logfiles
# Search
ausearch -k identity
aureport -f

Interview talking point: “The -p wa flag means write plus attribute change, and the -k key lets ausearch -k identity pull only matching events, so tagging rules well is what makes audits searchable.”

What it is: auditd records security events for files and programs, with rules written by auditctl watching permissions such as write or execute and tagging hits with a key.

Why it is used: To prove who changed a critical file or which process deleted data.

Terminal window
# Install audit
apt install auditd
# or
yum install audit
# Configure /etc/audit/auditd.conf
max_log_file = 50
max_log_file_action = rotate
# Add rules
auditctl -w /etc/passwd -p wa -k passwd_changes
auditctl -w /usr/bin/rm -p x -k file_delete
# View logs
ausearch -k passwd_changes
aureport --file
# Make rules persistent
# /etc/audit/rules.d/audit.rules

Interview talking point: “auditctl -w adds a live watch that vanishes on reboot, so persistent rules belong in /etc/audit/rules.d. ausearch -k filters by the key you assigned, turning raw audit lines into a focused trail.”

What it is: auditd is the Linux audit daemon. auditctl adds watch rules on paths, ausearch searches the audit log by key, aureport summarizes events, and auditctl -e 2 enables auditing persistently at boot.

Why it is used: To record who changed critical files or ran sensitive binaries, for forensics and compliance evidence.

Terminal window
# Install
apt install auditd
# Add rules
auditctl -w /etc/passwd -p wa -k passwd_change
auditctl -w /var/www/html -p r -k web_access
auditctl -w /sbin/iptables -p x -k iptables_change
# List rules
auditctl -l
# Search logs
ausearch -k passwd_change
aureport -f
# Enable at boot
auditctl -e 2

Interview talking point: “The -p flag sets which access types trigger a rule: wa on /etc/passwd catches writes and attribute changes, r logs reads, x logs execution. Rules carry a -k key so ausearch -k passwd_change pulls just that event class instead of grepping the whole audit log.”

What it is: Kubernetes auditing involves enabling audit logging with an audit policy file, securely storing logs, integrating with SIEM systems, and performing regular reviews.

Why it is used: Audit logs provide visibility into API operations, helping detect unauthorized access, policy violations, and suspicious activity.

Terminal window
# Enable audit
# Configure audit policy
# --audit-policy-file=/path/to/policy.yaml
# Review logs
# Store in secure location
# Use SIEM integration
# Regular review

Interview talking point: “A well-defined audit policy balances security visibility with log volume, capturing critical events without overwhelming storage or analysis tools.”

What it is: auditd is the Linux audit daemon, and auditctl adds rules that watch paths with permission filters, tagged by a key. ausearch and aureport query the resulting log.

Why it is used: To prove who changed files like /etc/passwd, or to monitor access to web content for compliance.

Terminal window
# Install
apt install auditd
# Add rules
auditctl -w /etc/passwd -p wa -k passwd_change
auditctl -w /var/www/html -p r -k web_access
# List rules
auditctl -l
# Search
ausearch -k passwd_change
aureport -f

Interview talking point: “Rules carry a key with -k, so ausearch -k passwd_change pulls only that stream while aureport -f summarizes file events. The -p wa on /etc/passwd watches writes and attribute changes, whereas -p r on the web tree watches reads.”

What it is: AIDE is a file integrity monitor: aide.conf defines database paths, rules combining attributes like permissions, owner, and checksums, and the paths to watch; aideinit builds the database and aide —check compares files against it.

Why it is used: To detect unauthorized modification of system binaries and configuration.

Terminal window
# Install
apt install aide
# Configure
# /etc/aide/aide.conf
# Database location
database=file:/var/lib/aide/aide.db
database_out=file:/var/lib/aide/aide.db.new
# Rules
Full = p+i+n+u+g+s+m+c+md5+sha256
Lsof = p+u+g+i+n+S
# Files to monitor
/etc p+inode+u+g+i+m+c+md5+sha256
/bin p+inode+u+g+i+m+c+md5+sha256
/sbin p+inode+u+g+i+m+c+md5+sha256
/usr p+inode+u+g+i+m+c+md5+sha256
# Initialize database
aideinit
# Check integrity
aide --check
aide --update
# Schedule
# /etc/cron.d/aide
0 5 * * * root /usr/bin/aide --check

Interview talking point: “aide —check only reports differences against the baseline, while aide —update accepts current state as the new baseline, so accepting blindly hides real tampering.”

What it is: AIDE is a file integrity checker that builds a database of file checksums, then compares the live system against it. aideinit initializes it, aide —check compares, and aide —update refreshes the database.

Why it is used: To detect unauthorized changes to system files, configs, or binaries after an intrusion or configuration drift.

Terminal window
# Install
apt install aide
# Initialize
aideinit
# Update database
aide --update
# Check
aide --check
# Configuration /etc/aide/aide.conf
/etc/ NORMAL
/var/log/ LOG
!/var/log/*.log
# Daily check
0 5 * * * /usr/bin/aide --check

Interview talking point: “aide —check reports differences against the stored database while aide —update regenerates that database, so after an expected change you run an update or every later check flags it. Config rules tag directory classes like NORMAL and LOG and exclude log files with a leading bang.”

What it is: osquery exposes the operating system as SQL tables; osqueryi runs queries like SELECT * FROM listening_ports against live system state.

Why it is used: To ask fleet-wide questions about users, processes, and ports using familiar SQL.

Terminal window
# Install
apt install osquery
# Interactive
osqueryi
# Queries
SELECT * FROM users;
SELECT * FROM processes WHERE name = 'nginx';
SELECT * FROM listening_ports;
SELECT * FROM file_events;
# Daemon
systemctl enable osqueryd
systemctl start osqueryd

Interview talking point: “osqueryi is for interactive one-off questions, while osqueryd runs scheduled queries such as file_events so changes are collected continuously in the background.”

What it is: Tripwire is a file integrity monitor: tripwire —init builds a signed baseline and tripwire —check compares the current system to it.

Why it is used: To prove which system files changed and whether they were tampered with.

Terminal window
# Install
apt install tripwire
# Initialize
twadmin --create-polfile /etc/tripwire/tw.pol
tripwire --init
# Check
tripwire --check
# Update
tripwire --update --accept-all
# Update policy
twadmin --create-polfile /etc/tripwire/twpol.txt
tripwire --update-policy /etc/tripwire/twpol.txt

Interview talking point: “After a check, tripwire —update —accept-all folds approved changes into the database, and policy text changes go through twadmin —create-polfile before tripwire —update-policy.”

Q378: How do you implement file integrity monitoring?

Section titled “Q378: How do you implement file integrity monitoring?”

What it is: File integrity monitoring records a baseline of system files and alerts when they change. The record uses AIDE or Tripwire, where twadmin creates the policy file, tripwire —init builds the database, and tripwire —check compares.

Why it is used: To detect tampering with system binaries and configuration during audits or after a breach.

Terminal window
# Using AIDE (see above)
# Using tripwire
apt install tripwire
# Initialize
twadmin --create-polfile /etc/tripwire/tw.pol
tripwire --init
# Check
tripwire --check
# Update
tripwire --update --accept-all

Interview talking point: “Tripwire separates the policy file from the database: twadmin —create-polfile writes the policy, tripwire —init loads the baseline, and tripwire —update —accept-all records intended changes as the new baseline.”


Q379: How do you implement file integrity monitoring?

Section titled “Q379: How do you implement file integrity monitoring?”

What it is: AIDE monitors file integrity by comparing checksums and metadata against a previously created database.

Why it is used: Detect unauthorized changes to critical system files for security auditing.

Terminal window
# Install AIDE
apt install aide
# Configure
# /etc/aide/aide.conf
# Database
database=file:/var/lib/aide/aide.db
database_out=file:/var/lib/aide/aide.db.new
# Rules
Fip = p+i+n+u+g+s+m+c+md5+sha256
Lnx = p+u+g+i+n+S
# Directories
/etc Fip
/bin Lnx
/sbin Lnx
/usr Lnx
# Initialize
aideinit
# Check
aide --check
aide --update
# Cron job
# /etc/cron.d/aide
0 5 * * * root /usr/bin/aide --check | mail -s "AIDE Report" admin@example.com

Interview talking point: “A baseline is created with aideinit; scheduled —check runs flag modifications that require investigation.”

Q380: How do you set up AIDE (Advanced Intrusion Detection Environment)?

Section titled “Q380: How do you set up AIDE (Advanced Intrusion Detection Environment)?”

What it is: AIDE builds a database of file checksums and metadata, then compares the current system against it to detect changes. aideinit creates the database, aide —update refreshes it, and aide —check runs the comparison, here from cron.

Why it is used: To notice unauthorized edits to system files and prove integrity after an incident or audit.

Terminal window
# Install
apt install aide
# Initialize database
aideinit
# Configure
cat /etc/aide/aide.conf
!/var/log/.*
!/var/cache/.*
# Update database
aide --update
# Check integrity
aide --check
# Daily cron
0 5 * * * /usr/bin/aide --check

Interview talking point: “The exclusion lines starting with ! keep noisy trees like /var/log and /var/cache out of the reports, and the daily cron entry at 5am runs aide —check so drift is caught automatically.”

Q381: How do you set up file integrity monitoring?

Section titled “Q381: How do you set up file integrity monitoring?”

What it is: AIDE builds a checksum and attribute database at aideinit, then a daily cron job runs aide —check to compare files like /etc/shadow against that baseline.

Why it is used: To detect unauthorized modification of critical files, which indicates tampering or intrusion.

Terminal window
# Install AIDE
aideinit
# Configure
# /etc/aide/aide.conf
/etc/shadow NORMAL
/etc/passwd NORMAL
/var/log NORMAL
# Daily check
0 5 * * * /usr/bin/aide --check

Interview talking point: “AIDE reports changes after the fact rather than blocking them, so the daily 5am cron run directly controls how fast you notice tampering.”

What it is: AIDE builds a database of file checksums and attributes; aideinit creates it and aide —check compares the system against that database.

Why it is used: To detect unauthorized changes to configuration and binaries after a possible intrusion.

Terminal window
# Install
apt install aide
# Initialize
aideinit
# Update after changes
aide --update
# Check
aide --check
# Configuration
# /etc/aide/aide.conf
/etc/pam.d/ NORMAL
/etc/shadow NORMAL
/var/log/ LOG
!/var/log/*.log

Interview talking point: “aide.conf rules choose what is tracked, for example NORMAL for /etc/pam.d and LOG for /var/log, while the bang pattern excludes matching log files from checks.”

What it is: chkrootkit is a local scanner that runs shell-based tests for known rootkit signs and other anomalies on the host.

Why it is used: To quickly check a suspect box for installed rootkits without heavy setup.

Terminal window
# Install
apt install chkrootkit
# Check
chkrootkit
# Specific
chkrootkit -q
# Cron
# /etc/cron.daily/chkrootkit
#!/bin/sh
chkrootkit | grep -v "not found"

Interview talking point: “chkrootkit -q narrows output to suspicious results, and the cron job pipes output through grep -v “not found” so clean tests do not clutter the daily report.”

What it is: ClamAV is an antivirus scanner; freshclam updates signatures, clamscan -r scans a tree, and the —remove flag deletes infected files.

Why it is used: To scan mail, home directories, or uploaded files for malware on Linux.

Terminal window
# Install
apt install clamav
# Update
freshclam
# Scan
clamscan -r /home
clamscan -r --remove /home
# Daemon
systemctl start clamav-freshclam
systemctl start clamav-daemon
# On-access
clamfs /etc/clamfs/clamfs.xml

Interview talking point: “clamscan is a one-shot scan, while clamav-daemon plus clamfs gives on-access scanning so files are checked when opened instead of on a schedule.”

What it is: rkhunter scans for rootkits, backdoors, and suspicious files, verifying known-good hashes of key binaries after rkhunter —update refreshes its data.

Why it is used: To catch signs of a compromised host as part of routine checks.

Terminal window
# Install
apt install rkhunter
# Update
rkhunter --update
# Check
rkhunter --check
# Cron
# /etc/cron.daily/rkhunter
#!/bin/sh
rkhunter --check --skip-keypress --report-warnings-only

Interview talking point: “The cron example runs rkhunter —check —skip-keypress —report-warnings-only so an unattended daily scan only reports real warnings instead of stalling at a prompt.”

What it is: Snort is a signature-based IDS that inspects traffic on an interface and fires alerts from rules written in local.rules. Suricata appears as a modern alternative run with its own config.

Why it is used: To detect scans, exploit attempts, and odd connections on a network segment.

Terminal window
# Install Snort
apt install snort
# Configure
# /etc/snort/snort.conf
ipvar HOME_NET 192.168.1.0/24
ipvar EXTERNAL_NET !$HOME_NET
# Custom rules
# /etc/snort/rules/local.rules
# Alert on ICMP
alert icmp any any -> $HOME_NET any (msg:"ICMP Ping"; sid:1000001; rev:1;)
# Alert on SSH attempts
alert tcp any any -> $HOME_NET 22 (msg:"SSH Connection Attempt"; \
flow:to_server,established; content:"SSH"; nocase; sid:1000002; rev:1;)
# Alert on port scan
alert tcp any any -> $HOME_NET any (msg:"Port Scan"; \
flow:to_server; detection_filter:track by_src,count 5,seconds 10; \
sid:1000003; rev:1;)
# Run snort
snort -c /etc/snort/snort.conf -i eth0
# Suricata (modern alternative)
apt install suricata
suricata -c /etc/suricata/suricata.yaml -i eth0

Interview talking point: “The HOME_NET and EXTERNAL_NET variables scope rules to your own subnet, and detection_filter turns repeated hits from one source into a port scan alert.”

What it is: OSSEC is a host-based intrusion detection agent that watches logs and files and can trigger active responses defined in ossec.conf.

Why it is used: To monitor a host for unauthorized changes and react automatically to alerts.

Terminal window
# Install
apt install ossec-hids-agent
# Configure
# /var/ossec/etc/ossec.conf
<active-response>
<disabled>no</disabled>
</active-response>
# Start
/var/ossec/bin/ossec-control start
# View alerts
tail -f /var/ossec/logs/alerts/alerts.log

Interview talking point: “Enabling active-response in ossec.conf makes the agent act rather than only report, and tail -f on /var/ossec/logs/alerts/alerts.log shows those alerts as they arrive.”

What it is: Snort is a packet logger and IDS configured by snort.conf, where ipvar HOME_NET sets your trusted range and RULE_PATH points at the rules.

Why it is used: To inspect network traffic for attacks and record what matched.

Terminal window
# Install
apt install snort
# Configure
# /etc/snort/snort.conf
ipvar HOME_NET 192.168.1.0/24
var RULE_PATH /etc/snort/rules
# Test rules
snort -T -c /etc/snort/snort.conf
# Run
snort -i eth0 -c /etc/snort/snort.conf
# Logs
ls /var/log/snort/

Interview talking point: “snort -T -c snort.conf tests configuration and rules without capturing, so you can validate a HOME_NET change before starting with snort -i eth0.”

What it is: Suricata is a network IDS/IPS that inspects traffic against rules; suricata-update refreshes those rules and suricata -i eth0 captures on an interface.

Why it is used: To detect malicious network traffic and log alerts for investigation.

Terminal window
# Install
apt install suricata
# Update rules
suricata-update
# Run
suricata -i eth0
suricata -c /etc/suricata/suricata.yaml -i eth0
# Log
tail -f /var/log/suricata/fast.log
# Test
suricata -t /etc/suricata/suricata.yaml

Interview talking point: “suricata -t validates the config and rules before you commit to a real run, and matches land in /var/log/suricata/fast.log which you can follow with tail -f.”

Q390: How do you configure intrusion detection?

Section titled “Q390: How do you configure intrusion detection?”

What it is: Intrusion detection at three points: a Snort network rule alerting on traffic into the local subnet, AIDE refreshed with aide update, and Tripwire with an initialized policy file.

Why it is used: Detects suspicious network activity and unauthorized file changes on hosts.

/etc/snort/snort.conf
# Network IDS (Snort)
var HOME_NET 192.168.1.0/24
alert tcp any any -> $HOME_NET any (msg:"Suspicious traffic"; sid:1000001;)
# Host IDS (AIDE)
aide --update
# File integrity (Tripwire)
twadmin --create-polfile /etc/tripwire/tw.pol
tripwire --init

Interview talking point: “Snort inspects packets while AIDE and Tripwire compare file hashes, so network and host-based detection produce different evidence of the same incident.”

Q391: How do you implement intrusion detection?

Section titled “Q391: How do you implement intrusion detection?”

What it is: OSSEC is a host based intrusion detection system installed as an agent, configured in ossec.conf where active-response is enabled, with custom rules in local_rules.xml.

Why it is used: To watch a host for suspicious activity and automatically respond using defined rules.

Terminal window
# OSSEC
# Install
apt install ossec-hids-agent
# Configure
# /var/ossec/etc/ossec.conf
<active-response>
<disabled>no</disabled>
</active-response>
# Rules in
# /var/ossec/etc/rules/local_rules.xml

Interview talking point: “OSSEC is host based, watching one machine’s logs and files rather than network traffic, and enabling active-response makes it act on events instead of only alerting.”

Q392: How do you implement intrusion detection?

Section titled “Q392: How do you implement intrusion detection?”

What it is: AIDE is a file integrity monitor that stores hashes and attributes in a database, builds it with aideinit, and compares with aide —check.

Why it is used: To detect unauthorized modification of system files after an intrusion.

Terminal window
# Install AIDE
apt install aide
# Configure
# /etc/aide/aide.conf
database=file:/var/lib/aide/aide.db
database_out=file:/var/lib/aide/aide.db.new
# Rules
Fip = p+i+n+u+g+s+m+c+md5+sha256
Lnx = p+u+g+i+n+S
# Files to monitor
/etc Fip
/bin Lnx
/sbin Lnx
# Initialize database
aideinit
# Check integrity
aide --check
# Schedule checks
# /etc/cron.d/aide
0 5 * * * root /usr/bin/aide --check | mail -s "AIDE Report" admin@example.com

Interview talking point: “AIDE reports changes after they happen rather than blocking them, so a daily cron job piping aide —check into mail alerts you when /etc or /bin no longer matches the database.”

What it is: OpenSCAP evaluates systems against SCAP profiles; oscap info lists the profiles and oscap xccdf eval runs one, saving XML results.

Why it is used: To check a host against CIS or vendor benchmarks and keep the report.

Terminal window
# Install
apt install openscap-scanner scap-security-guide
# List profiles
oscap info /usr/share/xml/scap/ssg/content/ssg-ubuntu2004-ds.xml
# Scan
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis \
--results scan-results.xml /usr/share/xml/scap/ssg/content/ssg-ubuntu2004-ds.xml
# Generate report
oscap xccdf generate report scan-results.html scan-results.xml

Interview talking point: “The scan writes scan-results.xml, and oscap xccdf generate report turns it into an HTML report you can hand to auditors rather than quoting console output.”

Q394: How do you implement CIS benchmarks?

Section titled “Q394: How do you implement CIS benchmarks?”

What it is: Applying CIS benchmarks: lynis audits the system, can target a CIS profile, and can emit HTML; example controls disable unused filesystem modules, set a GRUB password, and enable TCP syncookies.

Why it is used: To harden a host against a recognized security baseline.

Terminal window
# Install CIS benchmark tool
apt install lynis
# Run audit
lynis audit system
lynis audit --profile cis-ubuntu-22.04
# Key CIS controls
# 1.1.1 Disable unused filesystems
echo "install cramfs /bin/true" > /etc/modprobe.d/cramfs.conf
echo "install squashfs /bin/true" > /etc/modprobe.d/squashfs.conf
# 1.5.1 Set bootloader password
grub-mkpasswd-pbkdf2
# Add to /etc/grub.d/40_custom
# 3.1 Enable syncookies
sysctl -w net.ipv4.tcp_syncookies=1
# 4.1 Configure auditd
# See auditd configuration earlier
# Generate report
lynis audit system --html > report.html

Interview talking point: “The modprobe lines that point cramfs and squashfs at /bin/true stop those filesystems from ever loading, which is a cheap way to shrink attack surface.”

Q395: How do you configure Lynis security audit?

Section titled “Q395: How do you configure Lynis security audit?”

What it is: Lynis is a host security auditing tool; lynis audit system runs the full set of tests and lynis quick runs a short pass.

Why it is used: To baseline a server’s hardening level and get a prioritized list of fixes.

Terminal window
# Install
apt install lynis
# Audit
lynis audit system
lynis audit system --profile custom.prf
# Quick audit
lynis quick
# Update
lynis update info

Interview talking point: “lynis audit system —profile custom.prf audits against your own profile, and lynis quick trades coverage for speed when you just want a fast look.”

Q396: How do you implement container security scanning?

Section titled “Q396: How do you implement container security scanning?”

What it is: Container security scanning at build time, in the registry, and at runtime, backed by defined policies and CI/CD automation.

Why it is used: Finds image and running-container weaknesses at every stage, not just one.

Terminal window
# Container security scanning
# 1. Build time
# Scan images
# 2. Registry
# Scan stored
# 3. Runtime
# Scan running
# 4. Policies
# Define
# 5. Automation
# CI/CD

Interview talking point: “Scanning at three points covers different risks: build time catches bad base images, registry scans what is stored, and runtime sees what is actually deployed. Only runtime scanning reveals what a container does after launch.”

Q397: How do you implement container security scanning?

Section titled “Q397: How do you implement container security scanning?”

What it is: Container security scanning involves checking container images and running containers for known vulnerabilities across build, registry, and runtime stages.

Why it is used: It helps prevent deploying vulnerable containers into production environments.

Terminal window
# Build time
# Scan images
# Registry
# Scan stored
# Runtime
# Scan running
# Policies
# Define
# Automation
# CI/CD

Interview talking point: “Scanning at build, registry, and runtime creates multiple checkpoints, but policies and automation are needed to enforce those checks consistently.”

Q398: How do you implement security scanning?

Section titled “Q398: How do you implement security scanning?”

What it is: Security scanning covers images with trivy and docker scout, cluster posture with kubescape, and runtime behavior with falco.

Why it is used: To find vulnerabilities and misconfigurations before and after deployment.

Terminal window
# Container scanning
trivy image nginx:latest
docker scout cves myimage
# K8s security scan
kubescape scan --severity threshold
# Runtime security
falco --help

Interview talking point: “Image scanning catches known CVEs before deploy while falco watches running containers for anomalous activity, so the tools cover different phases of the container lifecycle.”

Q399: How do you implement security scanning?

Section titled “Q399: How do you implement security scanning?”

What it is: Security scanning identifies vulnerabilities across code, dependencies, containers, and clusters.

Why it is used: It catches known issues early before they reach production workloads.

Terminal window
# Container scanning
trivy image myimage:latest
# K8s scanning
kubescape scan
# Code scanning
sonarqube
# Dependency scanning
npm audit
snyk test

Interview talking point: “Tools like Trivy, Kubescape, SonarQube, and Snyk target different layers, so a layered scanning strategy is often needed.”

Q400: How do you implement security scanning?

Section titled “Q400: How do you implement security scanning?”

What it is: A scanning toolkit: Trivy and Clair for images, kube-bench and kube-hunter for clusters, Bandit and Semgrep for source, ZAP for running sites, TruffleHog and gitleaks for secrets.

Why it is used: To find vulnerabilities and leaked credentials before attackers do.

Terminal window
# Container scanning
# Trivy
trivy image myimage:latest
trivy image --severity HIGH,CRITICAL myimage:latest
trivy image --exit-code 1 --severity CRITICAL myimage:latest
# Clair
docker run -p 5432:5432 -d quay.io/coreos/clair:latest
clair-scanner myimage
# Infrastructure scanning
# Kube-bench
kube-bench run --targets node
# Kube-hunter
kubectl run --rm -it --image=kubehunter/kubehunter --name kubehunter
# SAST
# Bandit (Python)
bandit -r myapp/
# Semgrep
semgrep --config=auto mycode/
# DAST
# OWASP ZAP
zap-baseline.py -t https://myapp.example.com
# Secret scanning
# TruffleHog
trufflehog filesystem myrepo/
# gitleaks
gitleaks --path=mydir --verbose

Interview talking point: “The exit-code 1 flag on trivy image is what makes it fail a CI pipeline on CRITICAL findings, while exit-code 0 only reports. Each layer needs its own scanner: image, code, or live site.”

Q401: How do you implement security scanning?

Section titled “Q401: How do you implement security scanning?”

What it is: Security scanning implementation involves integrating SAST, automating DAST, scanning software dependencies (SCA), scanning containers, and enabling runtime protection.

Why it is used: It detects vulnerabilities across the application lifecycle.

Terminal window
# SAST
# Integrate
# DAST
# Automated
# SCA
# Dependencies
# Container
# Scanning
# Runtime
# Protection

Interview talking point: “A layered approach spanning SAST, SCA, container, DAST, and runtime scanning catches risks that single tools miss.”

What it is: Audit tooling covers lynis for hardening, rkhunter and chkrootkit for rootkits, nmap and ss for open ports, passwd inspection for UID 0 accounts, and aide or tripwire for file integrity.

Why it is used: Find weaknesses, backdoors and unauthorized changes before an attacker exploits them.

Terminal window
# Install audit tools
apt install lynis rkhunter chkrootkit
# Run Lynis
lynis audit system
lynis audit system --profile cis-ubuntu-22.04
# Run RKHunter
rkhunter --check
rkhunter --propupd
# Run CHKRootKit
chkrootkit
# Check open ports
nmap -sT -O localhost
ss -tulpn
# Check users
awk -F: '($3 == 0) {print $1}' /etc/passwd
lastlog
# Check logs
grep -i "failed password" /var/log/auth.log
grep -i "invalid user" /var/log/auth.log
# File integrity
aide --check
tripwire --check

Interview talking point: “ss -tulpn lists every listening socket together with its owning process in one command, and the awk filter over /etc/passwd catches any account granted UID 0 besides root.”

What it is: Lynis hardening runs audit tests such as AUTH-9262 and reports a hardening index you can track across runs.

Why it is used: To turn security recommendations into a repeatable, scheduled score.

Terminal window
# Install
apt install lynis
# Audit
lynis audit system
# Specific tests
lynis audit system --tests "AUTH-9262"
# Report
lynis show report
# Cron job
# /etc/cron.d/lynis
0 3 * * * root /usr/bin/lynis audit system --cronjob

Interview talking point: “lynis show report replays the previous run’s results, and a cron entry using —cronjob keeps the audit running nightly without any interaction.”

Q404: How do you configure system hardening scripts?

Section titled “Q404: How do you configure system hardening scripts?”

What it is: Lynis audits a host against hardening benchmarks with lynis audit system, while OpenSCAP evaluates a CIS XCCDF profile and writes results to an XML file.

Why it is used: To check a Linux host against CIS Benchmark standards and catch misconfiguration before an auditor does.

Terminal window
# CIS Benchmarks
# Use Lynis
lynis audit system
# Use OpenSCAP
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis \
--results scan-results.xml /usr/share/xml/scap/ssg/content/ssg-ubuntu2004-ds.xml
# Use CIS-CAT Pro

Interview talking point: “Both score you against a benchmark, but lynis audit system gives quick advisory findings while oscap xccdf eval yields structured XML you can later turn into a report.”

Q405: How do you implement system hardening?

Section titled “Q405: How do you implement system hardening?”

What it is: System hardening disables unused services and tightens kernel parameters, umask, USB storage and password policy in files like sysctl.conf and login.defs.

Why it is used: To shrink the attack surface of a server before it faces production traffic.

Terminal window
# Disable unnecessary services
systemctl mask avahi-daemon
systemctl mask cups
systemctl mask bluetooth
# Secure kernel parameters
# /etc/sysctl.conf
kernel.dmesg_restrict=1
kernel.kptr_restrict=2
kernel.yama.ptrace_scope=2
kernel.sysrq=0
# Disable IPv6 if not needed
net.ipv6.conf.all.disable_ipv6=1
net.ipv6.conf.default.disable_ipv6=1
# Disable USB storage
# /etc/modprobe.d/blacklist.conf
install usb-storage /bin/true
# Set secure umask
# /etc/profile
umask 027
# Password policies
# /etc/login.defs
PASS_MIN_LEN 12
PASS_MAX_DAYS 90

Interview talking point: “systemctl mask is stronger than disable because it makes the unit impossible to start, which suits avahi-daemon or cups you never want running, and kernel.dmesg_restrict blocks unprivileged dmesg reads.”

Q406: How do you optimize web application security?

Section titled “Q406: How do you optimize web application security?”

What it is: Web application hardening steps: deploy a WAF, set security headers, validate and sanitize input, and prevent SQL injection and XSS.

Why it is used: Blocks the most common web attacks before they reach application code.

Terminal window
# Web application security
# 1. WAF
# Deploy
# 2. Headers
# Security
# 3. Input validation
# Sanitization
# 4. SQL injection
# Prevention
# 5. XSS
# Protection

Interview talking point: “The WAF sits in front as a filter, while input validation and SQL injection and XSS prevention work inside the app. The outline uses both layers, since a WAF alone can be bypassed and code-level checks catch what passes through.”

Q407: How do you optimize web application security?

Section titled “Q407: How do you optimize web application security?”

What it is: Web application security optimization deploys WAF, configures security headers, applies input validation/sanitization, prevents SQL injection, and protects against XSS.

Why it is used: To defend against common web attacks at both edge and application layers.

Terminal window
# WAF
# Deploy
# Headers
# Security
# Input validation
# Sanitization
# SQL injection
# Prevention
# XSS
# Protection

Interview talking point: “Layered controls (WAF, headers, validation) reduce attack surface, with input sanitization being key for SQLi and XSS prevention.”

What it is: Server hardening covers patching, firewall rules, SELinux or AppArmor, disabling root login, SSH key auth, unused services, kernel tuning, audit logging, and encryption.

Why it is used: To shrink the attack surface of a production Linux host.

Terminal window
# Updates
# Regular patching
# Firewall
# Configure iptables/firewalld
# SELinux/AppArmor
# Enable and configure
# Users
# Disable root login
# SSH keys only
# Services
# Disable unused
# Network
# Harden kernel parameters
# Monitoring
# Enable audit logging
# Encryption
# Full disk encryption
# TLS everywhere

Interview talking point: “Disabling root login and requiring SSH keys removes password guessing entirely, and SELinux or AppArmor adds mandatory access control that file permissions alone cannot provide.”

What it is: Securing Linux means regular patching, an iptables or firewalld firewall, enabled SELinux or AppArmor, SSH key-only access with root login disabled, hardened kernel parameters, and audit logging.

Why it is used: To shrink the attack surface of servers hosting production workloads.

Terminal window
# Linux security
# 1. Updates
# Regular patching
# 2. Firewall
# iptables/firewalld
# 3. SELinux/AppArmor
# Enable and configure
# 4. Users
# Disable root login
# SSH keys only
# Strong passwords
# 5. Services
# Disable unused services
# 6. Network
# Harden kernel parameters
# Disable IP forwarding
# Rate limiting
# 7. Monitoring
# Audit logging
# IDS
# 8. Encryption
# Full disk encryption
# TLS everywhere

Interview talking point: “Disabling root login and requiring SSH keys ends password guessing, while mandatory access control like SELinux still confines a process even if it already runs as root.”

What it is: Database hardening removes anonymous and remote root accounts, creates an application user limited to SELECT, INSERT, UPDATE, DELETE on one database, flushes privileges, and adds SSL, firewall rules, and backups.

Why it is used: Limiting damage if an application account or host is compromised.

Terminal window
# MySQL security
# 1. Remove anonymous users
DELETE FROM mysql.user WHERE User='';
# 2. Remove remote root
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1');
# 3. Create application user
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strongpassword';
GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;
# 4. Use SSL for connections
# 5. Enable firewall for port 3306
# 6. Regular backups

Interview talking point: “Granting only the four statements an application actually uses beats broad privileges, and scoping the user to localhost keeps remote clients from reaching it, with FLUSH PRIVILEGES applying the account changes.”


Questions 101-200 continue with more advanced Linux topics…

What it is: Database hardening removes anonymous and remote root accounts, creates an application user with only SELECT, INSERT, UPDATE, and DELETE rights, and restricts PostgreSQL connections through pg_hba.conf host lines.

Why it is used: To limit blast radius so a compromised application only reaches its own database rights.

Terminal window
# MySQL
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1');
FLUSH PRIVILEGES;
# Create application user
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strongpassword';
GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'appuser'@'localhost';
# PostgreSQL
# pg_hba.conf
host all all 127.0.0.1/32 md5
host all all ::1/128 md5

Interview talking point: “Granting just the four DML verbs instead of ALL PRIVILEGES follows least privilege, and pg_hba.conf entries requiring md5 force password authentication over TCP. Access is matched per user and host, so appuser at localhost stays separate from any remote login.”


What it is: Securing LDAP means requiring TLS with a CA bundle and certificate validation, listening on ldaps as well as ldap, and writing access rules. Access statements decide who may read or write each part of the tree.

Why it is used: To protect directory credentials and data in transit and restrict what each bind DN can change.

/etc/ldap/ldap.conf
# TLS/SSL configuration
TLS_CACERT /etc/ssl/certs/ca-certificates.crt
TLS_REQCERT demand
# Enable TLS in slapd
# /etc/default/slapd
SLAPD_SERVICES="ldap://localhost/ ldap://localhost:7389/ ldaps://localhost:636/"
# Generate certificates
openssl req -new -x509 -nodes -days 365 \
-keyout /etc/ldap/tls/ldap.key \
-out /etc/ldap/tls/ldap.crt
# Restrict access
# /etc/ldap/slapd.conf
access to dn.base=""
by * read
access to *
by self write
by dn="cn=admin,dc=example,dc=com" write
by * read

Interview talking point: “Requiring a certificate demand makes the client reject unvalidated servers, and the access rules show the pattern: the admin DN gets write while everyone else is limited to read on the rest of the tree.”

Q413: How do you secure Linux system services?

Section titled “Q413: How do you secure Linux system services?”

What it is: Hardening services means disabling what you do not need and locking down what you keep. The record shows masking units, restricting SSH to keys and named users, and limiting cron and at with allow files.

Why it is used: To shrink the attack surface of a server before it faces a network.

Terminal window
# Disable unnecessary services
systemctl mask service_name
systemctl disable service_name
# View active services
systemctl list-units --type=service --state=running
# Secure SSH
# /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
X11Forwarding no
AllowUsers user1 user2
DenyUsers root
# Secure Cron
# /etc/cron.allow (only these users)
# /etc/cron.deny (deny these users)
# Secure at
# /etc/at.allow
# Secure system limits
# /etc/security/limits.conf
* hard maxlocks 100
* soft nproc 512

Interview talking point: “systemctl disable stops a unit starting at boot, while systemctl mask makes it impossible to start until unmasked, which is stronger for services that must never run.”

What it is: Service account security involves creating dedicated service accounts per application, limiting their RBAC permissions, and disabling automatic token mounting.

Why it is used: Properly scoped service accounts prevent overprivileged access and reduce the blast radius if a token or pod is compromised.

Terminal window
# Use dedicated service accounts
# Limit permissions
# Disable auto-mount of tokens
# Use RBAC
# Best practices
# Create SA per application
# Don't use default SA
# Rotate tokens regularly

Interview talking point: “Avoiding the default service account and disabling auto-mount of tokens ensures pods only have the minimal credentials they actually need.”

What it is: Defense in depth layers controls across network, application, data, identity, and monitoring, backed by compliance frameworks, audit logging, and data retention policies.

Why it is used: To make sure a single failed control does not become a full breach.

Terminal window
# Defense in depth
# 1. Network security
# - Firewalls
# - Network segmentation
# - VPN
# 2. Application security
# - Input validation
# - Output encoding
# - Parameterized queries
# - Security headers
# 3. Data security
# - Encryption at rest
# - Encryption in transit
# - Key management
# - Backup encryption
# 4. Identity and access
# - RBAC
# - MFA
# - Least privilege
# - Regular access review
# 5. Monitoring
# - SIEM
# - IDS/IPS
# - Vulnerability scanning
# - Penetration testing
# Compliance
# - GDPR, HIPAA, PCI-DSS
# - Audit logging
# - Data retention policies

Interview talking point: “The point is overlap: parameterized queries stop injection, RBAC limits blast radius, encryption protects stolen data, audit logs reveal what happened. No single layer is treated as sufficient on its own.”

Q416: How do you configure key management?

Section titled “Q416: How do you configure key management?”

What it is: HashiCorp Vault stores secrets, started here as a dev server, where vault kv put writes an API key under a path that applications then retrieve.

Why it is used: To keep secrets out of code and config, with centralized rotation and access history.

Terminal window
# HashiCorp Vault
vault server -dev
# Store secrets
vault kv put secret/myapp api_key=xxx
# Use in application
# Use kubernetes-secrets-injector or external-secrets-operator

Interview talking point: “Vault is a store with audit history, unlike a credential file, and injecting secrets into Kubernetes avoids committing them into manifests.”

Q417: How do you configure secrets management?

Section titled “Q417: How do you configure secrets management?”

What it is: Secrets backends include Vault over HTTPS, Kubernetes secrets created with kubectl, Sealed Secrets encrypted by kubeseal, and AWS Secrets Manager accessed with the aws CLI.

Why it is used: Keep credentials out of images and manifests while still granting applications controlled access.

Terminal window
# Using HashiCorp Vault
export VAULT_ADDR="https://vault.example.com:8200"
vault login -method=token token=<token>
# Kubernetes secrets
kubectl create secret generic mysecret \
--from-literal=username=admin \
--from-literal=password=secret
# Using Sealed Secrets
# Install controller
helm repo add sealed-secrets https://bitnami-labs.github.io/sealed-secrets
helm install sealed-secrets sealed-secrets/sealed-secrets
# Encrypt
kubeseal --format yaml < secret.yaml > sealed-secret.yaml
# AWS Secrets Manager
aws secretsmanager get-secret-value --secret-id mysecret
aws secretsmanager create-secret --name mysecret --secret-string '{"username":"admin","password":"secret"}'
# Use with CSI
kubectl apply -f secret-provider-class.yaml

Interview talking point: “Sealed Secrets invert the risk so ciphertext is safe to commit to git while only the cluster controller can decrypt; AWS Secrets Manager values are pulled at runtime with get-secret-value.”

Q418: How do you implement key management?

Section titled “Q418: How do you implement key management?”

What it is: Key management covers GPG keypairs for encryption, checksum files verified with sha256sum -c, HMAC signing with openssl, and the kernel keyring via keyctl.

Why it is used: To store, distribute, and verify secrets and integrity without leaking private material.

Terminal window
# Generate GPG key
gpg --full-generate-key
# Export public key
gpg --armor --export user@example.com > public.asc
# Import key
gpg --import public.asc
# Encrypt file
gpg -e -r user@example.com file.txt
# Decrypt file
gpg -d file.txt.gpg
# Hash verification
sha256sum file.tar.gz
sha256sum -c file.tar.gz.sha256
# HMAC
openssl dgst -sha256 -hmac "key" file.txt
# Use keyctl
keyctl add user mykey "my secret data" @u
keyctl list @u
keyctl pipe $(keyctl search @u user mykey)

Interview talking point: “sha256sum -c checks a stored checksum file in one step, and keyctl search followed by keyctl pipe retrieves key material without ever printing it to the terminal.”

What it is: A PKI workflow: generate a 4096-bit CA key, self-sign a CA certificate valid 3650 days, then create a 2048-bit server key, a CSR, and sign it for 365 days.

Why it is used: Establishes an internal certificate authority that issues trusted server certificates.

Terminal window
# Create CA
openssl genrsa -out ca.key 4096
openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -out ca.crt
# Issue certificate
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365 -sha256

Interview talking point: “The CA lives ten years while leaf certificates live one, so short-lived server certs can be reissued without ever rebuilding the trust anchor.”

Q420: How do you implement secret management?

Section titled “Q420: How do you implement secret management?”

What it is: Secret management with Vault: a kv engine stores secrets behind an API and the agent injector writes them into pods. Shown alternatives are AWS Secrets Manager and Kubernetes Secrets from literals.

Why it is used: To keep credentials out of source code and rotate them without redeploying.

Terminal window
# HashiCorp Vault
# Install
vault server -config=config.hcl
# Enable secrets engine
vault secrets enable -path=secret kv
# Write secret
vault kv put secret/myapp/db password=secretpassword
# Read secret
vault kv get secret/myapp/db
# Use with Kubernetes
# Install Vault Agent Injector
helm install vault hashicorp/vault \
--set "injector.enabled=true"
# Annotate pod
# metadata:
# annotations:
# vault.hashicorp.com/agent-inject: "true"
# vault.hashicorp.com/role: "myapp"
# vault.hashicorp.com/agent-inject-secret-db: "secret/data/myapp/db"
# Use in application
# Read from /vault/secrets/db file
# AWS Secrets Manager
aws secretsmanager create-secret \
--name myapp/db \
--secret-string '{"username":"admin","password":"secret"}'
# Kubernetes Secrets
kubectl create secret generic myapp-secrets \
--from-literal=username=admin \
--from-literal=password=secret

Interview talking point: “Kubernetes Secrets are only base64 encoded and live in etcd, so that is encoding rather than encryption. Vault injector writes secrets to files under /vault/secrets, keeping them out of environment variables.”

Q421: How do you implement secrets management?

Section titled “Q421: How do you implement secrets management?”

What it is: Secrets management with a dev-mode Vault server storing a key-value secret, an External Secrets Operator path for Kubernetes, and an AWS Secrets Manager secret created by CLI.

Why it is used: Keeps credentials out of code and controls access to them centrally.

Terminal window
# HashiCorp Vault
# Install
vault server -dev
# Store secret
vault kv put secret/myapp db_password=secret123
# Use in Kubernetes
# External Secrets Operator
# AWS Secrets Manager
aws secretsmanager create-secret --name myapp/db-password --secret-string '{"username":"admin","password":"secret"}'

Interview talking point: “vault server -dev holds data in memory and is unsealed, fine for a demo but unsuitable for production, which needs persistent storage and a sealed, unsealable server.”

Q422: How do you implement secrets management?

Section titled “Q422: How do you implement secrets management?”

What it is: Secrets management centralizes storage, access control, and rotation of sensitive credentials.

Why it is used: It reduces exposure risk compared to storing secrets in code or configs.

Terminal window
# Use Vault
# External secrets
# Rotate regularly
# Audit access
# Use encryption
# Short-lived tokens
# Best practices
# Use KMS

Interview talking point: “Tools like HashiCorp Vault, external secrets operators, KMS-backed encryption, short-lived tokens, and audit logging are industry standard.”

Q423: How do you implement secrets management?

Section titled “Q423: How do you implement secrets management?”

What it is: Secrets management centralizes credentials in a vault like HashiCorp Vault, encrypts them at rest, rotates them automatically, logs every access, and grants least-privilege access.

Why it is used: To have one auditable home for credentials instead of scattered config files.

Terminal window
# Secrets management
# 1. Centralized
# Vault
# 2. Rotation
# Auto
# 3. Audit
# Log access
# 4. Encryption
# Encrypt
# 5. Access control
# Least privilege

Interview talking point: “Rotation is the feature that limits blast radius, a leaked secret with automatic rotation has a short life, and access logging reveals whether it was ever used.”

Q424: How do you implement secrets management?

Section titled “Q424: How do you implement secrets management?”

What it is: Secrets management centralizes storage, access control, and rotation of sensitive credentials.

Why it is used: It prevents hardcoded secrets and reduces the risk of credential exposure.

Terminal window
# Centralized
# Vault
# Rotation
# Auto
# Audit
# Log access
# Encryption
# Encrypt
# Access control
# Least privilege

Interview talking point: “Automatic rotation with audit logging ensures secrets remain secure while providing traceability for access.”

Q425: How do you implement secrets rotation?

Section titled “Q425: How do you implement secrets rotation?”

What it is: Secrets rotation involves using tools like external-secrets-operator and key management services, rotating tokens regularly, and automating the process on a defined schedule.

Why it is used: Regular rotation limits the impact of leaked credentials by reducing their usable lifetime.

Terminal window
# Use external-secrets-operator
# Rotate regularly
# Use key management services
# Kubernetes
# Automatic token rotation
# Use short-lived tokens
# Best practice
# Rotate every 90 days
# Automate the process

Interview talking point: “Automating rotation is essential at scale, as manual processes are error-prone and often lead to expired or compromised credentials remaining in use.”

What it is: SOPS encrypts secret files so they can live in Git, using sops -e to encrypt and sops -d to decrypt. SealedSecrets and external-secrets are alternatives.

Why it is used: To version configuration including secrets without exposing plaintext credentials.

Terminal window
# Use SOPS
# Install
go install github.com/mozilla/sops@latest
# Encrypt
sops -e secrets.yaml > secrets.encrypted.yaml
# Decrypt
sops -d secrets.encrypted.yaml
# Or use SealedSecrets
# Or use external-secrets-operator

Interview talking point: “The encrypted file is committed like any other, so Git history records every change to secrets while the values stay unreadable without the encryption key.”

What it is: Ansible Vault encrypts whole YAML files behind a password, using create, encrypt, edit, view, and decrypt, plus rekey to change that password.

Why it is used: To keep secrets in version control alongside playbooks without exposing them.

Terminal window
# Create encrypted file
ansible-vault create secret.yml
# Encrypt existing file
ansible-vault encrypt secrets.yml
# Edit encrypted file
ansible-vault edit secrets.yml
# View encrypted file
ansible-vault view secrets.yml
# Decrypt file
ansible-vault decrypt secrets.yml
# Change password
ansible-vault rekey secret.yml
# Use in playbook
# playbook.yml
- hosts: all
vars_files:
- secrets.yml
tasks:
- name: Create user
user:
name: "{{ db_user }}"
password: "{{ db_password }}"
# Run with vault password
ansible-playbook site.yml --ask-vault-pass
# or
ansible-playbook site.yml --vault-password-file ~/.vault_pass.txt

Interview talking point: “A playbook loads an encrypted file through vars_files and runs with —ask-vault-pass or a vault password file when the job must be unattended.”

What it is: Docker secrets hold sensitive values. This creates one from stdin with docker secret create, lists and inspects them, and references the secret from compose either as external or from a file.

Why it is used: To deliver credentials to services without baking them into images or environment files.

Terminal window
# Create secret
echo "password" | docker secret create db_password -
# Use in service
docker secret ls
docker secret inspect db_password
# docker-compose.yml
secrets:
db_password:
external: true
# Or
secrets:
db_password:
file: ./db_password.txt

Interview talking point: “In compose, external true points at a secret already created in Docker, while a file source is read from disk at deploy time, so the two declare different origins.”

Q429: How do you use External Secrets Operator?

Section titled “Q429: How do you use External Secrets Operator?”

What it is: External Secrets Operator syncs external secrets into the cluster: a ClusterSecretStore points at AWS Secrets Manager and an ExternalSecret maps a remote key to a secret key.

Why it is used: To keep credentials out of Git and rotate them centrally without redeploying applications.

apiVersion: external-secrets.io/v1beta1
kind: ClusterSecretStore
metadata:
name: aws-secrets-manager
spec:
provider:
aws:
service: SecretsManager
region: us-east-1
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: myapp-secrets
spec:
refreshInterval: 1h
secretStoreRef:
name: aws-secrets-manager
kind: ClusterSecretStore
target:
name: myapp-secrets
data:
- secretKey: DB_PASSWORD
remoteRef:
key: myapp/db-password

Interview talking point: “refreshInterval 1h controls how often the operator rereads myapp/db-password from Secrets Manager, so a rotation on the AWS side lands in the myapp-secrets Kubernetes Secret within an hour without a restart.”

What it is: libvirt secrets store credentials referenced by UUID: secret-define registers the XML, secret-set-value sets the value, and a disk section can reference the secret as a passphrase.

Why it is used: Keeps passwords for disks or registries out of VM configuration files.

Terminal window
# Create secret
virsh secret-define secret.xml
# Set value
virsh secret-set-value UUID base64value
# Use in VM
# disk
<secret type='passphrase'>
<uuid>uuid</uuid>
</secret>

Interview talking point: “The guest XML carries only a UUID and never the secret itself, so configs stay shareable while the real value sits in libvirt’s store, set once through secret-set-value.”

Q431: How do you implement secrets encryption?

Section titled “Q431: How do you implement secrets encryption?”

What it is: Secrets encryption at rest is implemented by configuring the API server with an encryption-provider-config file that defines how Secret data is encrypted in etcd.

Why it is used: This prevents sensitive data like credentials from being stored in plaintext in etcd, protecting them if etcd is accessed directly.

encryption-config.yaml
apiVersion: v1
kind: Secret
metadata:
name: aes-key
data: <base64-key>
# Configure API server
# --encryption-provider-config=encryption-config.yaml
# Verify
# Check etcd directly
etcdctl get /registry/secrets/default/secret-name

Interview talking point: “Even with encrypted etcd storage, verifying the ciphertext directly with etcdctl confirms that secrets are actually encrypted rather than stored in plain text.”

What it is: Secrets management at scale involves using tools like Vault, external-secrets-operator, SealedSecrets, or AWS Secrets Manager with regular rotation, auditing, encryption, and short-lived tokens.

Why it is used: Centralized secret management reduces operational overhead while improving security through automated rotation and access control.

Terminal window
# Use Vault
# Use external-secrets-operator
# Use SealedSecrets
# Use AWS Secrets Manager
# Best practices
# Rotate regularly
# Audit access
# Use encryption
# Short-lived tokens

Interview talking point: “Short-lived tokens minimize exposure windows, and auditing access to secrets helps detect unauthorized usage across large clusters.”

What it is: age encrypts files simply, with keys produced by age-keygen, encryption protected by a passphrase with -p to a .age file, and decryption with -d using an identity key file with -i.

Why it is used: Fast, small-tool encryption for secrets and backups without GPG keyring complexity.

Terminal window
# Install
go install filippo.io/age/cmd/age@latest
# Generate keys
age-keygen
# Encrypt
age -p -o file.txt.age file.txt
# Decrypt
age -d -i key.txt file.txt.age

Interview talking point: “-i names the identity file used to decrypt, and the passphrase mode with -p involves no key pair at all, which is why it is handy for sharing a single secret.”

What it is: GPG provides public-key encryption and signing. You generate a key, encrypt to a recipient, decrypt, sign and verify files, list public and secret keys, and export or import keys.

Why it is used: To encrypt files for a recipient and to prove a file was signed by a known key.

Terminal window
# Generate key
gpg --full-generate-key
# Encrypt
gpg -e -r recipient@example.com file.txt
# Decrypt
gpg -d file.txt.gpg
# Sign
gpg -s file.txt
# Verify
gpg --verify file.txt.asc
# List keys
gpg --list-keys
gpg --list-secret-keys
# Export/Import
gpg --export -a > public.key
gpg --import public.key

Interview talking point: “-e needs a recipient while -d writes the decrypted result, and signing produces something gpg —verify checks against the sender’s key. gpg —export -a writes an ASCII armored public key, which is the form safe to publish and import elsewhere.”

What it is: GPG encryption creates a key pair with —full-generate-key, encrypts to a recipient with -e -r producing a .gpg file, decrypts with -d, and -c encrypts with a symmetric passphrase only.

Why it is used: Protect files for a specific person’s key, or quickly lock a file with just a password.

Terminal window
# Generate key
gpg --full-generate-key
# Encrypt
gpg -e -r recipient@example.com file.txt
# Decrypt
gpg -d file.txt.gpg
# Symmetric
gpg -c file.txt
gpg -o file.txt.gpg -c file.txt

Interview talking point: “-e -r binds the file to a public key so only the matching private key opens it, while -c uses one shared passphrase that anyone holding the password can decrypt.”

What it is: LinPEAS is a script that enumerates a Linux host for privilege escalation paths, printing findings in color-coded output.

Why it is used: To find misconfigurations and weak permissions during an authorized security assessment.

Terminal window
# Download
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh -o linpeas.sh
# Run
chmod +x linpeas.sh
./linpeas.sh
# Options
./linpeas.sh -s # stealth
./linpeas.sh -o # only interesting
./linpeas.sh -P # password spray

Interview talking point: “Beyond the default run, -o narrows output to interesting items, -s runs in stealth mode, and -P attempts a password spray against local accounts.”

Q437: How do you use linux-exploit-suggester?

Section titled “Q437: How do you use linux-exploit-suggester?”

What it is: linux-exploit-suggester compares the running kernel version against known local privilege escalation exploits and lists matching candidates.

Why it is used: To assess whether a kernel is exposed to publicly known exploits.

Terminal window
# Download
curl -L https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh -o les.sh
# Run
chmod +x les.sh
./les.sh
# With kernel version
./les.sh -k 5.4.0
# Show exploits only
./les.sh -p

Interview talking point: ”./les.sh -k 5.4.0 checks a specific kernel version and -p shows only exploit entries, so you get a short actionable list instead of general advice.”

What it is: nmap scans hosts for open ports with SYN, TCP connect, and UDP modes, plus version detection, OS detection, NSE scripts, and several output formats.

Why it is used: To inventory exposed services and find vulnerable hosts on a network.

Terminal window
# Install
apt install nmap
# Basic scan
nmap 192.168.1.1
# Scan types
nmap -sS 192.168.1.1 # SYN scan
nmap -sT 192.168.1.1 # TCP connect
nmap -sU 192.168.1.1 # UDP scan
nmap -sV 192.168.1.1 # Version detection
# OS detection
nmap -O 192.168.1.1
# Scripts
nmap -sC 192.168.1.1 # Default scripts
nmap --script=vuln 192.168.1.1
# Output
nmap -oA output 192.168.1.1 # All formats
nmap -oN output.nmap 192.168.1.1

Interview talking point: “-sS performs a half-open SYN scan while -sT completes the TCP handshake, and -oA writes normal, grepable, and XML output in one pass for tooling.”

Q439: How do you automate security updates?

Section titled “Q439: How do you automate security updates?”

What it is: unattended-upgrades on Debian and Ubuntu applies only security origins, supports a package blacklist and an automatic reboot at 02:00, enabled via dpkg-reconfigure, while yum-cron applies updates on RHEL systems.

Why it is used: To patch known vulnerabilities without a human running upgrades every day.

Terminal window
# Install unattended-upgrades (Debian/Ubuntu)
apt install unattended-upgrades
# Configure
# /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
};
Unattended-Upgrade::Package-blacklist {
"vim";
"apache2";
};
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";
# Enable
dpkg-reconfigure -plow unattended-upgrades
# RHEL/CentOS
yum install yum-cron
# /etc/yum/yum-cron.conf
apply_updates = yes
download_updates = yes
# Test
unattended-upgrades --dry-run --debug

Interview talking point: “Allowed-Origins limits automation to the security pocket, and a dry run with unattended-upgrades —dry-run —debug shows exactly what would change before you trust the schedule.”

Q440: How do you configure vulnerability scanning?

Section titled “Q440: How do you configure vulnerability scanning?”

What it is: OpenVAS scans targets after greenbone-nvt-sync refreshes its feed and openvasmd rebuilds the database, while Trivy scans container images or filesystems for known CVEs.

Why it is used: To find known vulnerabilities in packages, images and files before attackers exploit them.

Terminal window
# Use OpenVAS
# Install
apt install openvas
# Setup
greenbone-nvt-sync
openvasmd --rebuild
# Run scan
openvas -o scan-report.xml --target=target-id
# Or use Trivy
trivy image nginx:latest
trivy fs .

Interview talking point: “Trivy on an image and on the filesystem covers containers and code, whereas OpenVAS actively probes a running target using a synchronized vulnerability feed.”

What it is: Vulnerability management involves regularly scanning images and dependencies with tools like Trivy, Snyk, or Clair, patching quickly, automating updates, and quarantining vulnerable images.

Why it is used: Proactive scanning and rapid remediation reduce the window of exposure to known CVEs in container images and dependencies.

Terminal window
# Regular scanning
# Use Trivy, Snyk, Clair
# Patch quickly
# Automate updates
# Use base image scanning
# Scan dependencies
# Quarantine vulnerable images
# Use image policies

Interview talking point: “Integrating vulnerability scanning into CI pipelines with image policies prevents vulnerable artifacts from reaching production environments.”

Q442: How do you implement vulnerability management?

Section titled “Q442: How do you implement vulnerability management?”

What it is: A vulnerability management cycle: regular scanning, severity-based prioritization, remediation process, rescan verification, and metrics reporting.

Why it is used: Finds and fixes security weaknesses before attackers exploit them, with proof of closure.

Terminal window
# Vulnerability management
# 1. Scanning
# Regular
# 2. Prioritization
# Severity
# 3. Remediation
# Process
# 4. Verification
# Rescan
# 5. Reporting
# Metrics

Interview talking point: “Verification via rescan is what closes the loop; a ticket marked fixed without a rescan proves nothing. Severity prioritization also matters because teams cannot patch everything at once, so ranking drives the queue.”

Q443: How do you implement vulnerability management?

Section titled “Q443: How do you implement vulnerability management?”

What it is: Vulnerability management implementation includes regular scanning, severity-based prioritization, structured remediation, verification via rescan, and metrics reporting.

Why it is used: To identify and remediate security weaknesses before they are exploited.

Terminal window
# Scanning
# Regular
# Prioritization
# Severity
# Remediation
# Process
# Verification
# Rescan
# Reporting
# Metrics

Interview talking point: “Prioritizing by severity focuses effort on critical issues, while rescans and metrics track closure effectiveness over time.”

What it is: rsyslog is a syslog daemon configured to load UDP and TCP input modules on port 514, forward messages remotely, filter by program, and queue reliably.

Why it is used: To centralize and route machine logs to remote servers or per-program files.

/etc/rsyslog.conf
# Load modules
module(load="imudp")
module(load="imtcp")
# Input
input(type="imudp" port="514")
input(type="imtcp" port="514")
# Remote logging
*.* @@remote-host:514
# Filter
:programname, isequal, "nginx" /var/log/nginx.log
& ~
# Templates
$template RemoteLogs,"/var/log/%HOSTNAME%/%programname%.log"
*.* ?RemoteLogs
# Queue
$ActionQueueType LinkedList
$ActionQueueFileName remote-fwd
$ActionResumeRetryCount 3
$ActionQueueSaveOnShutdown on

Interview talking point: “The double at sign in the forwarding rule means TCP where a single one would be UDP, and the linked-list action queue keeps messages when the receiver is down.”

What it is: rsyslog.conf loads input modules for UDP and TCP on 514, defines a path template, forwards all messages to a remote host, and filters nginx into its own log.

Why it is used: To receive logs over the network, sort them into files, and forward everything to a central host.

/etc/rsyslog.conf
# Modules
$ModLoad imudp
$UDPServerRun 514
$ModLoad imtcp
$InputTCPServerRun 514
# Templates
$template RemoteLogs,"/var/log/%HOSTNAME%/%programname%.log"
# Forward
*.* @@remote-host:514
# Filter
:programname, isequal, "nginx" /var/log/nginx.log
& ~

Interview talking point: “The double at sign means TCP forwarding while a single one is UDP, and the ampersand tilde line after the nginx filter discards those messages so they are not written twice.”

What it is: rsyslog processes and forwards syslog messages: modules enable UDP and TCP listeners on 514, templates shape output paths, selectors route by facility or programname, a remote line sends everything to another host, and stop ends processing.

Why it is used: To centralize logs on a remote server and route messages into per-program files.

/etc/rsyslog.conf
# Modules
$ModLoad imudp
$UDPServerRun 514
$ModLoad imtcp
$InputTCPServerRun 514
# Templates
$template RemoteLogs,"/var/log/%HOSTNAME%/%PROGRAMNAME%.log"
$template DetailedLogs,"/var/log/%HOSTNAME%/%$year%/%$month%/%$day%/detail.log"
# Rules
# Log everything to remote server
*.* @@remote-server:514
# Local logging
*.info;mail.none;authpriv.none /var/log/messages
authpriv.* /var/log/secure
mail.* -/var/log/maillog
cron.* /var/log/cron
# Filter by program
:programname, isequal, "apache" /var/log/apache.log
# Stop processing
& stop

Interview talking point: “A double at in a remote selector means TCP forwarding while a single at means UDP, and the ampersand stop line keeps matched messages from also being written locally.”

Q447: How do you configure system logging?

Section titled “Q447: How do you configure system logging?”

What it is: An rsyslog configuration loading imuxsock and imjournal, defining a template that writes logs per hostname and program, and forwarding everything to a remote syslog host on port 514.

Why it is used: Centralizes logs by routing every message to a remote collector.

/etc/rsyslog.conf
# Module
$ModLoad imuxsock
$ModLoad imjournal
# Template
$template RemoteLogs,"/var/log/%HOSTNAME%/%PROGRAMNAME%.log"
# Forward all
*.* @@syslog.example.com:514

Interview talking point: “The double at sign before the hostname means TCP forwarding while a single at would mean UDP, which decides whether central log delivery survives packet loss.”

Q448: How do you configure system logging?

Section titled “Q448: How do you configure system logging?”

What it is: System logging combines rsyslog, which can listen on TCP and UDP 514 and forward with templates, with journald persistent storage and logrotate.

Why it is used: To collect, retain and forward service logs so incidents can be investigated later.

/etc/rsyslog.conf
# Configure rsyslog
$ModLoad imtcp
$InputTCPServerRun 514
$ModLoad imudp
$UDPServerRun 514
# Log templates
$template RemoteLogs,"/var/log/%HOSTNAME%/%PROGRAMNAME%.log"
*.* @@remote-server:514
# Configure journald
# /etc/systemd/journald.conf
[Journal]
Storage=persistent
Compress=yes
SystemMaxUse=500M
MaxRetentionSec=30day
# Forward to syslog
ForwardToSyslog=yes
# View logs
journalctl -u service
journalctl --since "1 hour ago"
journalctl -p err
# Log rotation
# /etc/logrotate.conf
daily
rotate 14
compress

Interview talking point: “journalctl —since narrows by time and -p err by priority, while journald ForwardToSyslog hands events to rsyslog, and logrotate settings like rotate 14 and compress keep fourteen daily archives.”

Q449: How do you implement log management?

Section titled “Q449: How do you implement log management?”

What it is: Filebeat tails log files and ships them to Logstash with host, docker and cloud metadata, logrotate rotates daily with compression and reloads the app, and a script greps errors.

Why it is used: Centralize logs for searching while keeping local disk usage bounded.

Terminal window
# Filebeat configuration
filebeat.inputs:
- type: log
paths:
- /var/log/*.log
- /var/log/*/*.log
fields:
type: syslog
fields_under_root: true
processors:
- add_host_metadata:
fields_under_root: true
- add_docker_metadata: ~
- add_cloud_metadata: ~
output.logstash:
hosts: ["logstash:5044"]
# Log rotation
# /etc/logrotate.d/myapp
/var/log/myapp/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 myapp myapp
postrotate
systemctl reload myapp > /dev/null 2>&1 || true
endscript
}
# Log analysis script
analyze_logs() {
local logfile="$1"
# Error count
echo "Errors: $(grep -c ERROR "$logfile")"
# Top errors
echo "Top errors:"
grep ERROR "$logfile" | cut -d: -f4- | sort | uniq -c | sort -rn | head -10
# Time distribution
echo "Time distribution:"
awk '/ERROR/ {print $2}' "$logfile" | cut -d: -h1 | sort | uniq -c
}

Interview talking point: “delaycompress leaves the newest rotated file uncompressed so the app can finish reopening logs, and the postrotate reload is what prevents lines being lost right after rotation.”

What it is: rsyslog reads /etc/rsyslog.conf where rules route facilities to files: .info goes to /var/log/messages, authpriv. to /var/log/secure, and a programname rule can divert one application’s output.

Why it is used: To split logs by severity or application so incidents are easier to investigate.

Terminal window
# Rsyslog config
cat /etc/rsyslog.conf
# Rules
*.info;mail.none;authpriv.none /var/log/messages
authpriv.* /var/log/secure
# Filter by facility
:programname, isequal, "nginx" /var/log/nginx.log
& ~

Interview talking point: “the trailing tilde after a programname rule stops those messages there so they are not also written to default files, because rsyslog stops at the first matching rule.”

Q451: How do you configure secure logging?

Section titled “Q451: How do you configure secure logging?”

What it is: A syslog-ng config with a system source, an auth and authpriv facility filter, and a file destination, chained so those messages land in /var/log/secure.

Why it is used: Isolates authentication events into a dedicated log for review.

/etc/syslog-ng/syslog-ng.conf
# Use syslog-ng
source s_system { system(); };
destination d_secure { file("/var/log/secure"); };
filter f_secure { facility(auth, authpriv); };
log { source(s_system); filter(f_secure); destination(d_secure); };

Interview talking point: “syslog-ng expresses routing as a log pipeline of source, filter, and destination, whereas the rsyslog example used a wildcard rule with a template to achieve separation.”

What it is: journald.conf under [Journal] sets journal storage limits, rotation, compression, and syslog forwarding. Restarting systemd-journald applies the new settings.

Why it is used: To cap how much disk the journal eats and to hand entries to an existing syslog pipeline.

/etc/systemd/journald.conf
[Journal]
SystemMaxUse=500M
SystemKeepFree=100M
RuntimeMaxUse=200M
RuntimeKeepFree=50M
MaxFileSec=1month
ForwardToSyslog=yes
Compress=yes
# Reload
systemctl restart systemd-journald

Interview talking point: “SystemMaxUse caps persistent journal storage while SystemKeepFree keeps free space reserved, and RuntimeMaxUse covers the volatile /run journal, so changes only take effect after systemctl restart systemd-journald.”

What it is: journald is systemd’s log service: journald.conf sets persistent or volatile storage, compression, size caps, retention, forwarding to syslog, and rate limits; journalctl queries by unit, time, priority, and follow, and creating /var/log/journal makes storage persistent.

Why it is used: To keep system logs across reboots with fast unit-scoped queries.

/etc/systemd/journald.conf
[Journal]
Storage=persistent
Compress=yes
SystemMaxUse=500M
SystemMaxFileSize=50M
MaxRetentionSec=30day
# Forward to syslog
ForwardToSyslog=yes
ForwardToKMsg=no
ForwardToWall=no
# Rate limiting
RateLimitIntervalSec=30s
RateLimitBurst=1000
# View logs
journalctl
journalctl -u nginx
journalctl --since "2024-01-01"
journalctl --since "1 hour ago"
journalctl -p err
journalctl -f
# Persistent storage
mkdir -p /var/log/journal
systemd-tmpfiles --create --prefix /var/log/journal

Interview talking point: “Without /var/log/journal the journal is volatile and lost at reboot, and RateLimitBurst means a runaway service can silently drop messages rather than fill the disk.”

What it is: A logrotate rule under /etc/logrotate.d rotates logs daily, keeps 14 compressed copies, delays compression, skips empty files, recreates the file with set permissions, and reloads nginx from a postrotate script.

Why it is used: To stop logs from filling disks while still keeping recent history.

Terminal window
# Logrotate config
cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
systemctl reload nginx > /dev/null
endscript
}

Interview talking point: “delaycompress leaves the freshly rotated file uncompressed until the next cycle so the running daemon can keep writing, and postrotate reloads the service so it reopens the new log file.”

What it is: logrotate rotates, compresses, and deletes old logs: global settings set daily rotation and retention, per-service files under /etc/logrotate.d add specifics like postrotate scripts, and -d dry-runs while -f forces an immediate rotation.

Why it is used: To stop logs from filling filesystems while keeping recent history.

/etc/logrotate.conf
# Global settings
daily
rotate 14
compress
delaycompress
missingok
notifempty
create 0640 root adm
# Include configs
include /etc/logrotate.d/
# Specific config
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
invoke-rc.d nginx rotate >/dev/null 2>&1
endscript
}
# Test
logrotate -d /etc/logrotate.conf
logrotate -f /etc/logrotate.d/nginx

Interview talking point: “delaycompress leaves the newest rotated file uncompressed for one cycle so daemons still writing to it do not break, and logrotate -d shows the plan without touching files.”

Q456: How do you configure log retention policies?

Section titled “Q456: How do you configure log retention policies?”

What it is: logrotate rotates myapp logs daily, keeps 90 copies, compresses with a delayed pass and recreates files as 0640, while journald caps itself with SystemMaxUse and MaxFileSec.

Why it is used: To stop logs filling the disk by rotating, compressing and expiring them on a schedule.

/etc/logrotate.d/myapp
# logrotate
/var/log/myapp/*.log {
daily
rotate 90
compress
delaycompress
missingok
create 0640 user group
}
# Or with systemd
# journald.conf
SystemMaxUse=500M
MaxFileSec=1month

Interview talking point: “delaycompress holds back compressing the just rotated file for one cycle, so the most recent rotated log stays directly readable by tools and people.”

What it is: This logrotate stanza rotates nginx logs daily, keeps 14 copies, compresses them with a delay, creates a fresh file with set ownership, and signals nginx in postrotate.

Why it is used: To rotate, compress, and recreate application logs on a schedule without losing or duplicating data.

/etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}

Interview talking point: “delaycompress leaves the newest rotated file uncompressed so the USR1 reopen in postrotate keeps writing cleanly, and sharedscripts runs that signal once per run instead of once per log file.”

What it is: logrotate rotates logs on a schedule with directives for cadence, rotation count, compression with delay, new file permissions, and a postrotate script.

Why it is used: To keep logs from filling disks while preserving recent history.

/etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
# Manual run
logrotate -f /etc/logrotate.conf
logrotate -d /etc/logrotate.conf # debug

Interview talking point: “The postrotate signal tells nginx to reopen its logs so it stops writing to the rotated file, and the d option runs the config in debug mode without changing anything.”

What it is: tail -f follows a growing log file live, /var/log/messages or syslog hold system events, auth.log or secure hold login events, and journalctl queries the systemd journal.

Why it is used: To watch a service in real time and trace a failure as it happens.

Terminal window
# System logs
tail -f /var/log/messages
tail -f /var/log/syslog
# Auth logs
tail -f /var/log/auth.log
tail -f /var/log/secure
# Application logs
tail -f /var/log/nginx/access.log
# Journal
journalctl
journalctl -u service
journalctl -f

Interview talking point: “tail -f streams one specific file while journalctl -f follows the whole journal, and journalctl -u service narrows the output down to a single unit.”

Q460: How do you analyze logs efficiently?

Section titled “Q460: How do you analyze logs efficiently?”

What it is: grep finds and counts matching lines, awk can tally ERROR occurrences, and a chain of awk, sort, uniq -c, and sort -rn ranks the most frequent field values in an access log.

Why it is used: To turn large logs into counts, top offenders, and time-window slices.

Terminal window
# Grep patterns
grep ERROR /var/log/messages
grep -c "pattern" file
# Awk analysis
awk '/ERROR/ {count++} END {print count}' file
# Sort and count
awk '{print $5}' access.log | sort | uniq -c | sort -rn
# Time-based
awk '$4 >= "[10/Oct/2023:10:00"' access.log

Interview talking point: “the pipeline of awk printing a field, sort, uniq -c, then sort -rn is the standard way to rank values by frequency, and uniq -c only works once sort has grouped identical lines.”

Q461: How do you analyze logs efficiently?

Section titled “Q461: How do you analyze logs efficiently?”

What it is: Efficient log analysis: grep filters and excludes lines, awk prints chosen fields or counts the last field, cut extracts columns for uniq counts, and tools like GoAccess and lnav produce reports or browse multiple logs together.

Why it is used: To extract errors, status codes, and traffic patterns from large log files.

Terminal window
# Using grep
grep -i error /var/log/syslog | head -20
grep -v "INFO" /var/log/app.log
# Using awk
awk '/ERROR/ {print $1, $5}' /var/log/app.log
awk '{print $NF}' /var/log/access.log | sort | uniq -c | sort -rn
# Using cut
cut -d' ' -f1 /var/log/access.log | sort | uniq -c
# Using logrotate with logwatch
apt install logwatch
# Using GoAccess
goaccess /var/log/nginx/access.log -o /var/www/html/report.html
# Using lnav
lnav /var/log/syslog
lnav /var/log/*.log

Interview talking point: “The pipeline of sort, uniq -c, then sort -rn ranks the most frequent values, turning an access log into a top-requests list in one pass.”

What it is: ELK runs Elasticsearch for storage, Kibana for querying, Logstash for parsing with grok, and Filebeat shipping log files into that pipeline.

Why it is used: To search, filter, and visualize application and system logs at scale.

Terminal window
# Install Elasticsearch
docker run -d -p 9200:9200 elasticsearch:7
# Install Kibana
docker run -d -p 5601:5601 kibana:7
# Install Logstash
docker run -d -p 5044:5044 logstash:7 -f /etc/logstash/conf.d/
# Filebeat configuration
filebeat.inputs:
- type: log
paths:
- /var/log/*.log
output.logstash:
hosts: ["localhost:5044"]
# Ingest pipeline
input {
beats {
port => 5044
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}" }
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
}
}

Interview talking point: “Filebeat ships and Logstash parses with grok patterns before Elasticsearch indexes it, so structure is applied in flight rather than being guessed at query time.”

What it is: Log analysis gathers logs in ELK or Loki, prefers JSON for queryable fields, applies levels from DEBUG to CRITICAL, and uses grep and awk for quick searches and slow-request extraction.

Why it is used: To turn raw log files into answers about errors, volume, and slow requests.

Terminal window
# Log analysis
# ELK Stack
# Elasticsearch
# Logstash
# Kibana
# Loki
# Grafana + Loki
# Structured logging
# JSON format
import json
import logging
class JSONFormatter(logging.Formatter):
def format(self, record):
return json.dumps({
'timestamp': self.formatTime(record),
'level': record.levelname,
'message': record.getMessage(),
'module': record.module
})
# Log levels
# DEBUG - Detailed info
# INFO - Confirmation
# WARNING - Something unexpected
# ERROR - Serious problem
# CRITICAL - Very serious problem
# Analysis queries
# Find errors
grep -i error /var/log/app.log
# Count by hour
awk '{print $2}' /var/log/app.log | sort | uniq -c
# Slow requests
awk '$9 > 5 {print}' /var/log/nginx/access.log

Interview talking point: “awk on the ninth field of an nginx access log filters requests by response time or status, which grep cannot do by position. Structured JSON makes the same question a field lookup instead.”

What it is: Logging emits structured JSON at defined levels, attaches trace IDs for correlation, rotates files with logrotate, aggregates into ELK or Loki, and applies a retention policy.

Why it is used: To keep application events searchable while preventing logs from filling the disk.

Terminal window
# Logging implementation
# 1. Format
# JSON
# Structured
# 2. Levels
# DEBUG, INFO, WARN, ERROR
# 3. Correlation
# Trace IDs
# 4. Rotation
# Logrotate
# 5. Aggregation
# ELK/Loki
# 6. Retention
# Policy

Interview talking point: “Rotation is what stops log growth from exhausting the disk, and structured JSON lets aggregation tools index fields instead of parsing free-form text with regex.”

What it is: Logging is the systematic recording of events, errors, and state changes in a structured format.

Why it is used: It helps with troubleshooting, auditing, and detecting issues in distributed systems.

Terminal window
# Format
# JSON
# Structured
# Levels
# DEBUG, INFO, WARN, ERROR
# Correlation
# Trace IDs
# Rotation
# Logrotate
# Aggregation
# ELK/Loki
# Retention
# Policy

Interview talking point: “Structured JSON logs with correlation IDs make it easier to trace a single request across multiple services.”

Q466: How do you set up centralized logging?

Section titled “Q466: How do you set up centralized logging?”

What it is: rsyslog runs as a server accepting TCP input on port 514 while clients forward all facilities and priorities to it; ELK is the alternative pipeline ending in Kibana.

Why it is used: To ship logs from many hosts to one place so they survive host loss and can be searched centrally.

Terminal window
# Using rsyslog
# Server
$ModLoad imtcp
$InputTCPServerRun 514
# Client
*.* @@logging-server:514
# Or ELK stack
# Filebeat -> Logstash -> Elasticsearch -> Kibana

Interview talking point: “The client rule ends with a double at sign, which means TCP forwarding, while a single at sign would mean UDP, so the number of at signs sets the protocol.”

What it is: Three log analysis approaches: GoAccess producing a real-time HTML report from an nginx access log, a Splunk forwarder, and Filebeat with nginx and system modules enabled.

Why it is used: Converts raw logs into reports or ships them to a central search platform.

Terminal window
# GoAccess
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html
# Splunk forwarder
# Install and configure
/opt/splunkforwarder/bin/splunk start
# ELK
filebeat modules enable nginx
filebeat modules enable system

Interview talking point: “Filebeat modules enable parsed fields for nginx automatically, while GoAccess writes a report straight from the file, so the choice is live central search versus a local report.”

What it is: Centralizing means shipping all hosts’ logs to one place: rsyslog forwarding over TCP to a server, or agents feeding Elasticsearch through Logstash, or Promtail feeding Loki for Grafana.

Why it is used: To gather every host’s logs in one place for searching and dashboards during incidents.

Terminal window
# Using rsyslog
# Server
$ModLoad imtcp
$InputTCPServerRun 514
# Client
*.* @@server:514
# Or using ELK
# Filebeat -> Logstash -> Elasticsearch -> Kibana
# Or using Loki
# Promtail -> Loki -> Grafana

Interview talking point: “The rsyslog route streams raw lines to a central box, while the ELK and Loki pipelines let agents label and index logs so you can search and chart them centrally.”

What it is: Centralized logging with the Elastic stack: Filebeat on clients tails log files and ships them to Logstash over port 5044, where a grok filter parses the syslog pattern and a date filter normalizes timestamps.

Why it is used: To collect logs from many hosts into one searchable place.

/etc/filebeat/filebeat.yml
# ELK Stack
# Filebeat on clients
filebeat.inputs:
- type: log
paths:
- /var/log/*.log
fields:
type: syslog
output.logstash:
hosts: ["logstash:5044"]
# Logstash config
# /etc/logstash/conf.d/01-input.conf
input {
beats {
port => 5044
}
}
# Filter
filter {
if [type] == "syslog" {
grok {
match => { "message" => "%{SYSLOGTIMESTAMP:syslog_timestamp} %{SYSLOGHOST:syslog_hostname} %{DATA:syslog_program}(?:\[%{POSINT:syslog_pid}\])?: %{GREEDYDATA:syslog_message}" }
}
date {
match => [ "syslog_timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss" ]
}
}
}

Interview talking point: “grok turns an unstructured message into named fields, and without the date match the indexed timestamp would default to ingest time, wrecking historical searches.”

What it is: Graylog centralizes logs with inputs such as GELF UDP, a sidecar collector running on hosts, and Filebeat shipping file paths with added fields.

Why it is used: To aggregate logs from many servers into one searchable web interface.

Terminal window
# Install Graylog
# Using OVA or AMI
# Configure inputs
# Web UI -> System -> Inputs -> GELF UDP
# Configure sidecar
apt install graylog-sidecar
graylog-sidecar -c /etc/graylog/sidecar/sidecar.yml
# Filebeat configuration
filebeat.inputs:
- type: log
paths:
- /var/log/syslog
fields:
type: syslog
fields_under_root: true

Interview talking point: “The sidecar runs on each host but receives its collector configuration from the server, so Filebeat inputs are managed centrally instead of edited on every machine.”

Q471: How do you configure log aggregation?

Section titled “Q471: How do you configure log aggregation?”

What it is: Filebeat tails log files and ships them to Logstash on port 5044, where a grok filter parses syslog lines into timestamp, hostname, program, and message fields.

Why it is used: To collect logs from many hosts and parse them into searchable structured fields centrally.

/etc/filebeat/filebeat.yml
# Filebeat configuration
filebeat.inputs:
- type: log
paths:
- /var/log/syslog
- /var/log/auth.log
fields:
type: syslog
fields_under_root: true
- type: log
paths:
- /var/log/nginx/*.log
fields:
type: nginx
fields_under_root: true
output.logstash:
hosts: ["logstash:5044"]
processors:
- add_host_metadata:
fields_under_root: true
- add_docker_metadata: ~
# Logstash pipeline
# /etc/logstash/conf.d/01-input.conf
input {
beats {
port => 5044
}
}
# /etc/logstash/conf.d/02-filter.conf
filter {
if [type] == "syslog" {
grok {
match => { "message" => "%{SYSLOGTIMESTAMP:timestamp} %{SYSLOGHOST:hostname} %{DATA:program}(?:\[%{POSINT:pid}\])?: %{GREEDYDATA:message}" }
}
date {
match => [ "timestamp", "MMM dd HH:mm:ss" ]
}
}
}

Interview talking point: “fields_under_root places the type tag at the top level, which is exactly what the Logstash filter condition on type equals syslog keys on, so misplacing it silently skips parsing.”

What it is: The ELK stack combines Elasticsearch on 9200, Kibana on 5601, and Logstash on 5044, with Filebeat on clients shipping system logs to Logstash.

Why it is used: Centralized log aggregation, search, and analysis across servers.

Terminal window
# Install Elasticsearch
docker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch
# Install Kibana
docker run -d -p 5601:5601 kibana
# Install Logstash
docker run -d -p 5044:5044 logstash
# Configure filebeat on clients
filebeat.modules:
- system
output.logstash:
hosts: ["logstash:5044"]

Interview talking point: “Filebeat output.logstash points clients at Logstash instead of Elasticsearch directly, so parsing and fan-in happen in one tier and every machine only needs a lightweight shipper.”


What it is: The ELK stack combines Elasticsearch for storage and search, Logstash for processing, and Kibana for visualization. Filebeat ships log files from disk into the pipeline, here targeting Logstash on port 5044.

Why it is used: To centralize logs from many machines so they can be searched and analyzed in one place.

Terminal window
# Install Elasticsearch
apt install elasticsearch
systemctl enable elasticsearch
# Configure
# /etc/elasticsearch/elasticsearch.yml
cluster.name: mycluster
network.host: 0.0.0.0
discovery.type: single-node
# Install Kibana
apt install kibana
# Install Logstash
apt install logstash
# Filebeat configuration
# /etc/filebeat/filebeat.yml
filebeat.inputs:
- type: log
paths:
- /var/log/*.log
output.logstash:
hosts: ["localhost:5044"]

Interview talking point: “Filebeat is configured as an input rather than Logstash tailing files itself, and the single-node discovery setting keeps Elasticsearch from waiting for cluster peers that will never join.”

What it is: Analog reads a plain config naming the logfile, the output HTML file, and the hostname, then writes the report to that output path.

Why it is used: To produce a lightweight static traffic report straight from an access log.

Terminal window
# Install
apt install analog
# Configure
# /etc/analog.cfg
LOGFILE /var/log/apache2/access.log
OUTFILE /var/www/html/analog.html
HOSTNAME myserver.com

Interview talking point: “Analog is driven entirely by its config file for input and output paths, so regenerating a report is just re-running it with no database behind it.”

What it is: AWStats has a per-site config with site name, log file, and data directory; updateall.pl refreshes stored data and the awstats command renders static HTML output.

Why it is used: To generate detailed historical web analytics from Apache logs on a schedule.

Terminal window
# Install
apt install awstats
# Configure
# /etc/awstats/awstats.mysite.conf
SiteName="mysite.com"
LogFile="/var/log/apache2/access.log"
DirData="/var/lib/awstats"
# Generate
awstats_updateall.pl now
awstats -config=mysite -output -staticlinks > /var/www/html/awstats.html

Interview talking point: “AWStats keeps parsed data in DirData, so awstats_updateall.pl does the actual parsing and the second command only renders that stored data into static HTML.”

What it is: Elastic APM Server runs as a container listening on port 8200, configured through environment variables naming the Elasticsearch hosts and Kibana host it talks to.

Why it is used: To collect application performance data and ship it into Elasticsearch for viewing in Kibana.

Terminal window
# Install
docker run -d --name apm-server \
--user=apm-server \
-p 8200:8200 \
-e ELASTICSEARCH_HOSTS=elasticsearch:9200 \
-e OUTPUT_LOGSTASH_INTERNAL=true \
-e KIBANA_HOST=kibana:5601 \
docker.elastic.co/apm/apm-server:latest

Interview talking point: “The container maps 8200:8200 as the intake port and points at Elasticsearch and Kibana purely through ELASTICSEARCH_HOSTS and KIBANA_HOST environment variables, so a topology change needs no image rebuild.”

What it is: Elasticsearch runs as a container exposing 9200 and 9300, then you PUT an index, POST a document into it, and GET _search to query it over HTTP.

Why it is used: To store and query indexed documents through a simple REST API.

Terminal window
# Install
docker run -d -p 9200:9200 -p 9300:9300 elasticsearch
# Create index
curl -X PUT "localhost:9200/myindex"
# Add document
curl -X POST "localhost:9200/myindex/_doc" -H 'Content-Type: application/json' -d'{"field":"value"}'
# Search
curl -X GET "localhost:9200/myindex/_search"

Interview talking point: “9200 is the HTTP port used by every curl call here while 9300 is the transport port, and PUT creates the index idempotently whereas POST adds a new document.”

What it is: The ELK stack pairs Elasticsearch for storage and search, Kibana for UI, and Logstash for parsing. Filebeat ships log files from clients into Logstash on port 5044.

Why it is used: To centralize logs from many hosts so they are searchable in one place.

Terminal window
# Elasticsearch
docker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7
# Kibana
docker run -d -p 5601:5601 kibana:7
# Logstash
docker run -d -p 5044:5044 -v /etc/logstash/conf.d:/usr/share/logstash/pipeline logstash:7
# Filebeat (on clients)
filebeat.inputs:
- type: log
paths:
- /var/log/*.log
output.logstash:
hosts: ["logstash:5044"]

Interview talking point: “Filebeat forwards to Logstash rather than straight to Elasticsearch, which gives a place to parse and filter before indexing. Elasticsearch runs as single-node here for a lab, and Kibana on 5601 is the interface over the data on 9200.”

What it is: The ELK setup installs Elasticsearch for storage, Kibana for the search UI, Logstash as a pipeline, and Filebeat to tail log files.

Why it is used: To centralize server logs so they are searchable across the whole fleet.

Terminal window
# Install Elasticsearch
apt install elasticsearch
# Configure
# /etc/elasticsearch/elasticsearch.yml
cluster.name: mycluster
network.host: 0.0.0.0
# Install Kibana
apt install kibana
# /etc/kibana/kibana.yml
# server.host: "0.0.0.0"
# Install Logstash
apt install logstash
# Configure Filebeat
apt install filebeat
# /etc/filebeat/filebeat.yml
filebeat.inputs:
- type: log
paths:
- /var/log/*.log
output.logstash:
hosts: ["localhost:5044"]

Interview talking point: “Filebeat tails /var/log/*.log and ships to Logstash on port 5044, Elasticsearch indexes it, and Kibana presents the search interface on top.”

What it is: You pull logs from S3 with aws s3 cp, then run GoAccess over the glob of log files with -a for all fields, optionally adding a GeoIP database.

Why it is used: To analyze archived access logs stored in S3 without running a server.

Terminal window
# Download logs
aws s3 cp s3://bucket/logs/ ./logs/
# Analyze
goaccess access.log*.log -a -o report.html
# With GeoIP
goaccess access.log -a -o report.html --geoip-database=GeoLite2-City.mmdb

Interview talking point: “GoAccess accepts a glob of rotated log files so a whole day of S3 objects becomes a single report, and the GeoIP option is what adds the city-level column.”

What it is: GoAccess parses an nginx access log into an HTML report, and with —real-time-html it writes the report into the web root and keeps it updating.

Why it is used: To turn access logs into browsable traffic reports quickly.

Terminal window
# Install
apt install goaccess
# Real-time
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html
# Generate static
goaccess /var/log/nginx/access.log -o report.html

Interview talking point: “With —real-time-html the report keeps re-reading the log and refreshing in the browser, while leaving that option off simply freezes a one-time static HTML snapshot.”

What it is: Kibana runs on port 5601, connects to Elasticsearch indices from Settings, and from there you build visualizations and assemble them into dashboards.

Why it is used: To search logs and build visualizations and dashboards on top of stored indices.

Terminal window
# Install
docker run -d -p 5601:5601 kibana
# Connect to Elasticsearch
# Kibana -> Settings -> Indices
# Create visualization
# Visualize -> Create new
# Create dashboard
# Dashboard -> Create new

Interview talking point: “Kibana stores no data of its own, so choosing the index pattern first in Settings and Indices is what makes searching, visualizing, and dashboarding possible at all.”

What it is: Loki runs on 3100 and Promtail scrapes files matched by a path, attaching labels like job before pushing them to the Loki push API endpoint.

Why it is used: To collect log files and push them into Loki for label-based querying.

Terminal window
# Install
docker run -d -p 3100:3100 grafana/loki
# Configure Promtail
# /etc/promtail/promtail.yaml
server:
http_listen_port: 9080
grpc_listen_port: 0
clients:
- url: http://loki:3100/api/prom/push
scrape_configs:
- job_name: system
static_configs:
- targets: [localhost]
labels:
job: varlogs
__path__: /var/log/*.log

Interview talking point: “Promtail tails the files listed under the path key and adds labels before pushing, and those labels rather than full-text indexing are what queries and dashboards group on.”

What it is: Loki is a log aggregation system configured via Helm, using boltdb-shipper for its index, S3 for objects, and a 24 hour index period with a set prefix.

Why it is used: To query logs cheaply by indexing labels while log data itself sits in object storage.

# Helm
loki:
auth_enabled: false
schema_config:
configs:
- from: 2022-01-01
store: boltdb-shipper
object_store: s3
schema: v11
index:
prefix: loki_index_
period: 24h

Interview talking point: “Loki indexes only labels while the log data goes to object_store s3, and index period 24h bounds index growth — that split is why Loki stays far cheaper than a full-text search cluster.”

What it is: Matomo runs in Docker with mounted application and database volumes, and pages load a tracking snippet that pushes page views and link tracking to matomo.php.

Why it is used: To run self-hosted web analytics you control the data for.

Terminal window
# Install via Docker
docker run -d -p 8080:80 \
-v /opt/matomo:/var/www/html \
-v /opt/matomo:/var/lib/mysql \
matomo
# Configure web server
# Add tracking code to pages
<script>
var _paq = window._paq = window._paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//matomo.example.com/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '1']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>

Interview talking point: “Unlike a log-file analyzer, Matomo depends on the in-page JavaScript snippet, so visits from clients that block that script never appear in the reports.”

What it is: The Splunk universal forwarder monitors files listed in inputs.conf and forwards them to an indexer set in outputs.conf, running as a boot-started service.

Why it is used: To ship logs to a central Splunk server for search and alerting.

Terminal window
# Install
dpkg -i splunkforwarder-latest.deb
# Start
/opt/splunkforwarder/bin/splunk start --accept-license
# Configure inputs
cat /opt/splunkforwarder/etc/system/local/inputs.conf
[monitor:///var/log/syslog]
sourcetype = syslog
# Configure outputs
cat /opt/splunkforwarder/etc/system/local/outputs.conf
[tcpout:default-autolb-group]
server = splunk-server:9997
# Enable boot start
/opt/splunkforwarder/bin/splunk enable boot-start

Interview talking point: “inputs.conf declares what to monitor with a sourcetype while outputs.conf points at the server on port 9997, cleanly separating collection from routing.”


Q487: How do you configure network monitoring?

Section titled “Q487: How do you configure network monitoring?”

What it is: These are live network monitoring tools: nethogs shows bandwidth per process on an interface, iftop shows flows between hosts, bmon graphs rates, iptraf-ng gives interface statistics, and vnstat reports interface traffic totals.

Why it is used: To find what or who is using the network when throughput spikes or a link saturates.

Terminal window
# Using nethogs
apt install nethogs
nethogs eth0
# Using iftop
apt install iftop
iftop
# Using bmon
apt install bmon
bmon
# Using iptraf-ng
apt install iptraf-ng
iptraf-ng
# Using vnstat
apt install vnstat
vnstat -l -i eth0

Interview talking point: “Choosing among them depends on the question: iftop for which hosts are talking, nethogs for which process owns the traffic, bmon for a rate graph, and vnstat -l -i eth0 scoped to one named interface.”

Q488: How do you configure network monitoring?

Section titled “Q488: How do you configure network monitoring?”

What it is: Blackbox exporter probes endpoints on port 9110, and Prometheus scrapes its /probe path with targets such as https://example.com using an http_2xx module.

Why it is used: To monitor uptime and response codes of external services from the monitoring system’s point of view.

Terminal window
# Use Prometheus + blackbox exporter
docker run -d -p 9115:9110 prom/blackbox-exporter
# Configure
# /etc/blackbox/blackbox.yml
modules:
http_2xx:
prober: http
# Prometheus scrape
- job_name: blackbox
metrics_path: /probe
static_configs:
- targets:
- https://example.com

Interview talking point: “Blackbox works by Prometheus calling /probe and passing a target, inverting the usual scrape, because the exporter has to be told what to check on each request.”

Q489: How do you implement application monitoring?

Section titled “Q489: How do you implement application monitoring?”

What it is: Application monitoring combines Jaeger spans for traces, Prometheus counters, histograms, and gauges for metrics, and Kubernetes liveness and readiness probes for restarts and traffic gating.

Why it is used: To see how the app behaves in production from both outside and inside.

Terminal window
# APM (Application Performance Monitoring)
# Jaeger
# Python
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("operation") as span:
span.set_attribute("key", "value")
# Prometheus metrics
from prometheus_client import Counter, Histogram, Gauge
request_count = Counter('http_requests_total', 'Total HTTP requests')
request_duration = Histogram('http_request_duration_seconds')
active_users = Gauge('active_users', 'Number of active users')
# Health checks
# Kubernetes liveness/readiness probes
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5

Interview talking point: “Liveness restarts a stuck container, while readiness only removes it from Service endpoints; using liveness where readiness belongs causes restart loops during a slow dependency. A Histogram gives percentiles a Counter cannot.”

Q490: How do you implement compliance monitoring?

Section titled “Q490: How do you implement compliance monitoring?”

What it is: Compliance monitoring that continuously checks controls, alerts on deviation, reports regularly, tracks remediation, and supports audits.

Why it is used: Catches configuration drift away from required controls before an audit does.

Terminal window
# Compliance monitoring
# 1. Controls
# Continuous
# 2. Alerts
# Deviation
# 3. Reporting
# Regular
# 4. Remediation
# Tracking
# 5. Audit
# Support

Interview talking point: “Deviation alerts are the core: controls pass once at deployment, then drift over time. Remediation tracking alongside alerts means every deviation gets an owner and a closure record the audit can read.”

Q491: How do you implement compliance monitoring?

Section titled “Q491: How do you implement compliance monitoring?”

What it is: Compliance monitoring implementation enables continuous control monitoring, alerts on deviations, provides regular reporting, tracks remediation, and supports audits.

Why it is used: To detect non-compliance early and maintain ongoing audit readiness.

Terminal window
# Controls
# Continuous
# Alerts
# Deviation
# Reporting
# Regular
# Remediation
# Tracking
# Audit
# Support

Interview talking point: “Real-time deviation alerts and tracked remediation ensure issues are addressed promptly, preventing them from accumulating over time.”

Q492: How do you implement infrastructure monitoring?

Section titled “Q492: How do you implement infrastructure monitoring?”

What it is: Host monitoring with Prometheus: node_exporter exposes CPU, memory, and filesystem metrics while excluding pseudo filesystems, alert rules fire on high CPU or memory, and Grafana dashboards visualize them.

Why it is used: To track host health and catch resource exhaustion before it causes outages.

Terminal window
# Infrastructure monitoring
# Prometheus + Grafana
# Node exporter
node_exporter --collector.filesystem.mount-points-exclude="^/(sys|proc|run)"
# Custom metrics
# Python client
from prometheus_client import Counter
requests_total = Counter('app_requests_total', 'Total requests')
# Alert rules
- alert: HighCPU
expr: 100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 5m
- alert: HighMemory
expr: (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100 > 90
# Dashboards
# Import from Grafana.com
# Logs
# ELK Stack
# Loki + Grafana

Interview talking point: “The memory alert uses MemTotal minus MemAvailable rather than free memory, which accounts for reclaimable cache. irate over a 5m window gives a smoothed rate instead of reacting to a single sample.”

Q493: How do you implement infrastructure monitoring?

Section titled “Q493: How do you implement infrastructure monitoring?”

What it is: Infrastructure monitoring collects metrics, stores them in a time-series database, visualizes them on dashboards, alerts on thresholds, and analyzes trends.

Why it is used: To see system health and spot problems before users report them.

Terminal window
# Infrastructure monitoring
# 1. Metrics
# Collect
# 2. Storage
# Time-series
# 3. Visualization
# Dashboards
# 4. Alerting
# Thresholds
# 5. Analysis
# Trends

Interview talking point: “Threshold alerting catches known sudden failures while trend analysis catches slow drift, so both are needed to cover abrupt and gradual degradation.”

Q494: How do you implement infrastructure monitoring?

Section titled “Q494: How do you implement infrastructure monitoring?”

What it is: Infrastructure monitoring collects, stores, and visualizes system metrics for awareness and alerting.

Why it is used: It enables proactive detection of issues and supports capacity planning.

Terminal window
# Metrics
# Collect
# Storage
# Time-series
# Visualization
# Dashboards
# Alerting
# Thresholds
# Analysis
# Trends

Interview talking point: “Time-series storage with well-defined dashboards and threshold-based alerts helps teams spot trends early.”

Q495: How do you implement monitoring alerting?

Section titled “Q495: How do you implement monitoring alerting?”

What it is: Prometheus alert rules evaluate expressions such as up equal to zero or CPU above 90 percent for a set duration, and AlertManager routes grouped alerts to email and Slack.

Why it is used: Detect failures and saturation early and notify the right people automatically.

# Prometheus alert rules
groups:
- name: critical
interval: 30s
rules:
- alert: InstanceDown
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Instance {{ $labels.instance }} down"
- alert: HighCPU
expr: 100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 90
for: 5m
labels:
severity: warning
- alert: DiskSpace
expr: (node_filesystem_avail_bytes / node_filesystem_size_bytes) < 0.1
for: 10m
labels:
severity: warning
# AlertManager config
# alertmanager.yml
route:
group_by: ['alertname']
group_wait: 10s
group_interval: 10s
repeat_interval: 12h
receiver: 'team-notifications'
receivers:
- name: 'team-notifications'
email_configs:
- to: 'team@example.com'
send_resolved: true
slack_configs:
- api_url: 'https://hooks.slack.com/services/XXX'

Interview talking point: “The for clause keeps transient blips from paging anyone, and AlertManager repeat_interval of 12 hours re-sends unresolved alerts while send_resolved announces when they clear.”

Q496: How do you implement system monitoring?

Section titled “Q496: How do you implement system monitoring?”

What it is: node_exporter is a Prometheus exporter that exposes host metrics on port 9100, started and enabled with systemctl like any other service.

Why it is used: To feed CPU, memory, and filesystem metrics into dashboards and alerts.

Terminal window
# Prometheus + node_exporter
# Install
apt install prometheus-node-exporter
# Configure
# /etc/default/prometheus
ARGS="--collector.interval=30s"
# Start service
systemctl start prometheus-node-exporter
systemctl enable prometheus-node-exporter
# Metrics
curl http://localhost:9100/metrics

Interview talking point: “The metrics are plain text you can verify with curl to localhost:9100/metrics before Prometheus scrapes them, which makes diagnosing an exporter a single command.”

What it is: A monitoring stack bundles Prometheus for metrics, Grafana for dashboards, and Alertmanager for notifications, installed here as one Helm chart.

Why it is used: To gain a ready-made platform for collecting, viewing, and alerting on cluster metrics.

Terminal window
# Use Prometheus + Grafana + Alertmanager
# Install via Helm
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack
# Access
kubectl port-forward svc/prometheus-grafana 3000

Interview talking point: “kube-prometheus-stack installs the pieces together, and kubectl port-forward svc/prometheus-grafana 3000 exposes Grafana locally without publishing it as a public service.”

Q498: How do you set up Prometheus monitoring?

Section titled “Q498: How do you set up Prometheus monitoring?”

What it is: Prometheus is an open-source monitoring system that scrapes metrics over HTTP on a configured interval. Its config file declares scrape jobs, and node_exporter exposes host metrics on port 9100.

Why it is used: To collect and query time-series metrics from hosts and services for alerting and dashboards.

Terminal window
# Install
apt install prometheus
# or
tar -xzf prometheus-*.tar.gz
# Configuration
# /etc/prometheus/prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
# Node exporter
./node_exporter --collector.filesystem.mount-points-exclude="^/(sys|proc|dev|run)($|/)"
# View metrics
curl http://localhost:9100/metrics

Interview talking point: “The global scrape interval sets how often targets are polled, and you can verify any target by curling its /metrics endpoint directly, which returns plain text metric lines before Prometheus ever sees them.”

Q499: How do you set up service monitoring?

Section titled “Q499: How do you set up service monitoring?”

What it is: Prometheus scrapes a service target at localhost:8080, while a shell health check curls the /health endpoint and exits nonzero when curl -f reports failure.

Why it is used: To verify continuously that a service is up and to alert when its health endpoint stops responding.

Terminal window
# Use Prometheus
- job_name: 'service'
static_configs:
- targets: ['localhost:8080']
# Health check endpoint
#!/bin/bash
curl -f http://localhost:8080/health || exit 1

Interview talking point: “curl -f returns a failing exit code on HTTP error statuses, so the pattern of curl -f plus exit 1 makes the script’s exit code a usable pass or fail signal.”

What it is: sar, from the sysstat package, samples and reports system activity. The examples sample CPU, per-CPU, memory, swap, I/O and network counters at an interval, and sar -A writes a full report to a file.

Why it is used: To answer what the machine was doing earlier by reading collected history, or to watch live at intervals.

Terminal window
# Install
apt install sysstat
# Enable data collection
systemctl enable sysstat
systemctl start sysstat
# CPU stats
sar -u 1 5
# All CPU
sar -P ALL 1 3
# Memory
sar -r 1 3
# Swap
sar -S 1 3
# I/O
sar -b 1 3
# Network
sar -n DEV 1 3
# Generate report
sar -A > /tmp/sar_report.txt

Interview talking point: “sar -u 1 5 means five samples one second apart, and enabling sysstat is what makes historical data exist, so sar is as much about past data as live sampling.”