Cybersecurity Engineer Top 100 Interview Questions
100 cybersecurity engineer interview questions with structured answers, comparison tables, flow diagrams, worked calculations and runnable code. Covers security fundamentals, cryptography, network and application security, identity, detection, incident response and vulnerability management, from the basics to design and scenario questions.
Questions 21-40 of 100
Q21.What is forward secrecy, and why does it matter?
Forward secrecy means that stealing a server's long-term private key later does not let an attacker decrypt traffic recorded earlier. Each session uses fresh, temporary keys that are discarded after use.
Static key exchange Ephemeral key exchange Session key derived from the server's long-term key Session key derived from temporary keys made per session A later key theft decrypts all recorded past traffic Past sessions stay protected after a key theft Removed in TLS 1.3 Required in TLS 1.3 Why it matters:
- Record now, decrypt later: an attacker can capture encrypted traffic for years and wait for a key leak, a court order or future computing advances.
- Limits breach impact: a compromised server key exposes only sessions made while the attacker holds it.
Ways forward secrecy is weakened in practice:
- Session resumption tickets are encrypted with a server key; if that key is never rotated, stealing it exposes resumed sessions.
- Long-lived pre-shared keys used without an ephemeral exchange give no forward secrecy.
Rotate ticket keys frequently and keep ephemeral key exchange enabled for every connection.
Q22.Why is authenticated encryption preferred over older block cipher modes?
Authenticated encryption protects both confidentiality and integrity in one step: it encrypts the data and adds a tag that fails to verify if a single bit is changed. Older modes only hide data, which leaves room for tampering and padding attacks.
ECB CBC CTR Encrypts each block independently Chains each block to the previous one Turns the block cipher into a stream Identical blocks give identical output, so patterns leak No integrity; error messages can enable padding attacks No integrity; reusing a nonce exposes the plaintext GCM ChaCha20-Poly1305 Counter mode plus an authentication tag Stream cipher plus a one-time authenticator Confidentiality and integrity, if nonces never repeat Same guarantees, fast in software Rules for using authenticated encryption safely:
- Never reuse a nonce with the same key. For GCM this can reveal the authentication key and allow forgeries.
- Check the tag before using any decrypted data, and treat a failed check as an attack, not a glitch.
- Use associated data for values such as headers or record IDs that must be authenticated but stay readable.
Prefer a well-reviewed library's high-level "encrypt" interface over assembling modes yourself.
Q23.What is envelope encryption, and how does key rotation work with it?
Envelope encryption encrypts data with a data key, then encrypts that data key with a key-encryption key held in a key management service or hardware security module. The bulk data never travels to the key service, and the master key never leaves it.
- Encrypt: generate a fresh data key, encrypt the data locally with it, ask the key service to encrypt (wrap) the data key, and store the wrapped key next to the data.
- Decrypt: send the wrapped key to the key service, receive the plaintext data key, decrypt locally, then discard the plaintext key from memory.
- Control: the key service checks permissions and logs every unwrap request.
flowchart LR A["Plaintext data"] -->|encrypt with| B["Data key"] B -->|wrapped by| C["Key-encryption key in key service"] A --> D["Ciphertext"] B --> E["Wrapped data key"] D --> F["Stored together"] E --> FHow rotation works:
- Rotating the key-encryption key creates a new version; new data keys are wrapped with it, and old versions stay available for decryption only.
- To retire an old version, rewrap the stored data keys: a few hundred bytes each, not the data itself.
- Rotating data keys means re-encrypting data, so it is done when data is rewritten or after a suspected compromise.
Example
Rotating the master key for a backup archive:
- The archive holds 10 TB of backups split into 2 million objects, each with its own data key.
- Re-encrypting all the data would mean reading and writing 10 TB.
- Rewrapping instead touches only the 2 million wrapped keys. At about 200 bytes each, that is roughly 400 MB of key material sent through the key service.
- After rewrapping, the old key-encryption key version is disabled, and any copy of it an attacker might hold no longer unlocks future reads.
Rotation becomes a routine job measured in hours rather than a multi-day data migration.
Q24.Why must security code use a cryptographically secure random number generator?
Tokens, keys, salts and password-reset links are only safe if attackers cannot predict them. General-purpose random number generators are designed for statistics and simulations, not secrecy, so their output can be predicted.
Why ordinary generators fail:
- Guessable seeds: many are seeded from the current time or a process ID, which an attacker can narrow down to a small range.
- Recoverable state: for common generators, observing enough outputs lets an attacker rebuild the internal state and compute every future value.
- Reproducibility is a feature for simulations but a disaster for secrets.
What to use instead:
- The operating system's cryptographically secure generator, exposed in most languages as a dedicated "secrets" or "secure random" module.
- At least 128 bits of randomness for session IDs and reset tokens; 256 bits is common for keys.
- Encode tokens in a URL-safe format and compare them in constant time.
A predictable reset token turns "forgot password" into "take over any account". This is one of the easiest mistakes to avoid with the right library call.
Example
How a seeded general-purpose generator can be replayed, while the secure generator cannot:
import random import secrets ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789" def weak_token(seed: int) -> str: generator = random.Random(seed) return "".join(generator.choice(ALPHABET) for _ in range(16)) # An attacker who guesses the seed, such as the server start time, rebuilds the token. print(weak_token(1_700_000_000) == weak_token(1_700_000_000)) # True token = secrets.token_urlsafe(32) # 32 random bytes from the operating system print(len(token)) # 43 print(secrets.token_urlsafe(32) == token) # FalseThe weak token is repeatable by anyone who can guess one number, while the secure token has 256 bits of unpredictability.
Q25.How do you estimate how long a brute-force attack on a password would take?
Estimate the number of possible passwords, then divide by how fast the attacker can test guesses.
keyspace = charset_size ^ lengthaverage_time = keyspace / 2 / guesses_per_secondentropy_bits = length × log2(charset_size)
What each term means:
- charset_size: how many characters each position can take, such as 26 for lowercase letters or 95 for all printable characters.
- length: the number of characters.
- guesses_per_second: depends on the attack. An online attack against a login page might manage a few guesses per second before rate limits apply; an offline attack on a stolen fast hash can reach billions per second on graphics cards.
- On average the right password is found after searching half the keyspace.
When to use it: to compare password policies and to show why slow password hashing matters. Length grows the keyspace far faster than adding character types.
The formula assumes random passwords. Human-chosen passwords fall to dictionary and pattern attacks long before the full keyspace is searched, so real-world times are much shorter.
Example
Comparing two passwords against an offline attacker testing 10 billion fast hashes per second:
- 8 random printable characters:
95^8 = 6,634,204,312,890,625combinations, about 52.6 bits. Searching all of them takes6.63 × 10^15 / 10^10 ≈ 663,420seconds, about 7.7 days, so the average is about 3.8 days. - 16 random lowercase letters:
26^16 ≈ 4.36 × 10^22combinations, about 75.2 bits. A full search takes about4.36 × 10^12seconds, roughly 138,000 years. - The same 8-character password behind a slow hash that allows only 10,000 guesses per second takes about 21,000 years for a full search.
The longer, simpler password beats the short complex one, and slow hashing turns days into millennia.
Q26.At which network layers do common attacks happen?
Attacks happen at every layer of the network stack, and each layer needs defenses that can see that layer. A firewall that only reads addresses and ports cannot stop an injection attack hidden in a valid web request.
Link Network Transport Attacks: address resolution spoofing, switch table flooding, rogue access points Attacks: address spoofing, route hijacking, ICMP floods Attacks: SYN floods, port scans, session hijacking Defenses: switch port security, inspection of address resolution traffic Defenses: ingress and egress filtering, route validation Defenses: stateful firewalls, SYN cookies, encryption Encryption layer Application Attacks: protocol downgrade, weak ciphers, invalid certificates Attacks: injection, credential stuffing, request floods Defenses: modern TLS only, strict certificate validation Defenses: input validation, rate limits, web application firewall Why the layer matters:
- Placement: a control must sit where it can inspect the attack. Application attacks need application-aware controls, and encrypted traffic must be inspected where it is decrypted.
- Blind spots: encryption protects against eavesdropping but also hides attacks from network sensors, so endpoint and application logs become more important.
- Defense in depth: most real intrusions cross several layers, from a phishing email at the application layer to lateral movement across the internal network.
Q27.How do packet-filtering, stateful and application-layer firewalls differ?
They differ in how much context they use to decide. A packet filter judges each packet alone, a stateful firewall tracks connections, and an application-layer firewall understands the protocol content itself.
Packet filter, stateless Stateful Application-layer or next-generation Web application firewall Decides on addresses, ports and protocol per packet Decides on connection state plus addresses and ports Decides on protocol content, user and application identity Decides on HTTP requests and responses Very fast and simple Allows replies automatically; blocks unsolicited packets Can block specific commands, files or apps Blocks common web attack payloads Needs rules for return traffic; easy to fool with crafted packets Blind to what is inside allowed connections Slower; needs decryption to see encrypted traffic Can be bypassed by encoding tricks; needs tuning When to use which:
- Stateless filters suit high-volume edges and simple network rules, such as cloud network access lists.
- Stateful firewalls are the default between network zones.
- Application-layer firewalls fit where user and application identity matter, such as controlling outbound web access.
- A web application firewall adds a shield in front of web apps, but it never replaces fixing the application's own flaws.
Q28.What is the difference between an intrusion detection system and an intrusion prevention system?
An intrusion detection system watches a copy of the traffic and raises alerts; an intrusion prevention system sits in the traffic path and can block what it detects. Both use the same detection logic, but their placement changes the risk they carry.
Detection system Prevention system Out of band, on a traffic copy Inline, in the traffic path Alerts humans or automation Drops or resets malicious traffic A false positive wastes an investigation A false positive blocks legitimate traffic If it fails, visibility is lost If it fails, traffic stops, unless it fails open Adds no latency Adds a small delay per packet How they detect:
- Signature-based: matches known attack patterns. Precise, but blind to new attacks.
- Anomaly-based: learns a baseline and flags deviations. Finds new behavior but produces more false positives.
When to use which: start new rules in detection mode, measure their false positive rate, and switch only the precise, high-confidence rules to blocking. Decide in advance whether an inline device should fail open, keeping traffic flowing, or fail closed, keeping protection.
Q29.How does network segmentation limit an attacker, and what is a DMZ?
Segmentation divides a network into zones with controlled paths between them, so an attacker who compromises one system cannot reach everything else. A DMZ is a zone for internet-facing services, placed between the internet and the internal network.
flowchart LR A["Internet"] --> B["Edge firewall"] B --> C["DMZ: reverse proxy and web servers"] C --> D["Internal firewall"] D --> E["Application tier"] E --> F["Database tier"] G["Admin network"] -->|managed access only| EHow segmentation limits an attacker:
- Contains the breach: a compromised web server in the DMZ can reach only the application ports it needs, not the databases or staff laptops.
- Forces detection points: traffic between zones crosses firewalls that log and alert.
- Protects the crown jewels: the most sensitive systems sit in the most restricted zones.
Good practice:
- Default-deny between zones and allow only named flows, such as "proxy to app on port 8443".
- Segment by function and sensitivity, and keep management interfaces on a separate network.
- Microsegmentation applies the same idea per workload, often with host-level or cloud security rules, and limits lateral movement even inside one zone.
Q30.How does address resolution spoofing enable a man-in-the-middle attack, and how do you prevent it?
On a local network, devices use the address resolution protocol to map IP addresses to hardware addresses, and the protocol has no authentication. An attacker sends forged replies claiming the gateway's IP address, so victims send their traffic through the attacker's machine.
- The attacker tells the victim "the gateway's IP is at my hardware address", and tells the gateway the same about the victim.
- Both update their caches and send traffic to the attacker.
- The attacker forwards the traffic on, so nothing seems broken, while reading or altering anything that is not encrypted.
sequenceDiagram participant V as Victim participant A as Attacker participant G as Gateway A->>V: Forged reply, gateway is at attacker address A->>G: Forged reply, victim is at attacker address V->>A: Traffic meant for the gateway A->>G: Forwarded traffic, read or alteredPrevention and detection:
- Switch-level inspection that checks replies against a table of known address bindings, built from address assignment records.
- Port security that limits which hardware addresses each switch port can use.
- Encryption everywhere: with TLS and certificate validation, intercepted traffic is unreadable and tampering is detected.
- Monitoring for sudden changes in the hardware address behind the gateway's IP address.
Q31.What attacks target DNS, and how do you defend against them?
DNS translates names to addresses, so whoever controls the answers can send users anywhere. Attacks either forge or redirect answers, abuse DNS as a hidden channel, or use it to amplify floods.
Cache poisoning Domain hijacking Tunneling Forged answers are planted in a resolver's cache The registrar account or name servers are changed Data is hidden inside query names and answers Defense: signed DNS records with validation, randomized query ports and IDs Defense: registrar lock, multi-factor authentication on registrar accounts Defense: monitor query length, randomness and volume per host Amplification flood Subdomain takeover Small spoofed queries trigger large replies at a victim A record still points to a deleted cloud resource that someone else claims Defense: disable open recursion, rate-limit responses Defense: inventory records and remove dangling ones Operational practices:
- Force internal devices to use your own resolvers, and block direct outbound DNS to the internet. This makes tunneling and malware lookups visible.
- Log DNS queries centrally; they are one of the cheapest and richest detection sources.
- Use encrypted DNS between clients and resolvers where privacy matters, while keeping visibility on the resolver.
Q32.How do volumetric, protocol and application-layer denial-of-service attacks differ?
They exhaust different resources. Volumetric attacks fill the network pipe, protocol attacks exhaust connection state in servers and firewalls, and application-layer attacks make the application do expensive work.
Volumetric Protocol Application layer UDP floods, reflection and amplification SYN floods, fragmented packet floods Floods of search or login requests Exhausts bandwidth Exhausts connection tables in servers and firewalls Exhausts CPU, database and threads Defenses: upstream scrubbing, anycast networks, provider filtering Defenses: SYN cookies, connection limits, stateless edge filtering Defenses: rate limits, caching, bot challenges, web firewall rules How to prepare:
- Know your normal baseline of traffic, so an attack is recognized quickly.
- Put internet-facing services behind a provider with enough capacity to absorb volumetric floods.
- Make expensive endpoints cheap to defend: cache results, require authentication and add per-client limits.
- Write a runbook with provider contacts and pre-approved emergency rules.
- Cap autoscaling, because unlimited scaling turns a denial-of-service attack into a denial-of-wallet attack.
Application-layer attacks are the hardest to filter because each request looks valid. Defending them depends on understanding what normal users actually do.
Q33.What does a port scan reveal, and how do TCP connect and SYN scans differ?
A port scan probes a host's ports to find which ones accept connections. From that, an attacker or defender learns which services are exposed, often their versions, and sometimes the operating system, which points to likely vulnerabilities.
TCP connect scan SYN scan Completes the full three-way handshake Sends SYN, then resets after SYN-ACK An open port accepts the connection An open port replies with SYN-ACK Needs no special privileges; uses normal sockets Needs raw packet access Logged by the application as a connection Often not logged by the application Slower, more packets Faster Other scan types: UDP scans are slow because closed ports often send nothing back. Version detection connects to services and reads their banners.
Defensive view:
- Scan your own address ranges regularly and compare results with what should be exposed. Unexpected open ports are findings in themselves.
- Detect scans by looking for one source touching many ports or many hosts in a short time.
- Do not rely on hiding services on unusual ports; scanners find them in seconds.
Q34.Which plaintext protocols should be replaced, and with what?
Any protocol that sends credentials or data unencrypted can be read or altered by someone on the network path. Replace each with its encrypted equivalent, including on internal networks, because attackers who get inside listen there too.
Telnet FTP HTTP SMTP between servers Risk: passwords and commands sent in clear Risk: credentials and files in clear Risk: sessions and data readable and changeable Risk: mail readable in transit Replace with SSH Replace with SFTP, or FTPS Replace with HTTPS plus HSTS Replace with SMTP with TLS required LDAP SNMP versions 1 and 2c POP3 and IMAP Risk: directory passwords in clear Risk: community strings act as clear passwords Risk: mail passwords in clear Replace with LDAP over TLS Replace with SNMP version 3 with authentication and encryption Replace with the same protocols over TLS When replacing them:
- Turn off the old protocol after migrating; leaving both enabled keeps the weakness.
- Validate certificates. Encryption without validation still allows a man-in-the-middle attack.
- Disable outdated versions of the secure protocols too, such as early TLS and SSL versions.
- Find remaining plaintext use by watching network flows for the old ports before switching them off.
Q35.How do site-to-site and remote-access VPNs differ?
A site-to-site VPN joins two networks, such as an office and a data center, through a permanent encrypted tunnel between gateways. A remote-access VPN connects one user's device to a network, using client software and user authentication.
Site-to-site Remote access Connects network to network Connects one device to a network Endpoints are gateways or routers Endpoints are client software and a VPN concentrator Authenticates with gateway certificates or pre-shared keys Authenticates with user credentials, multi-factor authentication and device checks Always on On when the user connects Used for branch offices and cloud to on-premises links Used by staff working remotely Security points:
- A VPN usually grants access to a whole network, so a stolen VPN login can expose a lot. Limit what VPN users can reach.
- Split tunneling sends only corporate traffic through the VPN; it improves speed but means the device is directly on the internet at the same time.
- Patch VPN gateways quickly. As internet-facing devices that hold credentials, they are frequent targets.
Many organizations now replace remote-access VPNs with per-application access proxies, in line with zero trust.
Q36.How would you secure a corporate wireless network?
Secure corporate wireless with per-user or per-device authentication instead of a shared password, the strongest current wireless encryption, and strict separation between staff, guest and device networks.
- Use enterprise authentication: each user or device proves its identity, ideally with a device certificate, against a central authentication server. Leaving staff means revoking one identity, not changing a password for everyone.
- Enable the latest wireless security protocol with protected management frames, and disable older encryption standards that can be cracked.
- Separate networks: guests get internet-only access with client isolation; printers and building systems go on their own restricted segment.
- Check device health on connection and place devices in the right segment automatically.
- Detect rogue and look-alike access points with wireless monitoring, since an attacker's "evil twin" network with the same name is a common trick.
- Treat wireless as untrusted: require the same authentication and encryption for internal apps as for remote users.
Physical placement matters too. Tune signal strength so the network does not reach the car park, which is where attackers would sit.
Q37.How do you detect data exfiltration over the network?
Detect exfiltration by comparing outbound traffic with each system's normal behavior, and by watching the channels attackers favor to hide data. Volume alone is not enough, because careful attackers move data slowly.
Outbound volume far above the host's baseline Uploads to domains first seen recently Long, random-looking DNS query names Steady connections at fixed intervals May be bulk data being copied out May be a staging or attacker-controlled site May be data hidden in DNS tunneling May be command-and-control beaconing Encrypted traffic on unusual ports Large archives created just before transfers Transfers at unusual hours for that user May be a custom channel avoiding the proxy May be data packaged for theft May be a stolen account in use Where the data comes from:
- Network flow records for volumes and destinations.
- Proxy and DNS logs for domains and query patterns.
- Endpoint telemetry to tie a connection to a specific process and user.
- Data loss prevention tools for content-aware rules on known sensitive data.
The strongest position combines detection with egress filtering: if servers can reach only a short list of approved destinations, most exfiltration paths are closed before they need detecting.
Q38.What is egress filtering, and why do so many networks neglect it?
Egress filtering controls which outbound connections are allowed to leave a network. Most networks filter inbound traffic carefully but let anything out, which is exactly what malware and data thieves rely on.
Why it gets neglected:
- Outbound rules break things visibly when they are wrong, while open egress fails silently.
- Applications often call many external services, and nobody keeps a list.
- The risk is less obvious than an open inbound port.
What it stops:
- Command-and-control: malware cannot call home to receive instructions.
- Exfiltration: stolen data has fewer ways out.
- Payload downloads: a first-stage infection cannot fetch its tools.
- Server-side request forgery impact: a tricked server cannot reach arbitrary destinations.
How to roll it out:
- Log outbound flows for a few weeks to learn what each server genuinely needs.
- Route web traffic from servers through a proxy with an allowlist of domains.
- Allow DNS only to internal resolvers, and block direct outbound connections on other ports.
- Default-deny, then alert on denied attempts, which often reveal compromised hosts.
Interview tip: when asked about network defense, mention egress control alongside inbound firewalls; candidates often forget that most attacks need to get data or signals out.
Q39.Write a function that checks whether an IP address is inside an allowed list of network ranges.
Parse the address and the ranges with a real IP address library, then test membership. Comparing strings, such as checking whether an address starts with "10.2", is a classic bug: it also matches 10.200.0.1.
Key points:
- Parse, do not pattern-match: a proper parser understands prefix lengths and rejects malformed input such as
300.1.1.1. - Fail closed: anything that does not parse as a single address is denied, including ranges and extra characters.
- Handle IPv6: keep IPv6 ranges in the list, and unwrap IPv4-mapped IPv6 addresses such as
::ffff:10.20.1.1, which some servers report for IPv4 clients. - Trust the right source: behind a load balancer, read the client address only from a header your own proxy sets, because clients can forge forwarding headers.
- Keep the list in configuration, so changing it does not need a code release.
Allowlists by IP address are a useful extra layer for admin tools, but they are not authentication. Addresses can be shared, reassigned or spoofed on some networks.
Example
An allowlist check using the standard library's IP address parser, run against tricky inputs:
import ipaddress ALLOWED = [ipaddress.ip_network(n) for n in ("10.20.0.0/16", "192.168.5.0/24", "2001:db8:42::/48")] def is_allowed(address: str) -> bool: try: ip = ipaddress.ip_address(address.strip()) except ValueError: return False # anything that is not one valid address is denied if ip.version == 6 and ip.ipv4_mapped: ip = ip.ipv4_mapped return any(ip in network for network in ALLOWED if network.version == ip.version) for candidate in ["10.20.7.9", "10.200.0.1", "192.168.5.255", "2001:db8:42::1", "::ffff:10.20.1.1", "10.20.0.1/8", "300.1.1.1"]: print(f"{candidate:18} {is_allowed(candidate)}") # Output: # 10.20.7.9 True # 10.200.0.1 False # 192.168.5.255 True # 2001:db8:42::1 True # ::ffff:10.20.1.1 True # 10.20.0.1/8 False # 300.1.1.1 FalseThe second line is the case a string prefix check would wrongly allow.
- Parse, do not pattern-match: a proper parser understands prefix lengths and rejects malformed input such as
Q40.A server is sending traffic to an unknown external address at night. How do you investigate?
Treat it as a possible compromise, but confirm before acting: establish what the traffic is, which process sends it, and whether it is legitimate, then contain quickly if it is not.
- Scope the traffic: from flow logs, get the destination, ports, volume, timing and how long it has been happening.
- Enrich the destination: check its domain, registration age, reputation and whether other hosts talk to it.
- Find the process: use endpoint telemetry to identify the program, its parent, its file hash, its signer and how it starts.
- Decide: match it against known jobs such as backups, updates or monitoring agents, and confirm with the system owner.
- Contain if suspicious: isolate the host from the network while keeping it powered on to preserve memory, and block the destination at the egress firewall.
- Investigate scope: look for the same indicators on other hosts, find the initial entry point and check for persistence.
flowchart TD A["Unexpected outbound traffic"] --> B["Scope with flow logs"] B --> C["Identify the sending process"] C --> D{"Known and approved?"} D -->|yes| E["Document and tune the alert"] D -->|no| F["Isolate host and block destination"] F --> G["Hunt for the same indicators elsewhere"] G --> H["Eradicate, recover, review"]Trade-offs:
- Isolating immediately limits damage but warns the attacker; watching longer reveals more but risks more data loss.
- Rebooting or reimaging destroys memory evidence, so capture it first when the stakes justify it.
Example
How such an investigation played out:
- Flow logs showed about 2 GB uploaded over port 443 every night at 02:10 to a domain registered nine days earlier.
- Endpoint data tied the connections to an unsigned program in a temporary folder, started by a scheduled task created three days before by a service account.
- The system owner confirmed no such job existed, so the host was isolated and the domain blocked.
- A search for the same file hash and task name found it on two more servers, which were isolated as well.
- The service account's password had been reused on a public-facing admin page, which was the entry point. The account was reset, the page was taken off the internet, and the three hosts were rebuilt from clean images.