Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 80 ยท Practice and Review

Cybersecurity Interview Questions

Common cybersecurity interview questions with clear model answers: principles, cryptography, authentication, web attacks, networks, operations and cloud, plus coding drills.

Security interviews test judgment more than memory. Interviewers want to hear that you know the vocabulary, can explain why a defense works, understand its limits, and can think through a messy situation out loud. A strong answer is short, correct, and ends with a trade-off or an example.

Below are common questions grouped by topic, each with a model answer of two to four sentences. Treat them as a model to rephrase in your own words, not text to memorize. The links lead to the lessons that teach the details. At the end are three small coding drills of the kind used in technical screens.

Foundations

What are the CIA triad and the principle of least privilege?

The triad is confidentiality (only authorized parties can read data), integrity (data is not altered without authorization) and availability (systems work when needed). Least privilege means every user, process and service gets only the access it needs for its job and no more, which limits the damage when an account is abused or stolen. See The CIA Triad and Core Principles.

What is the difference between a threat, a vulnerability and a risk?

A vulnerability is a weakness, a threat is something or someone that could exploit it, and risk is the likelihood and impact of that happening to a particular asset. A flaw on a server with no valuable data and no network access is a vulnerability but a small risk. See Threats, Vulnerabilities and Risk.

What is defense in depth, and why not rely on a perfect firewall?

Defense in depth uses several independent layers (network controls, strong authentication, patching, monitoring, backups) so that one failure does not mean total compromise. Every single control has gaps, and attackers need only one, so layers turn a single breach into a contained incident.

How would you threat-model a new login page?

Draw the data flow (browser, server, user database), mark the trust boundaries, and walk through STRIDE: spoofing (credential stuffing, phishing), tampering (altered requests), repudiation (no audit log), information disclosure (verbose errors, user enumeration), denial of service (login flooding) and elevation of privilege (broken access control). Then pick mitigations such as multi-factor authentication, rate limiting and uniform error messages. See Threat Modeling with STRIDE.

Cryptography

What is the difference between encoding, hashing and encryption?

Encoding (such as Base64) changes representation for transport and anyone can reverse it. Hashing is one-way: it produces a fixed-size fingerprint used for integrity checks and password storage. Encryption is reversible only with the right key and provides confidentiality. Mixing them up is the most common beginner mistake, and the first coding drill below makes the difference visible. See Cryptography in Plain Language.

Why are MD5 and SHA-1 not used for security anymore?

Practical collision attacks exist: attackers can create two different inputs with the same hash, which breaks signatures and integrity checks. Use SHA-256 or SHA-3, and for passwords use a slow, salted function. See Hash Functions and Integrity.

Why is HMAC better than hashing the key and message together?

Plain hash(key + message) is vulnerable to length-extension attacks on Merkle-Damgard hashes, while HMAC's nested construction is not. HMAC also gives authenticity, because only someone holding the key can produce a valid tag. Compare tags in constant time. See HMAC and Message Authentication.

When would you use symmetric and when asymmetric encryption?

Symmetric encryption (AES-GCM, ChaCha20-Poly1305) is fast and used for bulk data, but both sides need the same key. Asymmetric cryptography solves key distribution and enables signatures, but is slower, so protocols such as TLS use it to agree on a symmetric session key. See Symmetric Encryption and Modes and Public-Key Cryptography.

Why must a nonce never repeat with the same key, and why avoid ECB mode?

With stream-like modes such as CTR and GCM, a repeated nonce repeats the keystream, so XORing two ciphertexts cancels the key and leaks plaintext relationships (and in GCM it can leak the authentication key). ECB encrypts identical blocks identically, so patterns in the data stay visible.

What happens during a TLS handshake, in brief?

The client and server agree on a protocol version and cipher suite, the server presents a certificate chain that the client validates (trusted CA, valid dates, matching name), and both sides derive fresh session keys through a key exchange. From then on, data is encrypted and authenticated. See TLS, Certificates and PKI.

Authentication and access control

How should passwords be stored?

Never in plain text or with a fast hash. Use a slow, memory-hard algorithm such as Argon2id or scrypt (or PBKDF2 where required), with a unique random salt per user and tuned cost, and compare in constant time. Salts defeat precomputed tables; the cost slows guessing. See Password Storage Done Right.

