Linux_Practical_Interview_251 500
Linux Practical Interview Questions (251-500)
Section titled “Linux Practical Interview Questions (251-500)”Level 10: Network Services
Section titled “Level 10: Network Services”Firewall Fundamentals
Section titled “Firewall Fundamentals”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.
# Basic iptables rules# Allow established connectionsiptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSHiptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP/HTTPSiptables -A INPUT -p tcp --dport 80 -j ACCEPTiptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow localhostiptables -A INPUT -i lo -j ACCEPT
# Drop everything elseiptables -A INPUT -j DROP
# Save rulesiptables-save > /etc/iptables/rules.v4Interview 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.
# Basic filter rules# Allow loopbackiptables -A INPUT -i lo -j ACCEPT
# Allow establishediptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSHiptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP/HTTPSiptables -A INPUT -p tcp --dport 80 -j ACCEPTiptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Drop everything elseiptables -A INPUT -j DROP
# Forward rulesiptables -A FORWARD -i eth0 -o eth1 -j ACCEPTiptables -A FORWARD -i eth1 -o eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
# Rate limitingiptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --setiptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROPInterview 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.”
Q253: How do you configure UFW firewall?
Section titled “Q253: How do you configure UFW firewall?”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.
# Installapt install ufw
# Enableufw enableufw default deny incomingufw default allow outgoing
# Rulesufw allow sshufw allow 80/tcpufw allow from 192.168.1.0/24 to any port 5432
# Statusufw status numberedufw delete 1
# Loggingufw logging onufw logging lowInterview 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.
# Flush existing rulesiptables -Fiptables -Xiptables -t nat -Fiptables -t mangle -F
# Default policiesiptables -P INPUT DROPiptables -P FORWARD DROPiptables -P OUTPUT ACCEPT
# Loopbackiptables -A INPUT -i lo -j ACCEPT
# Established connectionsiptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# SSHiptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
# HTTP/HTTPSiptables -A INPUT -p tcp --dport 80 -j ACCEPTiptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Rate limitingiptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --setiptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
# Save rulesiptables-save > /etc/iptables/rules.v4Interview 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.”
Q255: How do you use firewalld?
Section titled “Q255: How do you use firewalld?”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.
# Installapt install firewalld
# Servicesfirewall-cmd --list-servicesfirewall-cmd --add-service=httpfirewall-cmd --add-port=8080/tcp
# Zonesfirewall-cmd --get-zonesfirewall-cmd --zone=public --list-all
# Permanentfirewall-cmd --runtime-to-permanent
# Rich rulesfirewall-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.”
Q256: How do you use iptables Layer 7?
Section titled “Q256: How do you use iptables Layer 7?”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.
# Installapt install ipp2p
# Block P2Piptables -A FORWARD -m ipp2p --ipp2p -j DROP
# With conntrackiptables -A FORWARD -m layer7 --l7proto bittorrent -j DROPInterview 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.”
Q257: How do you use nftables advanced?
Section titled “Q257: How do you use nftables advanced?”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.
# Create tablenft add table inet filter
# Add chainnft add chain inet filter input { type filter hook input priority 0; }
# Add rulenft add rule inet filter input ct state established,related accept
# NATnft add table ip natnft add chain ip nat postrouting { type nat hook postrouting priority 100; }nft add rule ip nat postrouting oifname "eth0" masqueradeInterview 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.”
Q258: How do you use nftables?
Section titled “Q258: How do you use nftables?”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.
# Installapt install nftables
# Create rulesetcat > /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
# Reloadnft -f /etc/nftables.confsystemctl enable nftablesInterview 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.”
Mail Services
Section titled “Mail Services”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.
service auth { unix_listener /var/spool/postfix/private/auth { mode = 0660 user = postfix group = postfix }}
# /etc/dovecot/10-auth.confauth_mechanisms = plain login!include auth-system.conf.extInterview 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.”
Q260: How do you configure Dovecot?
Section titled “Q260: How do you configure Dovecot?”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.
# Installapt install dovecot-core dovecot-imapd dovecot-pop3d
protocols = imap pop3listen = *
# /etc/dovecot/10-auth.confdisable_plaintext_auth = yesauth_mechanisms = plain login
# /etc/dovecot/10-mail.confmail_location = maildir:~/Maildir
# Configure userdb# /etc/dovecot/10-user.confuserdb { driver = passwd}
systemctl restart dovecotInterview 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.”
Q261: How do you configure Dovecot?
Section titled “Q261: How do you configure Dovecot?”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.
# Installapt install dovecot-core dovecot-imapd
protocols = imap pop3listen = *
# /etc/dovecot/10-auth.confdisable_plaintext_auth = yesauth_mechanisms = plain login
# /etc/dovecot/10-mail.confmail_location = maildir:~/Maildir
# Userdb (PAM)# /etc/dovecot/10-auth.conf!include auth-system.conf.ext
systemctl restart dovecotInterview 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.”
Q262: How do you configure Dovecot?
Section titled “Q262: How do you configure Dovecot?”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.
# Installapt install dovecot-imapd dovecot-pop3d
protocols = imap pop3listen = *base_dir = /var/run/dovecot/
# Authentication# /etc/dovecot/conf.d/10-auth.confdisable_plaintext_auth = yesauth_mechanisms = plain login
# User database# /etc/dovecot/conf.d/10-mail.confmail_location = maildir:~/Maildir
# PAMpassdb { driver = pam args = session_failure_delay=finite_secs}
# SSL# /etc/dovecot/conf.d/10-ssl.confssl = requiredssl_cert = </etc/ssl/certs/dovecot.pemssl_key = </etc/ssl/private/dovecot.pemInterview 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.”
Q263: How do you configure mail relay?
Section titled “Q263: How do you configure mail relay?”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.
# Postfix relay configurationrelayhost = [smtp.example.com]:587smtp_sasl_auth_enable = yessmtp_sasl_password_maps = hash:/etc/postfix/sasl_passwdsmtp_sasl_tls_security_level = encryptsmtp_tls_security_level = encryptsmtp_tls_wrappermode = no
# /etc/postfix/sasl_passwd[smtp.example.com]:587 username:password
# Secure the password filechmod 600 /etc/postfix/sasl_passwdpostmap /etc/postfix/sasl_passwd
# Relay for specific domains# /etc/postfix/transportexample.com :[smtp.example.com]* smtp:relay.other.com
# Testecho "Test email" | sendmail -v user@example.comInterview 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.”
Q264: How do you configure mail server?
Section titled “Q264: How do you configure mail server?”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.
# Install Postfixapt install postfix
# Configure main.cf# /etc/postfix/main.cfmyhostname = mail.example.commydomain = example.commyorigin = $mydomaininet_interfaces = allmydestination = $myhostname, localhost, localhost.localdomainhome_mailbox = Maildir/smtpd_sasl_auth_enable = yessmtpd_recipient_restrictions = permit_sasl_authenticated, reject
# Install Dovecotapt install dovecot-imapd
# Configure /etc/dovecot/conf.d/10-auth.confdisable_plaintext_auth = yesauth_mechanisms = plain login
# Configure /etc/dovecot/conf.d/10-mail.confmail_location = maildir:~/Maildir
# Create mail useruseradd -m -s /bin/bash mailuserpasswd mailuserInterview 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.
# Installapt install postfix mailutils
myhostname = mail.example.commydomain = example.commyorigin = $mydomainmydestination = $myhostname, localhost, localhost.localdomainmynetworks = 192.168.1.0/24 127.0.0.0/8relayhost = [smtp.provider.com]:587smtp_sasl_auth_enable = yessmtp_sasl_password_maps = hash:/etc/postfix/sasl_passwdsmtp_tls_security_level = encrypt
# Create password mapecho "[smtp.provider.com]:587 username:password" > /etc/postfix/sasl_passwdpostmap /etc/postfix/sasl_passwdsystemctl restart postfixInterview 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.
# Installapt install postfix-ldap
server_host = ldap.example.comsearch_base = ou=people,dc=example,dc=comquery_filter = mail=%sresult_attribute = mailForwardingAddressInterview 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.
smtpd_sasl_type = dovecotsmtpd_sasl_path = private/authsmtpd_sasl_auth_enable = yessmtpd_sasl_security_options = noanonymoussmtpd_sasl_local_domain = $myhostname
# /etc/postfix/master.cfsubmission inet n - - - - smtpd -o smtpd_sasl_auth_enable=yes -o smtpd_client_restrictions=permit_sasl_authenticated,rejectInterview 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.”
Q268: How do you configure Postfix?
Section titled “Q268: How do you configure Postfix?”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.
# Installapt install postfix mailutils
myhostname = mail.example.commydomain = example.commyorigin = $mydomainmydestination = $myhostname, localhost, localhost.localdomainmynetworks = 192.168.1.0/24 127.0.0.0/8relayhost = [smtp.gmail.com]:587smtp_sasl_auth_enable = yessmtp_sasl_password_maps = hash:/etc/postfix/sasl_passwdsmtp_tls_security_level = encrypt
# Create credentialsecho "[smtp.gmail.com]:587 username:password" > /etc/postfix/sasl_passwdpostmap /etc/postfix/sasl_passwdInterview 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.”
Q269: How do you configure Postfix?
Section titled “Q269: How do you configure Postfix?”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.
# Installapt install postfix
myhostname = mail.example.commydomain = example.commyorigin = $mydomaininet_interfaces = allmydestination = $myhostname, localhost, localhost.localdomainhome_mailbox = Maildir/smtpd_sasl_type = dovecotsmtpd_sasl_path = private/authsmtpd_sasl_auth_enable = yessmtpd_recipient_restrictions = permit_sasl_authenticated, reject
# Virtual aliases# /etc/postfix/virtualadmin@example.com adminsupport@example.com support@company.com
# Master.cfsubmission inet n - y - - smtpd -o syslog_name=postfix/submission
# Testpostfix checkpostfix reloadInterview 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.
# Install SpamAssassinapt install spamassassin spamc
# Configure Postfix# /etc/postfix/master.cfspamassassin unix - n n - - pipe user=spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}
# /etc/postfix/main.cfcontent_filter = spamassassin
# Configure SpamAssassin# /etc/spamassassin/local.cfrequired_score 5.0rewrite_header Subject [SPAM]report_safe 0
# Add headersadd_header all Status _YESNO_, score=_SCORE_ required=_REQD_ tests=_TESTS_add_header all Reply-To _ADDR_
# Train bayessa-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.”
File Sharing Services
Section titled “File Sharing Services”Q271: How do you configure FTP server?
Section titled “Q271: How do you configure FTP server?”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.
# Install vsftpdapt install vsftpd
# Configure# /etc/vsftpd.conflisten=YESanonymous_enable=NOlocal_enable=YESwrite_enable=YESlocal_umask=022dirmessage_enable=YESxferlog_enable=YESconnect_from_port_20=YES
# Enable SSLssl_enable=YESrsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pemrsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
# Chroot userschroot_local_user=YESallow_writeable_chroot=YES
# User listuserlist_enable=YESuserlist_file=/etc/vsftpd.userlistuserlist_deny=NO
# Start servicesystemctl start vsftpdsystemctl enable vsftpdInterview 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.
# Installapt install samba krb5-user
# Provisionsamba-tool domain provision --realm=EXAMPLE.COM --domain=EXAMPLE --adminpass=Password123 --server-role=dc
# Startsystemctl start samba
# Add useruseradd -M -s /sbin/nologin administratorsmbpasswd -a administrator
# Join domainnet ads join -U administratorInterview 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.”
Q273: How do you configure Samba?
Section titled “Q273: How do you configure Samba?”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.
[global] workgroup = WORKGROUP security = user map to guest = Bad User
[shared] path = /srv/samba/shared browsable = yes writable = yes guest ok = no valid users = @smbgroupInterview 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.”
Q274: How do you configure VsFTPd?
Section titled “Q274: How do you configure VsFTPd?”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.
# Installapt install vsftpd
listen=YESanonymous_enable=NOlocal_enable=YESwrite_enable=YESdirmessage_enable=YESuse_localtime=YESxferlog_enable=YESconnect_from_port_20=YESsecure_chroot_dir=/var/run/vsftpd/empty
# Enable SSLrsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pemrsa_private_key=/etc/ssl/private/ssl-cert-snakeoil.keyssl_enable=YES
# Create useruseradd -m -s /usr/sbin/nologin ftpuserpasswd ftpuser
systemctl restart vsftpdInterview 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.”
Proxy Services
Section titled “Proxy Services”Q275: How do you configure caching proxy?
Section titled “Q275: How do you configure caching proxy?”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.
# Install Squidapt install squid
# Basic confighttp_port 3128cache_dir ufs /var/spool/squid 1000 16 256
# Access controlacl localnet src 192.168.0.0/16http_access allow localnethttp_access deny all
# Cache rulesrefresh_pattern -i \.jpg$ 10080 90% 43200refresh_pattern -i \.html$ 1440 90% 3600refresh_pattern -i \.css$ 10080 90% 43200refresh_pattern -i \.js$ 10080 90% 43200
# Transparent proxyhttp_port 3128 transparent
# Testsquid -k parsesystemctl restart squidInterview 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.
# Install Varnishapt 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; }}
# Commandsvarnishd -F -f /etc/varnish/default.vclvarnishstatvarnishlogInterview 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.”
Q277: How do you configure Squid proxy?
Section titled “Q277: How do you configure Squid proxy?”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.
# Installapt install squid
http_port 3128acl localnet src 192.168.1.0/24http_access allow localnethttp_access deny all
# Cache configurationcache_dir ufs /var/spool/squid 10000 16 256maximum_object_size 4096 MB
# Authenticationauth_param basic program /usr/lib/squid/ncsa_auth /etc/squid/passwdacl authenticated proxy_auth REQUIREDhttp_access allow authenticated
# Reloadsystemctl reload squidInterview 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.”
Q278: How do you configure Squid proxy?
Section titled “Q278: How do you configure Squid proxy?”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.
http_port 3128acl localnet src 192.168.1.0/24http_access allow localnethttp_access deny all
cache_dir ufs /var/spool/squid 10000 16 256maximum_object_size 4096 MB
# Authenticationauth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwdacl authenticated proxy_auth REQUIREDhttp_access allow authenticatedInterview 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.”
Databases
Section titled “Databases”Q279: How do you backup databases?
Section titled “Q279: How do you backup databases?”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.
# MySQLmysqldump -u root -p --all-databases > all_databases.sqlmysqldump -u root -p mydb | gzip > mydb.sql.gz
# PostgreSQLpg_dumpall -U postgres > all.sqlpg_dump -U myuser mydb | gzip > mydb.sql.gz
# Automate# /etc/cron.d/backup0 2 * * * root mysqldump -u root -psecret mydb | gzip > /backup/mydb-$(date +\%Y\%m\%d).sql.gzInterview 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.”
Q280: How do you backup databases?
Section titled “Q280: How do you backup databases?”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.
#!/bin/bashDB_NAME="mydb"DB_USER="backup"DB_PASS="password"BACKUP_DIR="/backup/mysql"DATE=$(date +%Y%m%d_%H%M%S)
# MySQL backupmysqldump -u$DB_USER -p$DB_PASS --single-transaction --routines --triggers $DB_NAME | gzip > $BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz
# PostgreSQL backuppg_dump -U $DB_USER -F c -b -v -f $BACKUP_DIR/${DB_NAME}_${DATE}.dump $DB_NAME
# Retentionfind $BACKUP_DIR -name "*.sql.gz" -mtime +7 -deletefind $BACKUP_DIR -name "*.dump" -mtime +7 -delete
# Verifyzcat $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.dumpInterview 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.
# 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 dataUPDATE users SET new_field = old_field;
# 4. Make new column NOT NULLALTER TABLE users MODIFY COLUMN new_field VARCHAR(255) NOT NULL;
# 5. Remove old columnALTER TABLE users DROP COLUMN old_field;
# For PostgreSQL# Use pg_online# Create index concurrentlyCREATE INDEX CONCURRENTLY idx_users_email ON users(email);
# For MySQL# Use pt-online-schema-changept-online-schema-change D=t,s=users --alter "ADD COLUMN new_field VARCHAR(255)" \ --execute
# Rollback plan# Keep old column# Dual write# Test thoroughlyInterview 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.
# Master config[mysqld]server-id = 1log_bin = /var/log/mysql/mysql-binbinlog_do_db = mydb
# Slave config[mysqld]server-id = 2relay-log = /var/log/mysql/mysql-relay-bin
# On masterGRANT REPLICATION SLAVE ON *.* TO 'repl'@'%' IDENTIFIED BY 'password';FLUSH TABLES WITH READ LOCK;SHOW MASTER STATUS;
# On slaveCHANGE 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.”
Q283: How do you configure MySQL Cluster?
Section titled “Q283: How do you configure MySQL Cluster?”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.
# MySQL NDB Cluster# Installapt install mysql-cluster-community-server
# Management node config# /etc/mysql/my.cnf[ndb_mgmd]node-id=1hostname=192.168.1.10datadir=/var/lib/mysql-cluster
# Data nodes# /etc/mysql/my.cnf[ndbd]node-id=2hostname=192.168.1.11datadir=/var/lib/mysql-cluster
[ndbd]node-id=3hostname=192.168.1.12datadir=/var/lib/mysql-cluster
# SQL node# /etc/mysql/my.cnf[mysqld]node-id=4
# Start management nodendb_mgmd -f /etc/mysql/config.ini
# Start data nodesndbd --initial
# Start SQL nodemysqld --ndbcluster
# Check statusndb_mgm -e showInterview 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.
# MySQL 8.0 Group Replication[mysqld]server-id=1gtid_mode=ONenforce_gtid_consistency=ONbinlog_checksum=NONElog_slave_updates=ONrelay_log=relay-binbinlog_format=ROWtransaction_write_set_extraction=XXHASH64
# Group Replication pluginplugin_load_add='group_replication.so'group_replication_group_name="aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"group_replication_start_on_boot=OFFgroup_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 replicationSET 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 = 1log_bin = /var/log/mysql/mysql-binbinlog_do_db = mydb
# Slave[mysqld]server-id = 2relay-log = /var/log/mysql/mysql-relay-bin
# CommandsGRANT 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.”
Q286: How do you configure MySQL with HA?
Section titled “Q286: How do you configure MySQL with HA?”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.
# MHA# Installapt install mha4mysql-node mha4mysql-manager
# Configure# /etc/app1.cnf[server default]manager_workdir=/var/log/masterha/app1manager_log=/var/log/masterha/app1.logremote_workdir=/var/log/masterha
[server1]hostname=192.168.1.10candidate_master=1
[server2]hostname=192.168.1.11Interview 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.”
Q287: How do you configure MySQL/MariaDB?
Section titled “Q287: How do you configure MySQL/MariaDB?”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.
# Installapt install mysql-server# oryum install mariadb-server
# Secure installationmysql_secure_installation
# Create database and usermysql -u root -pCREATE 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
# Backupmysqldump -u root -p myapp > backup.sqlmysql -u root -p myapp < backup.sqlInterview 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.
# Streaming replicationwal_level = replicamax_wal_senders = 3wal_keep_size = 1GBhot_standby = on
# Master: /etc/postgresql/14/main/pg_hba.confhost replication replicator 192.168.1.0/24 md5
# Create replication userpsql -c "CREATE USER replicator REPLICATION LOGIN PASSWORD 'secret';"
# Backup on replicapg_basebackup -h master -D /var/lib/postgresql/14/main -U replicator -P -Xs
# Replica: /etc/postgresql/14/main/postgresql.confhot_standby = on
# Replica: /etc/postgresql/14/main/recovery.confstandby_mode = onprimary_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.1listen_port = 6432auth_type = md5auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transactionmax_client_conn = 1000default_pool_size = 20Interview 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.
# Masterwal_level = replicamax_wal_senders = 3max_replication_slots = 3
# Slavehot_standby = onprimary_conninfo = 'host=master_ip port=5432 user=repl password=password'
# Commandspg_basebackup -h master_ip -D /var/lib/postgresql/14/main -P -Xs -RInterview 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.
# Master configurationwal_level = replicamax_wal_senders = 3max_replication_slots = 3wal_keep_size = 1GB
# /etc/postgresql/14/main/pg_hba.confhost replication replicator 192.168.1.0/24 md5
# Create replication userpsql -U postgresCREATE USER replicator REPLICATION LOGIN PASSWORD 'password';
# Backup for replicapg_basebackup -h master -D /var/lib/postgresql/14/main -U replicator -P -X stream
# Replica configuration# /etc/postgresql/14/main/postgresql.confhot_standby = on
# Create recovery.conf# /etc/postgresql/14/main/recovery.confstandby_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.”
Q291: How do you configure PostgreSQL?
Section titled “Q291: How do you configure PostgreSQL?”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.
# Installapt install postgresql
# Connectsudo -u postgres psql
# Commands\list # list databases\dt # list tables\du # list users
# Create databaseCREATE DATABASE mydb;CREATE USER myuser WITH PASSWORD 'secret';GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
# Backuppg_dump -U user dbname > backup.sql
# Restorepsql -U user dbname < backup.sqlInterview 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.”
Q292: How do you configure PostgreSQL?
Section titled “Q292: How do you configure PostgreSQL?”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.
# Installapt install postgresql# oryum install postgresql-server
# Initializepostgresql-setup --initdb# orpg_ctl -D /var/lib/pgsql/data initdb
# Create user and databasesudo -u postgres createuser myusersudo -u postgres createdb mydbsudo -u postgres psqlALTER 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
# Backuppg_dump -U myuser mydb > backup.sqlInterview 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.”
Q293: How do you configure Redis cluster?
Section titled “Q293: How do you configure Redis cluster?”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.
# Create clusterredis-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 clusterredis-cli -c -p 7001 cluster nodesredis-cli -c -p 7001 cluster info
# Connect to clusterredis-cli -c -p 7001
# OperationsCLUSTER INFOCLUSTER SLOTSCLUSTER NODES
# Failover# Master electionredis-cli -p 7001 cluster failover
# Reshardredis-cli --cluster reshard 127.0.0.1:7001Interview 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.
# Sentinel configurationport 26379sentinel monitor mymaster 127.0.0.1 6379 2sentinel down-after-milliseconds mymaster 5000sentinel failover-timeout mymaster 180000sentinel parallel-syncs mymaster 1
# Start sentinelredis-sentinel /etc/redis/sentinel.conf
# Client connection# Python examplefrom redis.sentinel import Sentinelsentinel = 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)
# Commandsredis-cli -p 26379 INFO SENTINELredis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
# Failover# Sentinel automatically promotes replica to master# Old master becomes replica when back onlineInterview 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.”
Q295: How do you configure Redis?
Section titled “Q295: How do you configure Redis?”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.
# Installapt install redis-server# oryum install redis
# Configuration# /etc/redis/redis.confbind 127.0.0.1port 6379maxmemory 256mbmaxmemory-policy allkeys-lruappendonly yes
# Commandsredis-cli PINGredis-cli SET mykey "value"redis-cli GET mykeyredis-cli KEYS "*"
# Cluster moderedis-cli --cluster create 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 --cluster-replicas 1Interview 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.
# Database sharding# 1. Key strategy# Choose shard key
# 2. Routing# Application
# 3. Rebalancing# Plan
# 4. Cross-shard# Minimize
# 5. Monitoring# PerformanceInterview 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.
# Key strategy# Choose shard key
# Routing# Application
# Rebalancing# Plan
# Cross-shard# Minimize
# Monitoring# PerformanceInterview talking point: “Choosing the right shard key is critical — poor choices lead to hotspots and make cross-shard operations complex.”
Q298: How do you manage MySQL/MariaDB?
Section titled “Q298: How do you manage MySQL/MariaDB?”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.
# Installapt install mariadb-server
# Secure installationmysql_secure_installation
# Connectmysql -u root -p
# Common commandsSHOW DATABASES;CREATE DATABASE dbname;USE dbname;SHOW TABLES;DESCRIBE tablename;
# Backupmysqldump -u root -p dbname > backup.sql
# Restoremysql -u root -p dbname < backup.sqlInterview 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.”
Q299: How do you manage MySQL?
Section titled “Q299: How do you manage MySQL?”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.
# Installapt install mysql-server
# Securemysql_secure_installation
# Connectmysql -u root -p
# Create databaseCREATE DATABASE mydb;CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'password';GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost';FLUSH PRIVILEGES;
# Backupmysqldump -u root -p mydb > backup.sql
# Restoremysql -u root -p mydb < backup.sqlInterview 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.”
Q300: How do you manage PostgreSQL?
Section titled “Q300: How do you manage PostgreSQL?”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.
# Installapt install postgresql
# Connectsudo -u postgres psql
# Create user/databaseCREATE USER myuser WITH PASSWORD 'password';CREATE DATABASE mydb OWNER myuser;
# Backuppg_dump -U myuser mydb > backup.sql
# Restorepsql -U myuser mydb < backup.sql
# RolesALTER 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.”
Q301: How do you use MongoDB?
Section titled “Q301: How do you use MongoDB?”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.
# Installapt install mongodb
# Connectmongosh
# Commandsuse mydbdb.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.”
Q302: How do you use Redis Sentinel?
Section titled “Q302: How do you use Redis Sentinel?”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.confsentinel monitor mymaster 192.168.1.10 6379 2sentinel down-after-milliseconds mymaster 5000sentinel failover-timeout mymaster 180000sentinel parallel-syncs mymaster 1
# Startredis-sentinel /etc/redis/sentinel.conf
# ClientJedisSentinelPool 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.”
Q303: How do you use Redis?
Section titled “Q303: How do you use Redis?”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.
# Installapt install redis-server
# Configure /etc/redis/redis.confbind 127.0.0.1port 6379maxmemory 2gbmaxmemory-policy allkeys-lrusave ""
# Commandsredis-cliSET key valueGET keyDEL keyKEYS patternInterview 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.
# PostgreSQL# EXPLAIN ANALYZEEXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';
# pgbenchpgbench -i -s 100 mydbpgbench -c 10 -j 2 -t 1000 mydb
# MySQL# EXPLAINEXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
# mysqlslapmysqlslap --user=root --password --auto-generate-sql \ --concurrency=10 --iterations=5
# sysbenchsysbench /usr/share/sysbench/oltp_read_write.lua \ --mysql-host=localhost \ --mysql-db=test \ --threads=10 \ --time=60 \ run
# pt-query-digestpt-query-digest slow-query.logInterview 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.
# PostgreSQL tuning# postgresql.confshared_buffers = 256MBeffective_cache_size = 768MBmaintenance_work_mem = 64MBcheckpoint_completion_target = 0.9wal_buffers = 16MBdefault_statistics_target = 100random_page_cost = 1.1effective_io_concurrency = 200work_mem = 4MBmin_wal_size = 1GBmax_wal_size = 4GB
# MySQL tuning# my.cnfinnodb_buffer_pool_size = 1Ginnodb_log_file_size = 256Minnodb_flush_log_at_trx_commit = 2innodb_flush_method = O_DIRECTkey_buffer_size = 256Mquery_cache_size = 0tmp_table_size = 64Mmax_connections = 200
# Analyze queriesEXPLAIN 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.”
Directory Services
Section titled “Directory Services”Q306: How do you backup and restore LDAP?
Section titled “Q306: How do you backup and restore LDAP?”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.
# Backup databaseslapcat -n 1 > backup.ldif# or using ldapsearchldapsearch -x -LLL -b "dc=example,dc=com" > backup.ldif
# Restore# Stop slapdsystemctl stop slapd# Remove databaserm -rf /var/backups/ldap/*# Restoreslapadd -l backup.ldif# Set permissionschown -R openldap:openldap /var/lib/ldap/# Start slapdsystemctl start slapd
# Automate backup#!/bin/bashDATE=$(date +%Y%m%d)slapcat -n 1 > /backup/ldap-$DATE.ldifgzip /backup/ldap-$DATE.ldiffind /backup -mtime +30 -deleteInterview 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.
# Install clientapt install libnss-ldap libpam-ldap ldap-utils
# Configure NSS# /etc/nsswitch.confpasswd: compat ldapgroup: compat ldapshadow: compat ldaphosts: files dns ldapnetworks: files ldap
# Configure PAM# /etc/pam.d/common-sessionsession optional pam_mkhomedir.so skel=/etc/skel umask=077
# Configure LDAP client# /etc/ldap.confbase dc=example,dc=comuri ldap://ldap.example.comldap_version 3rootbinddn cn=admin,dc=example,dc=com
# Testgetent passwd johnid johnInterview 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.
# Installapt install realmd sssd adcli
# Join domainrealm join --user=admin example.com
# Checkrealm listid user@EXAMPLE.COM
# Loginlogin user@EXAMPLE.COMInterview 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.
# Master (provider) configurationoverlay syncprovsyncprov-checkpoint 100 10syncprov-sessionlog 100
# Enable syncprov modulemodulepath /usr/lib/ldapmoduleload syncprov
# Consumer (replica) configuration# /etc/ldap/slapd.confsyncrepl 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 URLsyncrepl rid=123 provider=ldap://master.example.com:389 searchbase="dc=example,dc=com" binddn="cn=syncuser,dc=example,dc=com" credentials=passwordInterview 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.”
Q310: How do you configure LDAP?
Section titled “Q310: How do you configure LDAP?”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.
# Installapt install slapd ldap-utils
# Configuredpkg-reconfigure slapd
# Add entriesldapadd -x -D "cn=admin,dc=example,dc=com" -W -f entries.ldif
# Searchldapsearch -x -b "dc=example,dc=com" "(objectclass=*)"
# Modifyldapmodify -x -D "cn=admin,dc=example,dc=com" -W -f modify.ldif
# Deleteldapdelete -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.”
Q311: How do you configure OpenLDAP?
Section titled “Q311: How do you configure OpenLDAP?”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.
# Installapt install slapd ldap-utils
# Reconfiguredpkg-reconfigure slapd
# Add entries# add_user.ldifdn: uid=john,ou=people,dc=example,dc=comobjectClass: inetOrgPersonobjectClass: posixAccountuid: johncn: John Doesn: DoegivenName: JohnuidNumber: 1000gidNumber: 1000homeDirectory: /home/johnmail: john@example.com
# Add entryldapadd -x -D "cn=admin,dc=example,dc=com" -W -f add_user.ldif
# Searchldapsearch -x -b "dc=example,dc=com" "(uid=john)"ldapsearch -x -H ldap://localhost -D "cn=admin,dc=example,dc=com" -WInterview 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.”
Q312: How do you set up LDAP client?
Section titled “Q312: How do you set up LDAP client?”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.
# Installapt install libnss-ldap libpam-ldap
# Configure# /etc/nsswitch.confpasswd: compat ldapgroup: compat ldapshadow: compat ldap
# PAM# /etc/pam.d/common-sessionsession optional pam_mkhomedir.so skel=/etc/skel umask=077Interview 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.”
Q313: How do you set up LDAP replication?
Section titled “Q313: How do you set up LDAP replication?”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.
# Master configserverID 1syncrepl rid=001 provider=ldap://ldap2.example.com bindmethod=simple binddn="cn=admin,dc=example,dc=com" credentials=secret searchbase="dc=example,dc=com" type=refreshAndPersistInterview 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.”
Level 11: Security and Hardening
Section titled “Level 11: Security and Hardening”SSH Hardening and Key Management
Section titled “SSH Hardening and Key Management”Q314: How do you harden SSH?
Section titled “Q314: How do you harden SSH?”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.
PermitRootLogin noPubkeyAuthentication yesPasswordAuthentication noPermitEmptyPasswords noMaxAuthTries 3ClientAliveInterval 300X11Forwarding noAllowTcpForwarding noForceCommand none
# Restartsystemctl restart sshd
# Generate keysssh-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.”
Q315: How do you secure SSH access?
Section titled “Q315: How do you secure SSH access?”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.
Port 2222PermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesMaxAuthTries 3ClientAliveInterval 300AllowUsers user1 user2
# Generate key pairssh-keygen -t ed25519 -C "work laptop"
# Copy keyssh-copy-id user@server
# Fail2banapt install fail2ban# oryum install fail2banInterview 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.”
Q316: How do you secure SSH?
Section titled “Q316: How do you secure SSH?”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.
# Edit /etc/ssh/sshd_configPermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesPort 2222MaxAuthTries 3ClientAliveInterval 300
# Restartsystemctl restart sshdInterview 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.”
Firewall Security and Network Protection
Section titled “Firewall Security and Network Protection”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.
# VLANsvconfig add eth0 100vconfig add eth0 200
# Firewalls# DMZ, internal, database tiers
# Kubernetes# NetworkPolicieskubectl apply -f network-policy.yamlInterview 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.
# API rate limiting# 1. Token bucket# Leaky bucket
# 2. Per-user# By key
# 3. Headers# Rate limit
# 4. Response# 429
# 5. Throttling# GracefulInterview 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.
# Token bucket# Leaky bucket
# Per-user# By key
# Headers# Rate limit
# Response# 429
# Throttling# GracefulInterview 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 defaultapiVersion: networking.k8s.io/v1kind: NetworkPolicymetadata: name: default-denyspec: podSelector: {} policyTypes: - Ingress - EgressInterview 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.
# VLANsvconfig add eth0 100 # DMZvconfig add eth0 200 # Internal
# Firewalls# Perimeter# Application# Database
# Kubernetes namespaceskubectl create namespace productionkubectl label namespace production env=productionInterview 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.
# VLAN isolationip link add link eth0 name eth0.100 type vlan id 100ip addr add 192.168.100.1/24 dev eth0.100
# iptables zonesiptables -N DMZiptables -A DMZ -j DROPiptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
# Network namespaces for isolationip netns add isolatedip netns exec isolated ip link set lo up
# Cgroups for process isolation# /etc/cgconfig.confgroup web { cpu { cpu.shares=512; } memory { memory.limit_in_bytes=512M; }}
# AppArmor/SELinuxapparmor_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.
# Create isolated network namespaceip netns add isolatedip netns exec isolated ip link set lo up
# Configure VLANip link add link eth0 name eth0.100 type vlan id 100ip addr add 192.168.100.1/24 dev eth0.100ip link set eth0.100 up
# iptables zones# DMZiptables -N DMZ-ZONEiptables -A DMZ-ZONE -j DROP
# Internaliptables -N INT-ZONEiptables -A INT-ZONE -j ACCEPT
# Bridge isolationip link add name br0 type bridgeip link set eth0 master br0ip link set eth1 master br0
# Prevent forwardingiptables -A FORWARD -i br0 -o br0 -j DROP
# AppArmor namespacesapparmor_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.
# Create network namespacesip netns add dmzip netns add internal
# Configure VLANsip link add link eth0 name eth0.100 type vlan id 100ip addr add 192.168.100.1/24 dev eth0.100ip link set eth0.100 up
# Bridge isolationip link add name br-dmz type bridgeip link set eth1 master br-dmzip link set eth2 master br-dmz
# iptables zone-based firewalliptables -N DMZ-ZONEiptables -N INTERNAL-ZONEiptables -N EXTERNAL-ZONE
# DMZ rulesiptables -A DMZ-ZONE -p tcp --dport 80 -j ACCEPTiptables -A DMZ-ZONE -p tcp --dport 443 -j ACCEPTiptables -A DMZ-ZONE -j REJECT
# Internal rulesiptables -A INTERNAL-ZONE -j ACCEPTiptables -A INTERNAL-ZONE -o eth0 -j MASQUERADEInterview 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.
# Network segmentation# 1. VLANs# Isolation
# 2. Firewalls# Zones
# 3. Zero trust# Micro-segmentation
# 4. Monitoring# Traffic
# 5. Compliance# AuditInterview 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.
# VLANs# Isolation
# Firewalls# Zones
# Zero trust# Micro-segmentation
# Monitoring# Traffic
# Compliance# AuditInterview talking point: “Micro-segmentation and zero trust limit lateral movement, while traffic monitoring and audits verify that boundaries remain effective.”
Q327: How do you implement rate limiting?
Section titled “Q327: How do you implement rate limiting?”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 limitingapiVersion: networking.k8s.io/v1kind: Ingressmetadata: 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: 80Interview 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.”
Q328: How do you implement rate limiting?
Section titled “Q328: How do you implement rate limiting?”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.
# iptables rate limitiptables -A INPUT -p tcp --dport 80 -m state --state NEW \ -m recent --setiptables -A INPUT -p tcp --dport 80 -m state --state NEW \ -m recent --update --seconds 60 --hitcount 10 -j DROP
# Nginx rate limiting# nginx.confhttp { 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.cfghttp-request deny deny_status 429 if { sc_http_req_rate(10) gt 10 }
# Application rate limiting# Python examplefrom flask import Flask, request, jsonifyfrom 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.”
Q329: How do you implement rate limiting?
Section titled “Q329: How do you implement rate limiting?”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 timefrom 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_requestsInterview 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.”
Q330: How do you configure fail2ban?
Section titled “Q330: How do you configure fail2ban?”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.
# Installapt install fail2ban
[sshd]enabled = trueport = sshmaxretry = 3bantime = 3600findtime = 600
[nginx-http-auth]enabled = true
# Commandsfail2ban-client statusfail2ban-client set sshd unbanip 192.168.1.10fail2ban-client get sshd ban Time
# Logstail -f /var/log/fail2ban.logInterview 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.”
Q331: How do you configure fail2ban?
Section titled “Q331: How do you configure fail2ban?”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.
# Installapt install fail2ban
# Configure# /etc/fail2ban/jail.local[DEFAULT]bantime = 3600findtime = 600maxretry = 5destemail = admin@example.comsender = fail2ban@example.comaction = %(action_mwl)s
[sshd]enabled = trueport = sshfilter = sshdlogpath = /var/log/auth.logmaxretry = 3
[nginx-http-auth]enabled = truefilter = nginx-http-authport = http,httpslogpath = /var/log/nginx/error.log
# Custom filter# /etc/fail2ban/filter.d/myapp.conf[Definition]failregex = <HOST> - .* "GET /adminignoreregex =
# Testfail2ban-regex /var/log/nginx/error.log /etc/fail2ban/filter.d/nginx-http-auth
# Commandsfail2ban-client statusfail2ban-client set sshd unbanip 192.168.1.100Interview talking point: “bantime, findtime, and maxretry define detection windows and ban duration; custom filters target application-specific attacks.”
Q332: How do you configure fail2ban?
Section titled “Q332: How do you configure fail2ban?”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.
# Install fail2banapt install fail2ban
# Configure# /etc/fail2ban/jail.local[DEFAULT]bantime = 3600findtime = 600maxretry = 5
[sshd]enabled = trueport = sshfilter = sshdlogpath = /var/log/auth.log
[nginx-http-auth]enabled = truefilter = nginx-http-authport = http,https
[apache2]enabled = trueport = http,https
# Custom filter# /etc/fail2ban/filter.d/custom.conf[Definition]failregex = <HOST> - .* "GET /admin
# Start servicesystemctl start fail2ban
# Check statusfail2ban-client statusfail2ban-client status sshdInterview 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.”
Q333: How do you use fail2ban?
Section titled “Q333: How do you use fail2ban?”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.
# Installapt install fail2banyum install fail2ban
# Configurecat /etc/fail2ban/jail.local[sshd]enabled = trueport = sshmaxretry = 3bantime = 3600
# Check statusfail2ban-client statusfail2ban-client status sshdInterview 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.
# Rate limiting# Nginxlimit_req_zone $binary_remote_addr zone=ddos:10m rate=100r/s;
# Fail2ban# Block repeated offenders
# Cloud protection# AWS Shield, Cloudflare, AkamaiInterview 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.
# Rate limiting with iptables# Limit connections per IPiptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW \ -m recent --setiptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW \ -m recent --update --seconds 60 --hitcount 20 -j DROP
# Limit ICMPiptables -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.confnet.ipv4.tcp_syncookies=1net.ipv4.tcp_syn_retries=2net.ipv4.tcp_max_syn_backlog=4096
# Application layer# Nginx rate limitinglimit_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.”
SELinux
Section titled “SELinux”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.
# Install policy toolsapt install policycoreutils-devel selinux-policy-dev
# Create module# myapp.temodule myapp 1.0;require { type http_t; type var_t; class file { read write };}allow http_t var_t:file { read write };
# Compilecheckmodule -M -m -o myapp.mod myapp.te
# Installsemodule -i myapp.ppInterview 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.”
Q337: How do you configure SELinux?
Section titled “Q337: How do you configure SELinux?”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.
# Check statusgetenforcesestatus
# Set modesetenforce 0 # permissivesetenforce 1 # enforcing
# Persistently# Edit /etc/selinux/configSELINUX=enforcing
# Manage contextschcon -t httpd_sys_content_t /var/www/htmlsemanage 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.”
Q338: How do you configure SELinux?
Section titled “Q338: How do you configure SELinux?”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.
# Statusgetenforcesestatus
# Set modesetenforce 0 # permissivesetenforce 1 # enforcing
# Make persistent# /etc/selinux/configSELINUX=enforcing
# Contextchcon -t httpd_sys_content_t /var/www/htmlsemanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"restorecon -Rv /web
# Booleansetsebool -P httpd_can_network_connect 1getsebool -a | grep httpdInterview 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.”
Q339: How do you configure SELinux?
Section titled “Q339: How do you configure SELinux?”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.
# Check SELinux statusgetenforcesestatus
# Set modesetenforce 1 # Enforcingsetenforce 0 # Permissive
# Configure /etc/selinux/config# SELINUX=enforcing# SELINUXTYPE=targeted
# Manage contextschcon -t httpd_sys_content_t /var/www/html/index.htmlsemanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"restorecon -Rv /web
# Boolean valuesgetsebool -asetsebool -P httpd_can_network_connect onInterview 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.”
Q340: How do you configure SELinux?
Section titled “Q340: How do you configure SELinux?”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.
# Check statusgetenforcesestatus
# Set modesetenforce 1 # Enforcingsetenforce 0 # Permissive
# Configure# /etc/selinux/configSELINUX=enforcingSELINUXTYPE=targeted
# Manage contextschcon -t httpd_sys_content_t /var/www/html/index.html
# Make persistentsemanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"restorecon -Rv /web
# Boolean valuesgetsebool -asetsebool -P httpd_can_network_connect on
# Create module# myapp.temodule myapp 1.0;require { type httpd_t; }allow httpd_t self:tcp_socket { accept listen };
# Compile and installcheckmodule -M -m -o myapp.mod myapp.tesemodule_package -o myapp.pp -m myapp.modsemodule -i myapp.ppInterview 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.
# Check SELinux statusgetenforcesestatus
# SELinux contexts# View file contextsls -Z /var/www/htmlls -Zd /var/www/html
# View process contextsps auxZ | grep nginx
# Change contextchcon -t httpd_sys_content_t /var/www/html/file.htmlsemanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"restorecon -Rv /web
# Boolean valuesgetsebool -asetsebool -P httpd_can_network_connect on
# Create custom policy module# 1. Generate Type Enforcement file# myapp.temodule 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 installcheckmodule -M -m -o myapp.mod myapp.tesemodule_package -o myapp.pp -m myapp.modsemodule -i myapp.ppInterview 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.”
AppArmor
Section titled “AppArmor”Q342: How do you configure AppArmor?
Section titled “Q342: How do you configure AppArmor?”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.
# Installapt install apparmor apparmor-profiles
# Check statusaa-status
# Enable modesaa-complain /usr/bin/nginxaa-enforce /usr/bin/nginx
# Create profilecat /etc/apparmor.d/usr.bin.myapp#include <tunables/global>/usr/bin/myapp { # Allow read /etc/myapp/** r, # Allow write /var/log/myapp/** rw,}
# Reloadapparmor_parser -r /etc/apparmor.d/usr.bin.myappInterview 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.”
Q343: How do you configure AppArmor?
Section titled “Q343: How do you configure AppArmor?”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.
# Statusaa-statusaa-enabled
# Modesaa-complain /usr/bin/nginxaa-enforce /usr/bin/nginx
# Profilecat /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,}
# Reloadapparmor_parser -r /etc/apparmor.d/usr.bin.nginxInterview 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.”
Q344: How do you configure AppArmor?
Section titled “Q344: How do you configure AppArmor?”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.
# Install AppArmorapt install apparmor apparmor-utils
# Check statusaa-status
# Create profileaa-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 modeaa-enforce /usr/bin/myapp
# Complain mode (testing)aa-complain /usr/bin/myapp
# Reload profileapparmor_parser -r /etc/apparmor.d/usr.bin.myappInterview 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.”
Q345: How do you implement AppArmor?
Section titled “Q345: How do you implement AppArmor?”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.
# Installapt install apparmor apparmor-utils
# Statusaa-statusapparmor_status
# Disable/enable profilesaa-disable /usr/sbin/namedaa-enable /usr/sbin/named
# Create profileaa-genprof /usr/bin/myapp
# Edit profilevim /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,}
# Reloadapparmor_parser -r /etc/apparmor.d/usr.bin.myapp
# Change to enforce/complain modeaa-complain /usr/bin/myappaa-enforce /usr/bin/myappInterview 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.
# Install AppArmorapt install apparmor apparmor-utils
# View profilesaa-statusls /etc/apparmor.d/
# Create profileaa-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/disableaa-disable /usr/bin/myappaa-enforce /usr/bin/myappaa-complain /usr/bin/myapp
# Reloadapparmor_parser -r /etc/apparmor.d/usr.bin.myappInterview 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.
# Generate profileaa-genprof /usr/bin/myapp
# Enforceaa-enforce /usr/bin/myapp
# Monitor in complainaa-complain /usr/bin/myapp
# Check statusaa-statusInterview 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.”
Linux Capabilities
Section titled “Linux Capabilities”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.
# View capabilities# File capabilitiesgetcap -r /usr/bin/
# Process capabilitiescat /proc/$$/status | grep Cap
# Set file capabilitiessetcap 'cap_net_raw+ep' /usr/bin/pinggetcap /usr/bin/ping
# Remove capabilitiessetcap -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.”
Q349: How do you use Linux capabilities?
Section titled “Q349: How do you use Linux capabilities?”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.
# Check capabilitiesgetcap -r /usr/bin
# Add capabilitysetcap cap_net_raw+ep /usr/bin/ping
# Check specificgetcap /usr/bin/ping
# Removesetcap -r /usr/bin/pingInterview 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.”
Q350: How do you use Linux capabilities?
Section titled “Q350: How do you use Linux capabilities?”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.
# Check capabilitiesgetcap -r /usr/bin
# Add capabilitysetcap cap_net_raw+ep /usr/bin/ping
# Checkgetcap /usr/bin/ping
# Removesetcap -r /usr/bin/ping
# Check processcat /proc/PID/status | grep CapInterview 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.”
PAM and Authentication
Section titled “PAM and Authentication”Q351: How do you configure Kerberos?
Section titled “Q351: How do you configure Kerberos?”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.
# Installapt install krb5-user
[libdefaults] default_realm = EXAMPLE.COM
[realms] EXAMPLE.COM = { kdc = kdc.example.com admin_server = kdc.example.com }
# Get ticketkinit admin@EXAMPLE.COMklistkdestroyInterview 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.”
Q352: How do you configure SSSD?
Section titled “Q352: How do you configure SSSD?”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.
# Installapt install sssd realmd
# Configure# /etc/sssd/sssd.conf[sssd]services = nss, pamdomains = LDAP
[domain/LDAP]id_provider = ldapauth_provider = ldapldap_uri = ldap://ldap.example.comldap_search_base = dc=example,dc=com
# Enablesystemctl enable sssdInterview 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.”
Q353: How do you implement MFA?
Section titled “Q353: How do you implement MFA?”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.
# MFA implementation# 1. Factors# Multiple
# 2. Methods# TOTP/Push
# 3. Rollout# Gradual
# 4. Backup# Recovery codes
# 5. Enforcement# PolicyInterview 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.”
Q354: How do you implement MFA?
Section titled “Q354: How do you implement MFA?”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.
# Factors# Multiple
# Methods# TOTP/Push
# Rollout# Gradual
# Backup# Recovery codes
# Enforcement# PolicyInterview 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.
# Install Google Authenticator PAM moduleapt install libpam-google-authenticator
# Configure PAM# /etc/pam.d/sshd# Add before @include common-authauth required pam_google_authenticator.so
# Configure SSH# /etc/ssh/sshd_configChallengeResponseAuthentication yesAuthenticationMethods password,keyboard-interactive
# For usersu - usernamegoogle-authenticator
# TOTP configuration# Add to user .google_authenticator# Store secret securely
# Testssh username@server# Enter password# Enter 6-digit codeInterview 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.
# PAM configuration filesls -la /etc/pam.d/
# Example: password policy# /etc/pam.d/common-passwordpassword required pam_pwhistory.so remember=5password [default=1] pam_permit.so
# Limit resources# /etc/security/limits.confusername soft nofile 4096username hard nofile 8192
# Time-based login# /etc/security/time.conflogin;ts001;users;Al0900-1700Interview 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.
# PAM configurationauth required pam_tally2.so deny=3 unlock_time=600
# Password policy# /etc/pam.d/common-passwordpassword required pam_pwhistory.so remember=5password requisite pam_cracklib.so try_first_pass retry=3 minlen=12
# Account expiry# /etc/login.defsPASS_MAX_DAYS 90PASS_MIN_DAYS 1PASS_WARN_AGE 14
# User expirypasswd -x 90 -w 14 -n 1 usernameInterview 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.”
Q358: How do you use authconfig?
Section titled “Q358: How do you use authconfig?”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.
# Configure authenticationauthconfig --enableshadow --enablemd5 \ --ldapserver=ldap.example.com \ --ldapbasedn="dc=example,dc=com" \ --update
# With Kerberosauthconfig --enablekrb5 \ --krb5realm=EXAMPLE.COM \ --krb5kdc=kdc.example.com \ --updateInterview 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.”
Q359: How do you use SSSD caching?
Section titled “Q359: How do you use SSSD caching?”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.
# Configure[sssd]cache_credentials = trueentry_cache_timeout = 600
# Clear cachesss_cache -E
# Debugsss_debuglevel 9
# Checkgetent passwd user@domainInterview 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.
# Configure PAMauth required pam_tally2.so deny=3 unlock_time=600 onerr=fail
# Password policy# /etc/pam.d/common-passwordpassword required pam_pwhistory.so remember=5password [default=1] pam_permit.sopassword requisite pam_cracklib.so try_first_pass retry=3 minlen=12 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1
# Set password expiry# /etc/login.defsPASS_MAX_DAYS 90PASS_MIN_DAYS 1PASS_WARN_AGE 14
# For userpasswd -x 90 -w 14 -n 1 usernamechage -M 90 -W 14 username
# View agingchage -l usernameInterview 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.”
Audit Logging
Section titled “Audit Logging”Q361: How do you audit file access?
Section titled “Q361: How do you audit file access?”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.
# Install auditapt install auditd
# Configure rulesauditctl -w /etc/passwd -p wa -k passwd_changesauditctl -w /var/www/html -p r -k web_access
# View logsausearch -k passwd_changesaureport -fInterview 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.
# Enable auditapiVersion: audit.k8s.io/v1kind: Policyrules:- 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/auditInterview 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.”
Q363: How do you configure audit logging?
Section titled “Q363: How do you configure audit logging?”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.
log_file = /var/log/audit/audit.logmax_log_file = 100max_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_changesInterview 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.”
Q364: How do you configure auditd?
Section titled “Q364: How do you configure auditd?”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.
# Installapt 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 reportaureport --summaryaureport --fileaureport --terminalInterview 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.
# PCI-DSS requirementsauditctl -w /etc/passwd -p wa -k pci_passwdauditctl -w /etc/shadow -p wa -k pci_shadowauditctl -w /var/log/ -p wa -k pci_logsauditctl -w /etc/sudoers -p wa -k pci_sudoers
# CIS benchmarksauditctl -w /etc/group -p wa -k group_changeauditctl -w /etc/hosts -p wa -k hosts_changeauditctl -w /etc/sysctl.conf -p wa -k sysctl_changeInterview 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.
# Monitor file changesauditctl -w /etc/passwd -p wa -k passwd_changeauditctl -w /etc/shadow -p wa -k shadow_change
# Monitor directoryauditctl -w /var/www/html -p r -k web_access
# Monitor commandsauditctl -w /usr/bin/rm -p x -k rm_command
# List rulesauditctl -l
# Searchausearch -k passwd_changeaureport -fInterview 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.
# Install auditdapt 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 logsausearch -k passwd_changesaureport -faureport -u
# Real-time monitoringauditctl -w /etc/passwd -p wa -k passwd_changesInterview 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.”
Q368: How do you implement audit logging?
Section titled “Q368: How do you implement audit logging?”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.
# 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 logsausearch -k passwd_changesaureport -faureport -uInterview 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.”
Q369: How do you implement audit trails?
Section titled “Q369: How do you implement audit trails?”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.
# Configure auditdauditctl -w /etc/passwd -p wa -k identityauditctl -w /etc/shadow -p wa -k identityauditctl -w /var/log/ -p wa -k logfiles
# Searchausearch -k identityaureport -fInterview 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.”
Q370: How do you set up audit logging?
Section titled “Q370: How do you set up audit logging?”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.
# Install auditapt install auditd# oryum install audit
# Configure /etc/audit/auditd.confmax_log_file = 50max_log_file_action = rotate
# Add rulesauditctl -w /etc/passwd -p wa -k passwd_changesauditctl -w /usr/bin/rm -p x -k file_delete
# View logsausearch -k passwd_changesaureport --file
# Make rules persistent# /etc/audit/rules.d/audit.rulesInterview 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.”
Q371: How do you use auditd?
Section titled “Q371: How do you use auditd?”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.
# Installapt install auditd
# Add rulesauditctl -w /etc/passwd -p wa -k passwd_changeauditctl -w /var/www/html -p r -k web_accessauditctl -w /sbin/iptables -p x -k iptables_change
# List rulesauditctl -l
# Search logsausearch -k passwd_changeaureport -f
# Enable at bootauditctl -e 2Interview 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.”
Q372: How do you use Kubernetes auditing?
Section titled “Q372: How do you use Kubernetes auditing?”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.
# Enable audit# Configure audit policy# --audit-policy-file=/path/to/policy.yaml
# Review logs# Store in secure location# Use SIEM integration# Regular reviewInterview talking point: “A well-defined audit policy balances security visibility with log volume, capturing critical events without overwhelming storage or analysis tools.”
Q373: How do you use Linux audit system?
Section titled “Q373: How do you use Linux audit system?”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.
# Installapt install auditd
# Add rulesauditctl -w /etc/passwd -p wa -k passwd_changeauditctl -w /var/www/html -p r -k web_access
# List rulesauditctl -l
# Searchausearch -k passwd_changeaureport -fInterview 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.”
File Integrity Monitoring
Section titled “File Integrity Monitoring”Q374: How do you configure AIDE?
Section titled “Q374: How do you configure AIDE?”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.
# Installapt install aide
# Configure# /etc/aide/aide.conf# Database locationdatabase=file:/var/lib/aide/aide.dbdatabase_out=file:/var/lib/aide/aide.db.new
# RulesFull = p+i+n+u+g+s+m+c+md5+sha256Lsof = 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 databaseaideinit
# Check integrityaide --checkaide --update
# Schedule# /etc/cron.d/aide0 5 * * * root /usr/bin/aide --checkInterview 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.”
Q375: How do you use AIDE?
Section titled “Q375: How do you use AIDE?”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.
# Installapt install aide
# Initializeaideinit
# Update databaseaide --update
# Checkaide --check
# Configuration /etc/aide/aide.conf/etc/ NORMAL/var/log/ LOG!/var/log/*.log
# Daily check0 5 * * * /usr/bin/aide --checkInterview 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.”
Q376: How do you use osquery?
Section titled “Q376: How do you use osquery?”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.
# Installapt install osquery
# Interactiveosqueryi
# QueriesSELECT * FROM users;SELECT * FROM processes WHERE name = 'nginx';SELECT * FROM listening_ports;SELECT * FROM file_events;
# Daemonsystemctl enable osquerydsystemctl start osquerydInterview 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.”
Q377: How do you use Tripwire?
Section titled “Q377: How do you use Tripwire?”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.
# Installapt install tripwire
# Initializetwadmin --create-polfile /etc/tripwire/tw.poltripwire --init
# Checktripwire --check
# Updatetripwire --update --accept-all
# Update policytwadmin --create-polfile /etc/tripwire/twpol.txttripwire --update-policy /etc/tripwire/twpol.txtInterview 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.
# Using AIDE (see above)
# Using tripwireapt install tripwire
# Initializetwadmin --create-polfile /etc/tripwire/tw.poltripwire --init
# Checktripwire --check
# Updatetripwire --update --accept-allInterview 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.
# Install AIDEapt install aide
# Configure# /etc/aide/aide.conf# Databasedatabase=file:/var/lib/aide/aide.dbdatabase_out=file:/var/lib/aide/aide.db.new
# RulesFip = p+i+n+u+g+s+m+c+md5+sha256Lnx = p+u+g+i+n+S
# Directories/etc Fip/bin Lnx/sbin Lnx/usr Lnx
# Initializeaideinit
# Checkaide --checkaide --update
# Cron job# /etc/cron.d/aide0 5 * * * root /usr/bin/aide --check | mail -s "AIDE Report" admin@example.comInterview 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.
# Installapt install aide
# Initialize databaseaideinit
# Configurecat /etc/aide/aide.conf!/var/log/.*!/var/cache/.*
# Update databaseaide --update
# Check integrityaide --check
# Daily cron0 5 * * * /usr/bin/aide --checkInterview 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.
# Install AIDEaideinit
# Configure# /etc/aide/aide.conf/etc/shadow NORMAL/etc/passwd NORMAL/var/log NORMAL
# Daily check0 5 * * * /usr/bin/aide --checkInterview 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.”
Q382: How do you use AIDE for integrity?
Section titled “Q382: How do you use AIDE for integrity?”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.
# Installapt install aide
# Initializeaideinit
# Update after changesaide --update
# Checkaide --check
# Configuration# /etc/aide/aide.conf/etc/pam.d/ NORMAL/etc/shadow NORMAL/var/log/ LOG!/var/log/*.logInterview 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.”
Malware and Rootkit Detection
Section titled “Malware and Rootkit Detection”Q383: How do you use chkrootkit?
Section titled “Q383: How do you use chkrootkit?”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.
# Installapt install chkrootkit
# Checkchkrootkit
# Specificchkrootkit -q
# Cron# /etc/cron.daily/chkrootkit#!/bin/shchkrootkit | 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.”
Q384: How do you use ClamAV?
Section titled “Q384: How do you use ClamAV?”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.
# Installapt install clamav
# Updatefreshclam
# Scanclamscan -r /homeclamscan -r --remove /home
# Daemonsystemctl start clamav-freshclamsystemctl start clamav-daemon
# On-accessclamfs /etc/clamfs/clamfs.xmlInterview 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.”
Q385: How do you use rkhunter?
Section titled “Q385: How do you use rkhunter?”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.
# Installapt install rkhunter
# Updaterkhunter --update
# Checkrkhunter --check
# Cron# /etc/cron.daily/rkhunter#!/bin/shrkhunter --check --skip-keypress --report-warnings-onlyInterview 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.”
Intrusion Detection/Prevention
Section titled “Intrusion Detection/Prevention”Q386: How do you configure IDS/IPS?
Section titled “Q386: How do you configure IDS/IPS?”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.
# Install Snortapt install snort
# Configure# /etc/snort/snort.confipvar HOME_NET 192.168.1.0/24ipvar EXTERNAL_NET !$HOME_NET
# Custom rules# /etc/snort/rules/local.rules# Alert on ICMPalert icmp any any -> $HOME_NET any (msg:"ICMP Ping"; sid:1000001; rev:1;)
# Alert on SSH attemptsalert tcp any any -> $HOME_NET 22 (msg:"SSH Connection Attempt"; \ flow:to_server,established; content:"SSH"; nocase; sid:1000002; rev:1;)
# Alert on port scanalert 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 snortsnort -c /etc/snort/snort.conf -i eth0
# Suricata (modern alternative)apt install suricatasuricata -c /etc/suricata/suricata.yaml -i eth0Interview 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.”
Q387: How do you use OSSEC?
Section titled “Q387: How do you use OSSEC?”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.
# Installapt 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 alertstail -f /var/ossec/logs/alerts/alerts.logInterview 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.”
Q388: How do you use Snort?
Section titled “Q388: How do you use Snort?”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.
# Installapt install snort
# Configure# /etc/snort/snort.confipvar HOME_NET 192.168.1.0/24var RULE_PATH /etc/snort/rules
# Test rulessnort -T -c /etc/snort/snort.conf
# Runsnort -i eth0 -c /etc/snort/snort.conf
# Logsls /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.”
Q389: How do you use Suricata?
Section titled “Q389: How do you use Suricata?”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.
# Installapt install suricata
# Update rulessuricata-update
# Runsuricata -i eth0suricata -c /etc/suricata/suricata.yaml -i eth0
# Logtail -f /var/log/suricata/fast.log
# Testsuricata -t /etc/suricata/suricata.yamlInterview 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.
# Network IDS (Snort)var HOME_NET 192.168.1.0/24alert 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.poltripwire --initInterview 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.
# OSSEC# Installapt 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.xmlInterview 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.
# Install AIDEapt install aide
# Configure# /etc/aide/aide.confdatabase=file:/var/lib/aide/aide.dbdatabase_out=file:/var/lib/aide/aide.db.new
# RulesFip = p+i+n+u+g+s+m+c+md5+sha256Lnx = p+u+g+i+n+S
# Files to monitor/etc Fip/bin Lnx/sbin Lnx
# Initialize databaseaideinit
# Check integrityaide --check
# Schedule checks# /etc/cron.d/aide0 5 * * * root /usr/bin/aide --check | mail -s "AIDE Report" admin@example.comInterview 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.”
Hardening Scans and Benchmarks
Section titled “Hardening Scans and Benchmarks”Q393: How do you use OpenSCAP?
Section titled “Q393: How do you use OpenSCAP?”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.
# Installapt install openscap-scanner scap-security-guide
# List profilesoscap info /usr/share/xml/scap/ssg/content/ssg-ubuntu2004-ds.xml
# Scanoscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis \ --results scan-results.xml /usr/share/xml/scap/ssg/content/ssg-ubuntu2004-ds.xml
# Generate reportoscap xccdf generate report scan-results.html scan-results.xmlInterview 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.
# Install CIS benchmark toolapt install lynis
# Run auditlynis audit systemlynis audit --profile cis-ubuntu-22.04
# Key CIS controls# 1.1.1 Disable unused filesystemsecho "install cramfs /bin/true" > /etc/modprobe.d/cramfs.confecho "install squashfs /bin/true" > /etc/modprobe.d/squashfs.conf
# 1.5.1 Set bootloader passwordgrub-mkpasswd-pbkdf2# Add to /etc/grub.d/40_custom
# 3.1 Enable syncookiessysctl -w net.ipv4.tcp_syncookies=1
# 4.1 Configure auditd# See auditd configuration earlier
# Generate reportlynis audit system --html > report.htmlInterview 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.
# Installapt install lynis
# Auditlynis audit systemlynis audit system --profile custom.prf
# Quick auditlynis quick
# Updatelynis update infoInterview 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.
# Container security scanning# 1. Build time# Scan images
# 2. Registry# Scan stored
# 3. Runtime# Scan running
# 4. Policies# Define
# 5. Automation# CI/CDInterview 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.
# Build time# Scan images
# Registry# Scan stored
# Runtime# Scan running
# Policies# Define
# Automation# CI/CDInterview 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.
# Container scanningtrivy image nginx:latestdocker scout cves myimage
# K8s security scankubescape scan --severity threshold
# Runtime securityfalco --helpInterview 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.
# Container scanningtrivy image myimage:latest
# K8s scanningkubescape scan
# Code scanningsonarqube
# Dependency scanningnpm auditsnyk testInterview 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.
# Container scanning# Trivytrivy image myimage:latesttrivy image --severity HIGH,CRITICAL myimage:latesttrivy image --exit-code 1 --severity CRITICAL myimage:latest
# Clairdocker run -p 5432:5432 -d quay.io/coreos/clair:latestclair-scanner myimage
# Infrastructure scanning# Kube-benchkube-bench run --targets node
# Kube-hunterkubectl run --rm -it --image=kubehunter/kubehunter --name kubehunter
# SAST# Bandit (Python)bandit -r myapp/
# Semgrepsemgrep --config=auto mycode/
# DAST# OWASP ZAPzap-baseline.py -t https://myapp.example.com
# Secret scanning# TruffleHogtrufflehog filesystem myrepo/
# gitleaksgitleaks --path=mydir --verboseInterview 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.
# SAST# Integrate
# DAST# Automated
# SCA# Dependencies
# Container# Scanning
# Runtime# ProtectionInterview talking point: “A layered approach spanning SAST, SCA, container, DAST, and runtime scanning catches risks that single tools miss.”
Q402: How do you perform security audits?
Section titled “Q402: How do you perform security audits?”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.
# Install audit toolsapt install lynis rkhunter chkrootkit
# Run Lynislynis audit systemlynis audit system --profile cis-ubuntu-22.04
# Run RKHunterrkhunter --checkrkhunter --propupd
# Run CHKRootKitchkrootkit
# Check open portsnmap -sT -O localhostss -tulpn
# Check usersawk -F: '($3 == 0) {print $1}' /etc/passwdlastlog
# Check logsgrep -i "failed password" /var/log/auth.loggrep -i "invalid user" /var/log/auth.log
# File integrityaide --checktripwire --checkInterview 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.”
Q403: How do you use Lynis for hardening?
Section titled “Q403: How do you use Lynis for hardening?”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.
# Installapt install lynis
# Auditlynis audit system
# Specific testslynis audit system --tests "AUTH-9262"
# Reportlynis show report
# Cron job# /etc/cron.d/lynis0 3 * * * root /usr/bin/lynis audit system --cronjobInterview 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.”
System Hardening
Section titled “System Hardening”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.
# CIS Benchmarks# Use Lynislynis audit system
# Use OpenSCAPoscap 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 ProInterview 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.
# Disable unnecessary servicessystemctl mask avahi-daemonsystemctl mask cupssystemctl mask bluetooth
# Secure kernel parameters# /etc/sysctl.confkernel.dmesg_restrict=1kernel.kptr_restrict=2kernel.yama.ptrace_scope=2kernel.sysrq=0
# Disable IPv6 if not needednet.ipv6.conf.all.disable_ipv6=1net.ipv6.conf.default.disable_ipv6=1
# Disable USB storage# /etc/modprobe.d/blacklist.confinstall usb-storage /bin/true
# Set secure umask# /etc/profileumask 027
# Password policies# /etc/login.defsPASS_MIN_LEN 12PASS_MAX_DAYS 90Interview 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.
# Web application security# 1. WAF# Deploy
# 2. Headers# Security
# 3. Input validation# Sanitization
# 4. SQL injection# Prevention
# 5. XSS# ProtectionInterview 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.
# WAF# Deploy
# Headers# Security
# Input validation# Sanitization
# SQL injection# Prevention
# XSS# ProtectionInterview talking point: “Layered controls (WAF, headers, validation) reduce attack surface, with input sanitization being key for SQLi and XSS prevention.”
Q408: How do you secure a Linux server?
Section titled “Q408: How do you secure a Linux server?”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.
# 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 everywhereInterview 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.”
Q409: How do you secure a Linux system?
Section titled “Q409: How do you secure a Linux system?”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.
# 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 everywhereInterview 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.”
Q410: How do you secure databases?
Section titled “Q410: How do you secure databases?”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.
# MySQL security# 1. Remove anonymous usersDELETE FROM mysql.user WHERE User='';
# 2. Remove remote rootDELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1');
# 3. Create application userCREATE 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 backupsInterview 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…
Q411: How do you secure databases?
Section titled “Q411: How do you secure databases?”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.
# MySQLDELETE 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 userCREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strongpassword';GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'appuser'@'localhost';
# PostgreSQL# pg_hba.confhost all all 127.0.0.1/32 md5host all all ::1/128 md5Interview 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.”
Q412: How do you secure LDAP?
Section titled “Q412: How do you secure LDAP?”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.
# TLS/SSL configurationTLS_CACERT /etc/ssl/certs/ca-certificates.crtTLS_REQCERT demand
# Enable TLS in slapd# /etc/default/slapdSLAPD_SERVICES="ldap://localhost/ ldap://localhost:7389/ ldaps://localhost:636/"
# Generate certificatesopenssl req -new -x509 -nodes -days 365 \ -keyout /etc/ldap/tls/ldap.key \ -out /etc/ldap/tls/ldap.crt
# Restrict access# /etc/ldap/slapd.confaccess to dn.base="" by * readaccess to * by self write by dn="cn=admin,dc=example,dc=com" write by * readInterview 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.
# Disable unnecessary servicessystemctl mask service_namesystemctl disable service_name
# View active servicessystemctl list-units --type=service --state=running
# Secure SSH# /etc/ssh/sshd_configPermitRootLogin noPasswordAuthentication noPubkeyAuthentication yesMaxAuthTries 3ClientAliveInterval 300X11Forwarding noAllowUsers user1 user2DenyUsers 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 512Interview 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.”
Q414: How do you secure service accounts?
Section titled “Q414: How do you secure service accounts?”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.
# 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 regularlyInterview talking point: “Avoiding the default service account and disabling auto-mount of tokens ensures pods only have the minimal credentials they actually need.”
Q415: How do you design secure systems?
Section titled “Q415: How do you design secure systems?”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.
# 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 policiesInterview 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.”
Encryption and Secrets
Section titled “Encryption and Secrets”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.
# HashiCorp Vaultvault server -dev
# Store secretsvault kv put secret/myapp api_key=xxx
# Use in application# Use kubernetes-secrets-injector or external-secrets-operatorInterview 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.
# Using HashiCorp Vaultexport VAULT_ADDR="https://vault.example.com:8200"vault login -method=token token=<token>
# Kubernetes secretskubectl create secret generic mysecret \ --from-literal=username=admin \ --from-literal=password=secret
# Using Sealed Secrets# Install controllerhelm repo add sealed-secrets https://bitnami-labs.github.io/sealed-secretshelm install sealed-secrets sealed-secrets/sealed-secrets
# Encryptkubeseal --format yaml < secret.yaml > sealed-secret.yaml
# AWS Secrets Manageraws secretsmanager get-secret-value --secret-id mysecretaws secretsmanager create-secret --name mysecret --secret-string '{"username":"admin","password":"secret"}'
# Use with CSIkubectl apply -f secret-provider-class.yamlInterview 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.
# Generate GPG keygpg --full-generate-key
# Export public keygpg --armor --export user@example.com > public.asc
# Import keygpg --import public.asc
# Encrypt filegpg -e -r user@example.com file.txt
# Decrypt filegpg -d file.txt.gpg
# Hash verificationsha256sum file.tar.gzsha256sum -c file.tar.gz.sha256
# HMACopenssl dgst -sha256 -hmac "key" file.txt
# Use keyctlkeyctl add user mykey "my secret data" @ukeyctl list @ukeyctl 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.”
Q419: How do you implement PKI?
Section titled “Q419: How do you implement PKI?”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.
# Create CAopenssl genrsa -out ca.key 4096openssl req -x509 -new -nodes -key ca.key -sha256 -days 3650 -out ca.crt
# Issue certificateopenssl genrsa -out server.key 2048openssl req -new -key server.key -out server.csropenssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365 -sha256Interview 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.
# HashiCorp Vault# Installvault server -config=config.hcl
# Enable secrets enginevault secrets enable -path=secret kv
# Write secretvault kv put secret/myapp/db password=secretpassword
# Read secretvault kv get secret/myapp/db
# Use with Kubernetes# Install Vault Agent Injectorhelm 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 Manageraws secretsmanager create-secret \ --name myapp/db \ --secret-string '{"username":"admin","password":"secret"}'
# Kubernetes Secretskubectl create secret generic myapp-secrets \ --from-literal=username=admin \ --from-literal=password=secretInterview 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.
# HashiCorp Vault# Installvault server -dev
# Store secretvault kv put secret/myapp db_password=secret123
# Use in Kubernetes# External Secrets Operator
# AWS Secrets Manageraws 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.
# Use Vault# External secrets
# Rotate regularly# Audit access
# Use encryption# Short-lived tokens
# Best practices# Use KMSInterview 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.
# Secrets management# 1. Centralized# Vault
# 2. Rotation# Auto
# 3. Audit# Log access
# 4. Encryption# Encrypt
# 5. Access control# Least privilegeInterview 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.
# Centralized# Vault
# Rotation# Auto
# Audit# Log access
# Encryption# Encrypt
# Access control# Least privilegeInterview 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.
# 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 processInterview 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.”
Q426: How do you manage secrets in Git?
Section titled “Q426: How do you manage secrets in Git?”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.
# Use SOPS# Installgo install github.com/mozilla/sops@latest
# Encryptsops -e secrets.yaml > secrets.encrypted.yaml
# Decryptsops -d secrets.encrypted.yaml
# Or use SealedSecrets# Or use external-secrets-operatorInterview 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.”
Q427: How do you use Ansible Vault?
Section titled “Q427: How do you use Ansible Vault?”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.
# Create encrypted fileansible-vault create secret.yml
# Encrypt existing fileansible-vault encrypt secrets.yml
# Edit encrypted fileansible-vault edit secrets.yml
# View encrypted fileansible-vault view secrets.yml
# Decrypt fileansible-vault decrypt secrets.yml
# Change passwordansible-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 passwordansible-playbook site.yml --ask-vault-pass# oransible-playbook site.yml --vault-password-file ~/.vault_pass.txtInterview 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.”
Q428: How do you use Docker secrets?
Section titled “Q428: How do you use Docker secrets?”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.
# Create secretecho "password" | docker secret create db_password -
# Use in servicedocker secret lsdocker secret inspect db_password
# docker-compose.ymlsecrets: db_password: external: true
# Orsecrets: db_password: file: ./db_password.txtInterview 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/v1beta1kind: ClusterSecretStoremetadata: name: aws-secrets-managerspec: provider: aws: service: SecretsManager region: us-east-1
---apiVersion: external-secrets.io/v1beta1kind: ExternalSecretmetadata: name: myapp-secretsspec: refreshInterval: 1h secretStoreRef: name: aws-secrets-manager kind: ClusterSecretStore target: name: myapp-secrets data: - secretKey: DB_PASSWORD remoteRef: key: myapp/db-passwordInterview 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.”
Q430: How do you use libvirt secrets?
Section titled “Q430: How do you use libvirt secrets?”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.
# Create secretvirsh secret-define secret.xml
# Set valuevirsh 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.
apiVersion: v1kind: Secretmetadata: name: aes-keydata: <base64-key>
# Configure API server# --encryption-provider-config=encryption-config.yaml
# Verify# Check etcd directlyetcdctl get /registry/secrets/default/secret-nameInterview 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.”
Q432: How do you secure secrets at scale?
Section titled “Q432: How do you secure secrets at scale?”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.
# Use Vault# Use external-secrets-operator# Use SealedSecrets# Use AWS Secrets Manager
# Best practices# Rotate regularly# Audit access# Use encryption# Short-lived tokensInterview talking point: “Short-lived tokens minimize exposure windows, and auditing access to secrets helps detect unauthorized usage across large clusters.”
Q433: How do you use age encryption?
Section titled “Q433: How do you use age encryption?”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.
# Installgo install filippo.io/age/cmd/age@latest
# Generate keysage-keygen
# Encryptage -p -o file.txt.age file.txt
# Decryptage -d -i key.txt file.txt.ageInterview 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.”
Q434: How do you use GPG encryption?
Section titled “Q434: How do you use GPG encryption?”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.
# Generate keygpg --full-generate-key
# Encryptgpg -e -r recipient@example.com file.txt
# Decryptgpg -d file.txt.gpg
# Signgpg -s file.txt
# Verifygpg --verify file.txt.asc
# List keysgpg --list-keysgpg --list-secret-keys
# Export/Importgpg --export -a > public.keygpg --import public.keyInterview 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.”
Q435: How do you use GPG encryption?
Section titled “Q435: How do you use GPG encryption?”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.
# Generate keygpg --full-generate-key
# Encryptgpg -e -r recipient@example.com file.txt
# Decryptgpg -d file.txt.gpg
# Symmetricgpg -c file.txtgpg -o file.txt.gpg -c file.txtInterview 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.”
Security Updates and Vulnerability
Section titled “Security Updates and Vulnerability”Q436: How do you use LinPEAS?
Section titled “Q436: How do you use LinPEAS?”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.
# Downloadcurl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh -o linpeas.sh
# Runchmod +x linpeas.sh./linpeas.sh
# Options./linpeas.sh -s # stealth./linpeas.sh -o # only interesting./linpeas.sh -P # password sprayInterview 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.
# Downloadcurl -L https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh -o les.sh
# Runchmod +x les.sh./les.sh
# With kernel version./les.sh -k 5.4.0
# Show exploits only./les.sh -pInterview 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.”
Q438: How do you use nmap?
Section titled “Q438: How do you use nmap?”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.
# Installapt install nmap
# Basic scannmap 192.168.1.1
# Scan typesnmap -sS 192.168.1.1 # SYN scannmap -sT 192.168.1.1 # TCP connectnmap -sU 192.168.1.1 # UDP scannmap -sV 192.168.1.1 # Version detection
# OS detectionnmap -O 192.168.1.1
# Scriptsnmap -sC 192.168.1.1 # Default scriptsnmap --script=vuln 192.168.1.1
# Outputnmap -oA output 192.168.1.1 # All formatsnmap -oN output.nmap 192.168.1.1Interview 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.
# Install unattended-upgrades (Debian/Ubuntu)apt install unattended-upgrades
# Configure# /etc/apt/apt.conf.d/50unattended-upgradesUnattended-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";
# Enabledpkg-reconfigure -plow unattended-upgrades
# RHEL/CentOSyum install yum-cron# /etc/yum/yum-cron.confapply_updates = yesdownload_updates = yes
# Testunattended-upgrades --dry-run --debugInterview 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.
# Use OpenVAS# Installapt install openvas
# Setupgreenbone-nvt-syncopenvasmd --rebuild
# Run scanopenvas -o scan-report.xml --target=target-id
# Or use Trivytrivy image nginx:latesttrivy 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.”
Q441: How do you handle vulnerabilities?
Section titled “Q441: How do you handle vulnerabilities?”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.
# Regular scanning# Use Trivy, Snyk, Clair
# Patch quickly# Automate updates
# Use base image scanning# Scan dependencies
# Quarantine vulnerable images# Use image policiesInterview 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.
# Vulnerability management# 1. Scanning# Regular
# 2. Prioritization# Severity
# 3. Remediation# Process
# 4. Verification# Rescan
# 5. Reporting# MetricsInterview 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.
# Scanning# Regular
# Prioritization# Severity
# Remediation# Process
# Verification# Rescan
# Reporting# MetricsInterview talking point: “Prioritizing by severity focuses effort on critical issues, while rescans and metrics track closure effectiveness over time.”
Level 12: Logging and Observability
Section titled “Level 12: Logging and Observability”syslog and rsyslog
Section titled “syslog and rsyslog”Q444: How do you configure rsyslog?
Section titled “Q444: How do you configure rsyslog?”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.
# Load modulesmodule(load="imudp")module(load="imtcp")
# Inputinput(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 onInterview 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.”
Q445: How do you configure rsyslog?
Section titled “Q445: How do you configure rsyslog?”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.
# 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.”
Q446: How do you configure rsyslog?
Section titled “Q446: How do you configure rsyslog?”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.
# 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/messagesauthpriv.* /var/log/securemail.* -/var/log/maillogcron.* /var/log/cron
# Filter by program:programname, isequal, "apache" /var/log/apache.log
# Stop processing& stopInterview 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.
# Module$ModLoad imuxsock$ModLoad imjournal
# Template$template RemoteLogs,"/var/log/%HOSTNAME%/%PROGRAMNAME%.log"
# Forward all*.* @@syslog.example.com:514Interview 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.
# 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=persistentCompress=yesSystemMaxUse=500MMaxRetentionSec=30day
# Forward to syslogForwardToSyslog=yes
# View logsjournalctl -u servicejournalctl --since "1 hour ago"journalctl -p err
# Log rotation# /etc/logrotate.confdailyrotate 14compressInterview 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.
# Filebeat configurationfilebeat.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 scriptanalyze_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.”
Q450: How do you manage syslog?
Section titled “Q450: How do you manage syslog?”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.
# Rsyslog configcat /etc/rsyslog.conf# Rules*.info;mail.none;authpriv.none /var/log/messagesauthpriv.* /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.
# Use syslog-ngsource 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.”
journald Configuration
Section titled “journald Configuration”Q452: How do you configure journald?
Section titled “Q452: How do you configure journald?”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.
[Journal]SystemMaxUse=500MSystemKeepFree=100MRuntimeMaxUse=200MRuntimeKeepFree=50MMaxFileSec=1monthForwardToSyslog=yesCompress=yes
# Reloadsystemctl restart systemd-journaldInterview 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.”
Q453: How do you configure journald?
Section titled “Q453: How do you configure 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.
[Journal]Storage=persistentCompress=yesSystemMaxUse=500MSystemMaxFileSize=50MMaxRetentionSec=30day
# Forward to syslogForwardToSyslog=yesForwardToKMsg=noForwardToWall=no
# Rate limitingRateLimitIntervalSec=30sRateLimitBurst=1000
# View logsjournalctljournalctl -u nginxjournalctl --since "2024-01-01"journalctl --since "1 hour ago"journalctl -p errjournalctl -f
# Persistent storagemkdir -p /var/log/journalsystemd-tmpfiles --create --prefix /var/log/journalInterview 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.”
Log Rotation
Section titled “Log Rotation”Q454: How do you rotate logs?
Section titled “Q454: How do you rotate logs?”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.
# Logrotate configcat /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.”
Q455: How do you rotate logs?
Section titled “Q455: How do you rotate logs?”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.
# Global settingsdailyrotate 14compressdelaycompressmissingoknotifemptycreate 0640 root adm
# Include configsinclude /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}
# Testlogrotate -d /etc/logrotate.conflogrotate -f /etc/logrotate.d/nginxInterview 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.
# logrotate/var/log/myapp/*.log { daily rotate 90 compress delaycompress missingok create 0640 user group}
# Or with systemd# journald.confSystemMaxUse=500MMaxFileSec=1monthInterview 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.”
Q457: How do you configure logrotate?
Section titled “Q457: How do you configure logrotate?”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.
/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.”
Q458: How do you use logrotate?
Section titled “Q458: How do you use logrotate?”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.
/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 runlogrotate -f /etc/logrotate.conflogrotate -d /etc/logrotate.conf # debugInterview 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.”
Application and Service Logs
Section titled “Application and Service Logs”Q459: How do you view system logs?
Section titled “Q459: How do you view system logs?”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.
# System logstail -f /var/log/messagestail -f /var/log/syslog
# Auth logstail -f /var/log/auth.logtail -f /var/log/secure
# Application logstail -f /var/log/nginx/access.log
# Journaljournalctljournalctl -u servicejournalctl -fInterview 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.
# Grep patternsgrep ERROR /var/log/messagesgrep -c "pattern" file
# Awk analysisawk '/ERROR/ {count++} END {print count}' file
# Sort and countawk '{print $5}' access.log | sort | uniq -c | sort -rn
# Time-basedawk '$4 >= "[10/Oct/2023:10:00"' access.logInterview 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.
# Using grepgrep -i error /var/log/syslog | head -20grep -v "INFO" /var/log/app.log
# Using awkawk '/ERROR/ {print $1, $5}' /var/log/app.logawk '{print $NF}' /var/log/access.log | sort | uniq -c | sort -rn
# Using cutcut -d' ' -f1 /var/log/access.log | sort | uniq -c
# Using logrotate with logwatchapt install logwatch
# Using GoAccessgoaccess /var/log/nginx/access.log -o /var/www/html/report.html
# Using lnavlnav /var/log/sysloglnav /var/log/*.logInterview 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.”
Q462: How do you analyze logs with ELK?
Section titled “Q462: How do you analyze logs with ELK?”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.
# Install Elasticsearchdocker run -d -p 9200:9200 elasticsearch:7
# Install Kibanadocker run -d -p 5601:5601 kibana:7
# Install Logstashdocker run -d -p 5044:5044 logstash:7 -f /etc/logstash/conf.d/
# Filebeat configurationfilebeat.inputs:- type: log paths: - /var/log/*.logoutput.logstash: hosts: ["localhost:5044"]
# Ingest pipelineinput { 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.”
Q463: How do you implement log analysis?
Section titled “Q463: How do you implement log analysis?”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.
# Log analysis# ELK Stack# Elasticsearch# Logstash# Kibana
# Loki# Grafana + Loki
# Structured logging# JSON formatimport jsonimport 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 errorsgrep -i error /var/log/app.log
# Count by hourawk '{print $2}' /var/log/app.log | sort | uniq -c
# Slow requestsawk '$9 > 5 {print}' /var/log/nginx/access.logInterview 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.”
Q464: How do you implement logging?
Section titled “Q464: How do you implement logging?”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.
# 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# PolicyInterview 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.”
Q465: How do you implement logging?
Section titled “Q465: How do you implement logging?”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.
# Format# JSON# Structured
# Levels# DEBUG, INFO, WARN, ERROR
# Correlation# Trace IDs
# Rotation# Logrotate
# Aggregation# ELK/Loki
# Retention# PolicyInterview 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.
# Using rsyslog# Server$ModLoad imtcp$InputTCPServerRun 514
# Client*.* @@logging-server:514
# Or ELK stack# Filebeat -> Logstash -> Elasticsearch -> KibanaInterview 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.”
Q467: How do you use log analysis tools?
Section titled “Q467: How do you use log analysis tools?”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.
# GoAccessgoaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html
# Splunk forwarder# Install and configure/opt/splunkforwarder/bin/splunk start
# ELKfilebeat modules enable nginxfilebeat modules enable systemInterview 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.”
Log Centralization
Section titled “Log Centralization”Q468: How do you centralize logs?
Section titled “Q468: How do you centralize logs?”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.
# Using rsyslog# Server$ModLoad imtcp$InputTCPServerRun 514
# Client*.* @@server:514
# Or using ELK# Filebeat -> Logstash -> Elasticsearch -> Kibana
# Or using Loki# Promtail -> Loki -> GrafanaInterview 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.”
Q469: How do you centralize logs?
Section titled “Q469: How do you centralize logs?”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.
# ELK Stack
# Filebeat on clientsfilebeat.inputs: - type: log paths: - /var/log/*.log fields: type: syslogoutput.logstash: hosts: ["logstash:5044"]
# Logstash config# /etc/logstash/conf.d/01-input.confinput { beats { port => 5044 }}
# Filterfilter { 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.”
Q470: How do you configure graylog?
Section titled “Q470: How do you configure graylog?”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.
# Install Graylog# Using OVA or AMI
# Configure inputs# Web UI -> System -> Inputs -> GELF UDP
# Configure sidecarapt install graylog-sidecargraylog-sidecar -c /etc/graylog/sidecar/sidecar.yml
# Filebeat configurationfilebeat.inputs:- type: log paths: - /var/log/syslog fields: type: syslog fields_under_root: trueInterview 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.
# Filebeat configurationfilebeat.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.confinput { beats { port => 5044 }}
# /etc/logstash/conf.d/02-filter.conffilter { 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.”
Q472: How do you set up ELK Stack?
Section titled “Q472: How do you set up ELK Stack?”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.
# Install Elasticsearchdocker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch
# Install Kibanadocker run -d -p 5601:5601 kibana
# Install Logstashdocker run -d -p 5044:5044 logstash
# Configure filebeat on clientsfilebeat.modules: - systemoutput.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.”
Q473: How do you set up ELK stack?
Section titled “Q473: How do you set up ELK stack?”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.
# Install Elasticsearchapt install elasticsearchsystemctl enable elasticsearch
# Configure# /etc/elasticsearch/elasticsearch.ymlcluster.name: myclusternetwork.host: 0.0.0.0discovery.type: single-node
# Install Kibanaapt install kibana
# Install Logstashapt install logstash
# Filebeat configuration# /etc/filebeat/filebeat.ymlfilebeat.inputs: - type: log paths: - /var/log/*.logoutput.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.”
Q474: How do you use Analog?
Section titled “Q474: How do you use Analog?”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.
# Installapt install analog
# Configure# /etc/analog.cfgLOGFILE /var/log/apache2/access.logOUTFILE /var/www/html/analog.htmlHOSTNAME myserver.comInterview 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.”
Q475: How do you use AWStats?
Section titled “Q475: How do you use AWStats?”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.
# Installapt install awstats
# Configure# /etc/awstats/awstats.mysite.confSiteName="mysite.com"LogFile="/var/log/apache2/access.log"DirData="/var/lib/awstats"
# Generateawstats_updateall.pl nowawstats -config=mysite -output -staticlinks > /var/www/html/awstats.htmlInterview 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.”
Q476: How do you use Elastic APM?
Section titled “Q476: How do you use Elastic APM?”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.
# Installdocker 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:latestInterview 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.”
Q477: How do you use Elasticsearch?
Section titled “Q477: How do you use Elasticsearch?”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.
# Installdocker run -d -p 9200:9200 -p 9300:9300 elasticsearch
# Create indexcurl -X PUT "localhost:9200/myindex"
# Add documentcurl -X POST "localhost:9200/myindex/_doc" -H 'Content-Type: application/json' -d'{"field":"value"}'
# Searchcurl -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.”
Q478: How do you use ELK Stack?
Section titled “Q478: How do you use ELK Stack?”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.
# Elasticsearchdocker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7
# Kibanadocker run -d -p 5601:5601 kibana:7
# Logstashdocker 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/*.logoutput.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.”
Q479: How do you use ELK stack?
Section titled “Q479: How do you use ELK stack?”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.
# Install Elasticsearchapt install elasticsearch
# Configure# /etc/elasticsearch/elasticsearch.ymlcluster.name: myclusternetwork.host: 0.0.0.0
# Install Kibanaapt install kibana# /etc/kibana/kibana.yml# server.host: "0.0.0.0"
# Install Logstashapt install logstash
# Configure Filebeatapt install filebeat# /etc/filebeat/filebeat.ymlfilebeat.inputs: - type: log paths: - /var/log/*.logoutput.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.”
Q480: How do you use GoAccess with AWS?
Section titled “Q480: How do you use GoAccess with AWS?”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.
# Download logsaws s3 cp s3://bucket/logs/ ./logs/
# Analyzegoaccess access.log*.log -a -o report.html
# With GeoIPgoaccess access.log -a -o report.html --geoip-database=GeoLite2-City.mmdbInterview 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.”
Q481: How do you use GoAccess?
Section titled “Q481: How do you use GoAccess?”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.
# Installapt install goaccess
# Real-timegoaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html
# Generate staticgoaccess /var/log/nginx/access.log -o report.htmlInterview 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.”
Q482: How do you use Kibana?
Section titled “Q482: How do you use Kibana?”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.
# Installdocker run -d -p 5601:5601 kibana
# Connect to Elasticsearch# Kibana -> Settings -> Indices
# Create visualization# Visualize -> Create new
# Create dashboard# Dashboard -> Create newInterview 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.”
Q483: How do you use Loki?
Section titled “Q483: How do you use Loki?”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.
# Installdocker run -d -p 3100:3100 grafana/loki
# Configure Promtail# /etc/promtail/promtail.yamlserver: http_listen_port: 9080 grpc_listen_port: 0clients: - url: http://loki:3100/api/prom/pushscrape_configs:- job_name: system static_configs: - targets: [localhost] labels: job: varlogs __path__: /var/log/*.logInterview 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.”
Q484: How do you use Loki?
Section titled “Q484: How do you use Loki?”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.
# Helmloki: auth_enabled: false
schema_config: configs: - from: 2022-01-01 store: boltdb-shipper object_store: s3 schema: v11 index: prefix: loki_index_ period: 24hInterview 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.”
Q485: How do you use Piwik/Matomo?
Section titled “Q485: How do you use Piwik/Matomo?”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.
# Install via Dockerdocker 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.”
Q486: How do you use splunk forwarder?
Section titled “Q486: How do you use splunk forwarder?”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.
# Installdpkg -i splunkforwarder-latest.deb
# Start/opt/splunkforwarder/bin/splunk start --accept-license
# Configure inputscat /opt/splunkforwarder/etc/system/local/inputs.conf[monitor:///var/log/syslog]sourcetype = syslog
# Configure outputscat /opt/splunkforwarder/etc/system/local/outputs.conf[tcpout:default-autolb-group]server = splunk-server:9997
# Enable boot start/opt/splunkforwarder/bin/splunk enable boot-startInterview 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.”
Monitoring Tools
Section titled “Monitoring Tools”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.
# Using nethogsapt install nethogsnethogs eth0
# Using iftopapt install iftopiftop
# Using bmonapt install bmonbmon
# Using iptraf-ngapt install iptraf-ngiptraf-ng
# Using vnstatapt install vnstatvnstat -l -i eth0Interview 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.
# Use Prometheus + blackbox exporterdocker run -d -p 9115:9110 prom/blackbox-exporter
# Configure# /etc/blackbox/blackbox.ymlmodules: http_2xx: prober: http
# Prometheus scrape- job_name: blackbox metrics_path: /probe static_configs: - targets: - https://example.comInterview 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.
# APM (Application Performance Monitoring)# Jaeger# Pythonfrom opentelemetry import trace
tracer = trace.get_tracer(__name__)with tracer.start_as_current_span("operation") as span: span.set_attribute("key", "value")
# Prometheus metricsfrom 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 probeslivenessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 30 periodSeconds: 10
readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 5 periodSeconds: 5Interview 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.
# Compliance monitoring# 1. Controls# Continuous
# 2. Alerts# Deviation
# 3. Reporting# Regular
# 4. Remediation# Tracking
# 5. Audit# SupportInterview 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.
# Controls# Continuous
# Alerts# Deviation
# Reporting# Regular
# Remediation# Tracking
# Audit# SupportInterview 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.
# Infrastructure monitoring# Prometheus + Grafana# Node exporternode_exporter --collector.filesystem.mount-points-exclude="^/(sys|proc|run)"
# Custom metrics# Python clientfrom 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 + GrafanaInterview 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.
# Infrastructure monitoring# 1. Metrics# Collect
# 2. Storage# Time-series
# 3. Visualization# Dashboards
# 4. Alerting# Thresholds
# 5. Analysis# TrendsInterview 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.
# Metrics# Collect
# Storage# Time-series
# Visualization# Dashboards
# Alerting# Thresholds
# Analysis# TrendsInterview 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 rulesgroups: - 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.ymlroute: 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.
# Prometheus + node_exporter# Installapt install prometheus-node-exporter
# Configure# /etc/default/prometheusARGS="--collector.interval=30s"
# Start servicesystemctl start prometheus-node-exportersystemctl enable prometheus-node-exporter
# Metricscurl http://localhost:9100/metricsInterview 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.”
Q497: How do you set up monitoring stack?
Section titled “Q497: How do you set up monitoring stack?”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.
# Use Prometheus + Grafana + Alertmanager# Install via Helmhelm repo add prometheus-community https://prometheus-community.github.io/helm-chartshelm install prometheus prometheus-community/kube-prometheus-stack
# Accesskubectl port-forward svc/prometheus-grafana 3000Interview 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.
# Installapt install prometheus# ortar -xzf prometheus-*.tar.gz
# Configuration# /etc/prometheus/prometheus.ymlglobal: 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 metricscurl http://localhost:9100/metricsInterview 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.
# Use Prometheus- job_name: 'service' static_configs: - targets: ['localhost:8080']
# Health check endpoint#!/bin/bashcurl -f http://localhost:8080/health || exit 1Interview 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.”
Q500: How do you use sar for monitoring?
Section titled “Q500: How do you use sar for monitoring?”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.
# Installapt install sysstat
# Enable data collectionsystemctl enable sysstatsystemctl start sysstat
# CPU statssar -u 1 5# All CPUsar -P ALL 1 3
# Memorysar -r 1 3
# Swapsar -S 1 3
# I/Osar -b 1 3
# Networksar -n DEV 1 3
# Generate reportsar -A > /tmp/sar_report.txtInterview 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.”