Why is multi-factor authentication stronger, and what are its weak points?

It requires proof from different categories (something you know, have, are), so a stolen password alone is not enough. SMS codes can be intercepted or SIM-swapped and one-time codes can be phished in real time, which is why phishing-resistant passkeys are preferred. See Multi-Factor Authentication and Passkeys.

Server sessions or JWTs: what are the trade-offs?

Server-side sessions are easy to revoke and keep data on the server, but need shared storage when scaling. JWTs are self-contained and convenient across services, but hard to revoke before expiry, readable by anyone holding them, and prone to bugs such as accepting alg: none. Use short lifetimes and strict verification. See Sessions, Cookies and JWTs.

What is the difference between authentication and authorization, and what is an IDOR?

Authentication asks who you are; authorization asks what you may do. An insecure direct object reference is an authorization bug: the app trusts an ID in the request (/invoice/1042) without checking that the signed-in user owns that object. Fix it with a check on every request, deny by default. See Authorization and Access Control Models.

Why does OAuth use PKCE and a state parameter?

PKCE binds the authorization code to the client that started the flow, so a stolen code is useless. state ties the callback to the original request and prevents cross-site request forgery against the login flow. See OAuth 2.0, OpenID Connect and SSO.

Web application security

What is SQL injection and how do you prevent it?

It happens when untrusted input is concatenated into SQL, so the input changes the query's structure. Use parameterized queries (or an ORM used correctly) so values never become SQL, give the database account minimal privileges, and map identifiers to allow-lists. See SQL Injection and Parameterized Queries.

Explain reflected, stored and DOM-based XSS, and the defenses.

Reflected XSS bounces a payload from the request into the response, stored XSS keeps it in the database to hit every viewer, and DOM-based XSS happens entirely in client-side code. Defend with context-aware output encoding, avoiding dangerous sinks such as innerHTML, sanitizing any HTML you must accept, and a Content Security Policy as a backstop. See Cross-Site Scripting and Output Encoding.

What is the difference between XSS and CSRF?

XSS runs attacker code inside your site's origin, so it can read data and act as the user. CSRF makes the victim's browser send a request the user did not intend, relying on the browser attaching cookies automatically. Tokens, SameSite cookies and origin checks defend against CSRF; encoding and CSP defend against XSS. See CSRF, SameSite and CORS.

Does CORS protect my server from other websites?

No. CORS relaxes the browser's same-origin policy for reading responses; it does not authenticate callers and does not stop requests from non-browser clients. A permissive setting such as reflecting any origin with credentials enabled is itself a vulnerability.

What is SSRF and why is it dangerous in the cloud?

Server-side request forgery makes your server fetch a URL the attacker chooses, reaching internal services and cloud metadata endpoints that expose credentials. Defend with allow-lists of hosts, resolving and checking the IP address (and re-checking after redirects), blocking private and link-local ranges, and metadata services that require extra headers or tokens. See SSRF, Unsafe Deserialization and XXE.

Which HTTP security headers matter most?

Strict-Transport-Security (force HTTPS), Content-Security-Policy (limit script sources and framing), X-Content-Type-Options: nosniff, Referrer-Policy, and cookie flags Secure, HttpOnly and SameSite. See HTTP Security Headers.

Networks

How does a stateful firewall differ from a simple packet filter, and what is zero trust?

A packet filter judges each packet in isolation; a stateful firewall tracks connections, so it allows replies only to requests that were actually made. Zero trust drops the idea of a trusted inside: every request is authenticated, authorized and checked against device health, whatever network it comes from. See Firewalls, Segmentation and Zero Trust.

How would you mitigate a DDoS attack?

Absorb and filter upstream: use a CDN or scrubbing service with large capacity, rate-limit per client, cache aggressively, scale out where possible and have an incident plan. You cannot beat volumetric floods from a single server. See Common Network Attacks and Defenses.

What is a man-in-the-middle attack and how does TLS stop it?

An attacker positioned between two parties reads or alters traffic. TLS defeats it by encrypting traffic and, crucially, authenticating the server through a certificate chain; users who click through certificate warnings undo this protection. HSTS removes the option of downgrading to HTTP.

IDS or IPS?

An intrusion detection system observes and alerts; an intrusion prevention system sits in the traffic path and can also block. Prevention risks blocking legitimate traffic on false positives, so many teams start in detect-only mode and tune rules first. See Intrusion Detection and Network Monitoring.

Secure coding and operations

Why do memory-safety bugs matter, and how are they reduced?

Buffer overflows and use-after-free errors let attackers corrupt memory and sometimes run code. Memory-safe languages remove whole classes of them; for C and C++, use bounds-checked containers, compiler hardening (stack protectors, ASLR, DEP) and sanitizers in testing. See Memory Safety and Why Languages Matter.

How do you reduce supply chain risk?

Pin and lock versions, review new dependencies, scan for known vulnerabilities, watch for typosquatted names, verify signatures where available, build in a clean environment and keep a software bill of materials. See Dependency and Supply Chain Security.

Walk me through the incident response phases.

Preparation; detection and analysis; containment (stop the spread, preserve evidence); eradication (remove the cause); recovery (restore and monitor); and lessons learned. Mention communication with stakeholders and keeping a timeline from the start. See the Practice: Detection and Response exercises for a worked timeline.

How do you prioritize a hundred vulnerabilities?

Start with known exploitation and exposure, then use severity (CVSS) and asset criticality, then compensating controls. A 9.8 on an isolated test box may wait; a 7.5 under active attack on an internet-facing server may not.

What is the difference between RTO and RPO, and what is the 3-2-1 backup rule?

RTO is how long you can be down; RPO is how much data you can afford to lose, measured in time. 3-2-1 means three copies, on two kinds of media, with one offsite (and offline or immutable against ransomware). Test restores regularly. See Backups, Resilience and Business Continuity.

Three coding drills

Technical screens often ask for a short function with a security twist. Practice these and then explain what each one defends against.

Drill 1: encoding, hashing and encryption side by side

Python Drill 1: three different tools

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The talking points: only encryption needs a key, only hashing has a fixed output size and cannot be undone, and encoding offers no protection at all.

Drill 2: deny by default and the IDOR check

Python Drill 2: an authorization check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The talking points: authorization is checked on every request on the server, ownership matters in addition to the role, and anything not explicitly allowed is denied.

Drill 3: an SSRF-safe URL check

Python Drill 3: validating a fetch target

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The talking points: allow-list rather than deny-list, check the resolved address and then connect to that exact address (so a second DNS lookup cannot change the answer), and re-validate every redirect.

Extra topics interviewers like

These shorter questions come up often as warm-ups or follow-ups. Give the definition first, then one concrete example or defence, and you will sound precise.

What is perfect forward secrecy (PFS)?

A property of a key exchange: each session uses fresh, temporary keys that are discarded afterwards, so stealing a server's long-term private key later does not let an attacker decrypt traffic they recorded earlier. It is achieved with ephemeral Diffie-Hellman (ECDHE) and is built into TLS 1.3. See TLS, Certificates and PKI.

What is a replay attack, and how do you stop it?

The attacker records a valid message (a login, a payment request, an authentication token) and sends it again later. Encryption alone does not help, because the replayed bytes are genuine. Defences make each message unique or short-lived: nonces, timestamps with a small validity window, sequence numbers (as in IPsec and TLS), one-time tokens and a server-side cache of recently seen values. See Kerberos, LDAP and RADIUS and IPsec, IKE, AH and ESP.

What is a null session?

An anonymous connection to a Windows file-sharing service (SMB) made with no username or password, which on old, unhardened systems could list users, shares and policies and so help an attacker map a network. Modern systems restrict anonymous access by default; keep them patched, block SMB from the internet, disable SMBv1, and use least privilege on shares.

What is a honeypot?

A decoy system or account that looks valuable but has no legitimate use, so any contact with it is suspicious. Low-interaction honeypots emulate a few services; high-interaction ones are real systems under heavy monitoring. They give early warning and let defenders study attacker behaviour, but they must be isolated so they cannot become a stepping stone. Honeytokens (fake credentials, database rows or documents) work the same way. See Logging, Log Analysis and SIEM.

What is a polymorphic virus, and why does it defeat simple antivirus?

Malware that changes its own code (usually by encrypting its body with a new key and mutating its decryptor) each time it spreads, so every copy has a different byte signature. Simple signature matching misses it. Detection relies on behaviour, emulation, memory scanning and heuristics. Metamorphic malware goes further and rewrites its entire code. See Malware Types and How They Spread and Detecting Malicious Behavior.

What are EDR, XDR and the difference between them?

EDR (endpoint detection and response) records activity on laptops and servers (processes, files, network connections), detects suspicious behaviour and lets analysts isolate a host and investigate. XDR (extended detection and response) correlates data from several layers (endpoints, email, identity, network, cloud) in one platform, so a chain of events that looks harmless in each tool alone becomes visible. Both complement a SIEM and a SOC rather than replace them. See Endpoint Protection and System Hardening.

What is Blowfish, and is it still a good choice?

Blowfish is a symmetric block cipher designed by Bruce Schneier in 1993: 64-bit blocks, key sizes from 32 to 448 bits, fast in software and free to use. Its 64-bit block size is the weakness: when large amounts of data are encrypted under one key, block collisions become likely (the "Sweet32" type of issue). Its successor Twofish and the standard AES (128-bit blocks) are preferred, and for passwords the bcrypt scheme builds on Blowfish's key setup. See Symmetric Encryption and Modes.

What does traceroute do, and how can it help or be abused?

It shows the path packets take to a destination by sending packets with increasing TTL (time-to-live) values; each router that decrements the TTL to zero returns an ICMP "time exceeded" message, revealing its address and the round-trip time. Defenders use it to find where latency or loss occurs and to understand routing. Attackers can use it for network mapping, so firewalls often limit ICMP responses. See Networking Essentials for Defenders.

What is shoulder surfing, and how do you reduce it?

Watching someone enter a password, PIN or private information over their shoulder, or filming it from a distance. Reduce it with privacy screen filters, positioning screens away from public view, covering the keypad, using biometrics or passkeys instead of typed secrets in public, and being aware of cameras. It is a classic example of a threat no software control can stop, which is why awareness training matters (Phishing and Social Engineering).

Quick drill: stop a replayed request

Interviewers sometimes ask you to sketch the fix. This sketch shows a request that is accepted once, then rejected when replayed or when it is too old:

Python Nonce and timestamp replay protection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Questions to ask back

Interviews run both ways. Good questions show maturity: How do you track and fix vulnerabilities, and what is your typical time to patch? Who owns security decisions during a release? How often do you rehearse incident response? What does the team do with a near miss?

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An interviewer asks how to protect against CSRF. Which answer is strongest?

    CSRF abuses automatic cookie sending, so the defense is to require something the attacker's page cannot supply, backed by SameSite and origin checks. HTTPS and CORS do not address it.
  2. 2. Which statement correctly separates hashing from encryption?

    A hash is a one-way fingerprint. Encryption is designed so that the key holder can recover the plaintext.
  3. 3. Why is a 'detect' mode often used first for an IPS?

    Blocking on a poorly tuned rule can cut off legitimate users, so teams observe and tune before turning on prevention.
  4. 4. What is the best response when you do not know the answer in an interview?

    Security work constantly meets unknowns. Showing a sound method and honesty about limits is what interviewers are looking for.

Summary

  • Good answers define the term, explain why the defense works, name its limits and give an example.
  • Know the pairs people confuse: encoding, hashing, encryption; authentication, authorization; XSS, CSRF; threat, vulnerability, risk; RTO, RPO; IDS, IPS.
  • Cover the standard defenses: parameterized queries, output encoding, tokens plus SameSite, slow salted password hashing, least privilege, layered controls and tested backups.
  • For incidents, describe the phases, the timeline and how you would prioritize.
  • Prepare coding drills (authorization checks, validation, URL allow-lists) and explain the attack each one stops.

Next: Cybersecurity Cheat Sheet, a one-page recap of principles, crypto choices, OWASP defenses, headers and response steps.