Tools / Security Engineering Interview questions
Last updated
1. What is security engineering?
Security engineering is the practice of designing, building and operating systems so they keep working correctly when someone is actively trying to break them. It treats security as an engineering property, like reliability or performance, instead of something added after release.
In practice the work covers threat modeling, secure architecture, authentication and access control, cryptography, vulnerability management, security testing, monitoring and incident response.
The main difference from general IT security is the focus on building security in: a security engineer reviews designs, writes guardrails and automation, and fixes root causes, rather than only reacting to alerts.
Take quiz
writing marketing copy about compliance
replacing hardware every year
installing antivirus on employee laptops after release
building security into systems by design
tuning database indexes for speed
threat modeling a new feature design
approving office parking requests
designing company logos
2. What is the CIA triad?
The CIA triad is the core model for describing security goals: Confidentiality, Integrity and Availability. Almost every control or attack can be mapped to one or more of these three.
| Goal | Meaning | Example control | Example attack |
| Confidentiality | Only authorized parties can read data | Encryption, access control | Data breach |
| Integrity | Data is not altered without detection | Hashes, digital signatures | Tampering with a transaction |
| Availability | Systems are usable when needed | Redundancy, DDoS protection | Denial of service |
The goals can conflict. Heavy encryption adds latency, and aggressive lockouts can hurt availability, so engineers balance them based on the asset being protected.
Take quiz
Integrity
Availability
Scalability
Confidentiality
Non-repudiation of logs
Integrity of stored hashes
Availability
Confidentiality of data in transit
3. What is the principle of least privilege?
The principle of least privilege says every user, service or process should get only the permissions it needs to do its job, and only for as long as it needs them.
If an account with narrow rights is compromised, the damage is limited. A read-only reporting service cannot drop tables, even if an attacker takes it over.
- Start with no access and add permissions explicitly.
- Prefer scoped roles over shared admin accounts.
- Use time-bound or just-in-time elevation for sensitive tasks.
- Review and remove unused permissions regularly.
Take quiz
it removes the need for passwords
a compromised account can do limited damage
it makes every query run faster
it encrypts data automatically
A shared admin login used by all services
db_owner on the whole database
DROP and ALTER on every schema
SELECT on the required tables only
4. What is defense in depth?
Defense in depth means protecting a system with several independent layers of control, so that one failure does not lead to a full compromise.
A typical web application might have a WAF at the edge, network segmentation, authenticated APIs, input validation in code, encryption of stored data, and monitoring that alerts on abnormal behavior.
The key word is independent. Two layers that share the same weakness, such as the same credentials, do not add real depth.
Take quiz
trusting all internal traffic
annual penetration tests only
multiple independent layers of controls
one very strong perimeter firewall
WAF, network segmentation, input validation and encryption together
A strong password on the admin page only
A single firewall with a very complex rule set
Hiding the server name in HTTP headers
5. What is threat modeling?
Threat modeling is a structured way to find what can go wrong in a system before it is built or released, and to decide what to do about it.
A common approach asks four questions:
- What are we building? (draw a data flow diagram)
- What can go wrong? (use STRIDE or attack trees)
- What are we going to do about it? (mitigate, accept, transfer, avoid)
- Did we do a good enough job? (validate and review)
The earlier it is done, the cheaper the fixes. Redesigning a trust boundary on paper costs far less than patching it in production.
Take quiz
after the first breach
after the product is retired
only during annual audits
during design, before the code is built
a marketing roadmap
a data flow diagram with trust boundaries
the company org chart
a list of office assets
6. What is the STRIDE model?
STRIDE is a threat classification model from Microsoft. Each letter names a category of threat you check against every element in a data flow diagram.
| Letter | Threat | Violated property | Typical mitigation |
| S | Spoofing | Authentication | Strong authentication, MFA |
| T | Tampering | Integrity | Signatures, checksums, ACLs |
| R | Repudiation | Non-repudiation | Audit logs, signed events |
| I | Information disclosure | Confidentiality | Encryption, access control |
| D | Denial of service | Availability | Rate limits, redundancy |
| E | Elevation of privilege | Authorization | Least privilege, input validation |
Take quiz
Spoofing
Repudiation
Denial of service
Tampering
Spoofing of TLS certificates
Elevation of privilege
Repudiation
Information disclosure over email
7. What are authentication and authorization?
Authentication answers "who are you?" and authorization answers "what are you allowed to do?". Authentication always comes first, because permissions only make sense for a known identity.
Logging in with a password and an OTP is authentication. Checking that the logged-in user has the admin role before allowing a delete is authorization.
A common mistake is authenticating the user but forgetting the authorization check on each object, which leads to broken access control issues such as IDOR.
Take quiz
hashing
authorization
authentication
encryption
a stronger password policy
TLS on the login page
a longer session timeout
an object-level authorization check
8. What are encryption at rest and encryption in transit?
Encryption at rest protects stored data, such as disks, databases and backups, so a stolen drive or snapshot is unreadable. Encryption in transit protects data moving across a network, typically with TLS, so eavesdroppers cannot read or modify it.
| Aspect | At rest | In transit |
| Protects against | Stolen disks, leaked backups | Sniffing, man-in-the-middle |
| Typical tech | AES-256, TDE, KMS-managed keys | TLS 1.2/1.3, mTLS, VPN |
| Key concern | Key storage and rotation | Certificate validation |
You usually need both. Encrypting only the database does not help if the same data crosses the network in plain text.
Take quiz
Transparent Data Encryption on the disk
Database indexing
TLS
RAID mirroring
encryption at rest
encryption in transit
a stronger firewall rule
rate limiting
9. What are symmetric and asymmetric encryption?
Symmetric encryption uses one shared secret key to both encrypt and decrypt. It is fast, so it is used for bulk data. AES is the standard example.
Asymmetric encryption uses a key pair: a public key to encrypt (or verify) and a private key to decrypt (or sign). It solves key distribution but is much slower. RSA and ECC are common.
Real systems combine both. TLS uses asymmetric cryptography to agree on a session key, then switches to a symmetric cipher for the data.
Take quiz
symmetric keys never need to be protected
symmetric encryption needs no key
asymmetric keys expire after one packet
symmetric ciphers are much faster for bulk data
neither, keys are derived from the IP address
the private key
both keys are published
the public key
10. What is hashing in security?
A cryptographic hash function turns any input into a fixed-length digest. It is one-way, so you cannot recover the input from the digest, and a tiny change in the input produces a completely different output.
Hashes are used to verify file integrity, store passwords (with a slow salted algorithm), and build digital signatures.
Hashing is not encryption. Encryption is reversible with a key, while hashing is not meant to be reversed at all.
echo -n "hello" | sha256sum # 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Take quiz
hashing is one-way, encryption is reversible with a key
hashing needs a private key, encryption does not
there is no difference
encryption always produces a fixed-length output
encrypt a database column
recover a lost password
verify a downloaded file was not altered
hide an IP address
11. What is the OWASP Top 10?
The OWASP Top 10 is a regularly updated awareness list of the most critical web application security risks, produced by the Open Worldwide Application Security Project from real vulnerability data and community input.
It is not a complete standard, but teams use it as a baseline for training, code review checklists and testing. Categories include broken access control, cryptographic failures, injection, insecure design, security misconfiguration and vulnerable components.
For deeper verification requirements, OWASP offers the ASVS, which is a detailed testable checklist.
Take quiz
a certification exam for engineers
an awareness list of the most critical web application risks
a firewall product
a law that every website must follow
ZAP Baseline
Dependency-Check
Top 10 only
ASVS
12. What is SQL injection?
SQL injection happens when untrusted input is concatenated into a SQL query, letting an attacker change the query's meaning and read, modify or delete data.
// Vulnerable String q = "SELECT * FROM users WHERE name = '" + name + "'"; // name = ' OR '1'='1 -> returns every user
The fix is to separate code from data using parameterized queries (prepared statements), so the database treats the input as a value, never as SQL.
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE name = ?"); ps.setString(1, name);
Take quiz
hashing the table names
limiting the page size
parameterized queries
hiding the database port
it changes the query logic so the condition is always true
it bypasses TLS
it crashes the web server
it encrypts the table
13. What is cross-site scripting (XSS)?
XSS is a vulnerability where an application includes untrusted input in a page without proper encoding, so an attacker's JavaScript runs in the victim's browser under the site's origin.
The script can steal session tokens, perform actions as the user, or rewrite the page. The three main types are stored, reflected and DOM-based.
The core defense is context-aware output encoding (HTML, attribute, JavaScript, URL), backed by a Content Security Policy and HttpOnly cookies to reduce impact.
Take quiz
reboot the web server
crack the TLS private key
run SQL on the database directly
run JavaScript in the victim's browser on the vulnerable site
disabling cookies entirely
context-aware output encoding
using only POST requests
longer passwords
14. What is CSRF?
Cross-Site Request Forgery tricks a logged-in user's browser into sending an unwanted request to a site where they are authenticated. The browser attaches cookies automatically, so the server thinks the request is genuine.
Example: a malicious page auto-submits a form to bank.com/transfer while you are logged in to the bank.
Defenses include anti-CSRF tokens, SameSite cookies, checking the Origin header, and requiring re-authentication for sensitive actions.
Take quiz
browsers send cookies automatically with cross-site requests
the server has no database
passwords are stored in plain text
the attacker steals the TLS key
longer URLs
disabling HTTPS
anti-CSRF tokens
gzip compression
15. What is multi-factor authentication?
Multi-factor authentication (MFA) requires two or more different types of proof of identity. The three classic factors are something you know (password), something you have (phone, hardware key) and something you are (fingerprint).
Two passwords are not MFA, because both are the same factor type.
Strength varies. FIDO2/WebAuthn keys resist phishing, authenticator apps are decent, and SMS codes are weakest because of SIM swapping and interception.
Take quiz
two different passwords
a password and a hardware security key
a PIN and a second PIN
a password and a security question
SMS code
security questions
email OTP
FIDO2/WebAuthn security key
16. What are vulnerability, threat and risk?
A vulnerability is a weakness, a threat is something that can exploit it, and risk is the likelihood and impact of that exploitation happening.
| Term | Meaning | Example |
| Vulnerability | Weakness in a system | Unpatched web server |
| Threat | Actor or event that can exploit it | Ransomware group |
| Risk | Likelihood x impact | High chance of data loss on a critical server |
Risk is what leadership cares about, so engineers translate technical findings into risk to prioritize fixes.
Take quiz
control
threat actor
vulnerability
risk appetite
likelihood multiplied by impact
the number of servers
the firewall rule count
the CVE count
17. What is a zero-day vulnerability?
A zero-day is a vulnerability that is unknown to the vendor, or has no patch available yet, so defenders have had "zero days" to fix it. Attackers who find it can exploit it before anyone can patch.
Because you cannot patch what has no fix, mitigation relies on other layers: network segmentation, least privilege, exploit-mitigation features (ASLR, DEP), virtual patching in a WAF or IPS, and behavior-based detection.
Once a vendor releases a patch, it becomes an n-day vulnerability.
Take quiz
it has a CVSS score of exactly zero
it only affects Windows
it is older than a year
no vendor patch is available when it is exploited
disabling logging
virtual patching and segmentation
waiting for the next audit
installing a larger disk
18. What is a Web Application Firewall (WAF)?
A WAF sits in front of a web application and inspects HTTP/HTTPS traffic, blocking requests that match attack patterns such as SQL injection, XSS or malicious bots.
A network firewall works at layers 3 and 4 (IP, port). A WAF works at layer 7 and understands URLs, headers and request bodies.
It is a useful extra layer and good for virtual patching, but it does not replace fixing the underlying code. Attackers can often bypass rules with encoding tricks.
Take quiz
application layer (layer 7)
layer 3 routing only
data link layer only
physical layer
a replacement for patching
a full replacement for input validation
an extra layer, not a substitute for secure code
unnecessary if you use HTTPS
19. What is TLS and why is it used?
Transport Layer Security (TLS) is the protocol behind HTTPS. It gives a connection three guarantees: confidentiality (encryption), integrity (tamper detection) and authentication of the server, and optionally the client.
The server proves its identity with a certificate signed by a trusted certificate authority. The client and server then agree on session keys and encrypt traffic with them.
Use TLS 1.2 at minimum and prefer TLS 1.3. SSL and TLS 1.0/1.1 are deprecated.
Take quiz
server authentication via certificates
protection against a flaw in the application code
detection of tampering in transit
encryption of data in transit
SSL 3.0
TLS 1.0
TLS 1.1
TLS 1.3
20. What is a secure software development lifecycle (SSDLC)?
A secure SDLC adds security activities to every phase of development, instead of testing for security only at the end.
| Phase | Security activity |
| Requirements | Define security and compliance requirements |
| Design | Threat modeling, secure architecture review |
| Implementation | Secure coding standards, SAST, secrets scanning |
| Testing | DAST, dependency scanning, penetration testing |
| Release and operate | Hardening, monitoring, patching, incident response |
This is often called "shifting left", which means finding issues when they are cheapest to fix.
Take quiz
moving servers to another region
outsourcing all reviews
doing security work earlier in development
delaying testing until release
design
marketing
retirement
release monitoring only
21. What is the difference between SAST, DAST and IAST?
All three find application vulnerabilities, but they look at the application from different positions.
| Aspect | SAST | DAST | IAST |
| Analyzes | Source code or bytecode | Running app from outside | Running app from inside via an agent |
| Needs running app | No | Yes | Yes |
| When | Early, on commit | Staging or test | During functional tests |
| Strength | Precise code location | Finds runtime and config issues | Low false positives, real data flow |
| Weakness | False positives, no runtime context | Limited coverage, no code line | Needs agent, language support |
Teams usually combine them: SAST in the pull request, DAST in the pipeline against staging, and IAST where test coverage is good.
Take quiz
Black-box fuzzing only
IAST
DAST
SAST
only the Git history
a running application from the outside
compiled firmware offline
the developer's laptop settings
22. How does the OAuth 2.0 authorization code flow work?
The authorization code flow lets an app get access to a user's resources without ever seeing the user's password. The user authenticates at the authorization server, which hands the app a short-lived code, and the app exchanges that code for tokens over a back channel.
sequenceDiagram
participant U as User
participant C as Client App
participant A as Authorization Server
participant R as Resource Server
U->>C: Click login
C->>A: Redirect with client_id, scope, state, code_challenge
A->>U: Authenticate and consent
A->>C: Redirect back with authorization code
C->>A: Exchange code + code_verifier
A->>C: Access token (and refresh token)
C->>R: API call with access token
Public clients such as SPAs and mobile apps must use PKCE, and the state parameter protects against CSRF on the redirect.
Take quiz
the authorization code (plus PKCE verifier)
a session cookie from another site
the user's password
the TLS private key
to encrypt the access token at rest
to hash user passwords
to stop an intercepted authorization code from being redeemed by an attacker
to replace the need for HTTPS
23. What is the difference between OAuth 2.0 and OpenID Connect?
OAuth 2.0 is about authorization: it lets an app obtain an access token to call an API on the user's behalf. It says nothing standard about who the user is.
OpenID Connect (OIDC) is a thin identity layer on top of OAuth 2.0. It adds an ID token (a signed JWT with claims like sub and email), a /userinfo endpoint and the openid scope.
Use OAuth for "can this app read my calendar?" and OIDC for "log me in with this provider". Using a bare access token as proof of login is a classic mistake.
Take quiz
CSRF token
ID token
API key
session cookie
Basic authentication over HTTP
plain OAuth 2.0 access tokens only
SAML assertions only through query strings
OpenID Connect
24. How does the TLS 1.3 handshake work?
TLS 1.3 completes the handshake in one round trip, down from two in TLS 1.2, and removes weak options like RSA key exchange and static Diffie-Hellman.
sequenceDiagram
participant C as Client
participant S as Server
C->>S: ClientHello (versions, ciphers, key share)
S->>C: ServerHello (chosen cipher, key share)
S->>C: Certificate + CertificateVerify + Finished (encrypted)
C->>S: Finished
Note over C,S: Both derive session keys, application data flows
Both sides send ephemeral (EC)DHE key shares, so each session key is independent. This gives forward secrecy: stealing the server's private key later does not decrypt recorded traffic.
Take quiz
zero, always
four
one
three
a stolen long-term key cannot decrypt past recorded sessions
passwords are not needed
a server can never be spoofed
certificates never expire
25. Why should passwords be hashed with bcrypt or Argon2 instead of SHA-256?
SHA-256 is designed to be fast, which is the opposite of what you want for passwords. A single GPU can test billions of SHA-256 guesses per second against a leaked database.
bcrypt, scrypt and Argon2 are deliberately slow and tunable. Argon2 is also memory-hard, which makes GPU and ASIC cracking expensive. Each hash uses a unique salt, so identical passwords produce different hashes and rainbow tables are useless.
import argon2 ph = argon2.PasswordHasher() hash = ph.hash("s3cret") ph.verify(hash, "s3cret")
Add a server-side pepper and raise the cost factor over time as hardware improves.
Take quiz
it produces output that is too long
it requires a private key
it cannot be computed twice
it is too fast, so offline guessing is cheap
it encrypts the password with RSA
it is memory-hard
it uses only 8 characters
it publishes the salt separately
26. How does a JWT work and what are its common pitfalls?
A JSON Web Token has three Base64URL parts: header, payload (claims) and signature. The server signs the first two with a secret (HS256) or a private key (RS256/ES256), and anyone with the key can verify the token without a database lookup.
The payload is encoded, not encrypted, so never put secrets in it.
- Accepting
alg: noneor letting the token choose the algorithm. - Not validating
exp,issandaud. - Long-lived tokens with no revocation path.
- Storing tokens in
localStorage, where XSS can read them.
Keep access tokens short-lived, pin the expected algorithm in the verifier and rotate refresh tokens.
Take quiz
it is Base64URL encoded, not encrypted
it is stored only on the server
it is always AES encrypted
it cannot be read without the key
using short expiry times
validating the audience claim
accepting the alg none header
pinning the algorithm
27. How does the SameSite cookie attribute help against CSRF?
The SameSite attribute tells the browser when to include a cookie on cross-site requests. If the cookie is not sent, the forged request arrives unauthenticated and fails.
| Value | Cross-site behavior |
| Strict | Never sent on cross-site requests |
| Lax | Sent only on top-level GET navigations |
| None | Always sent, requires Secure flag |
Modern browsers default to Lax, which blocks most CSRF on POST requests. It is still not complete: same-site subdomains, GET requests that change state and older browsers remain risks, so keep CSRF tokens for sensitive actions.
Take quiz
None
Strict
Lax
Secure
tokens make cookies faster
Lax encrypts the cookie value
SameSite is removed in HTTPS
SameSite has gaps such as state-changing GETs and subdomain attacks
28. How do you prevent SQL injection beyond parameterized queries?
Parameterized queries are the primary fix, but they cover only values. Table names, column names and ORDER BY directions cannot be bound as parameters, so those need other handling.
- Allowlist dynamic identifiers, mapping user choices to fixed column names in code.
- Use an ORM or query builder correctly, and avoid raw string fragments inside it.
- Give the application account least privilege, with no DROP or file access.
- Validate type and length of input as a secondary check.
- Keep stored procedures free of dynamic SQL built from parameters.
- Hide detailed database errors from users and log them server-side.
sort = {"name": "name", "date": "created_at"}.get(user_sort, "created_at") query = f"SELECT * FROM orders ORDER BY {sort}"
Take quiz
bind it as a normal query parameter
trust it if it is under 20 characters
map it to an allowlist of fixed column names
strip only the quote characters
to reduce the damage if an injection still occurs
to stop SQL from logging
to avoid needing parameters
to make queries run faster
29. What is the difference between stored, reflected and DOM-based XSS?
The difference is where the malicious payload lives and where it is injected into the page.
| Type | Payload location | Executes when | Example |
| Stored | Saved on the server (database) | Any user views the infected page | Malicious comment on a blog |
| Reflected | In the request, echoed in the response | Victim opens a crafted link | Search term printed unescaped |
| DOM-based | In the URL or client data, handled by JavaScript | Client script writes it into the DOM unsafely | innerHTML = location.hash |
Stored XSS is generally the most dangerous because it needs no victim interaction beyond visiting the page. DOM-based XSS never reaches the server, so server-side filters cannot see it. Prefer textContent over innerHTML.
Take quiz
Reflected XSS
Stored XSS
Blind SQL injection
DOM-based XSS
reflected XSS
stored XSS
clickjacking
CSRF
30. What is SSRF and how do you prevent it?
Server-Side Request Forgery lets an attacker make the server send HTTP requests to a destination the attacker chooses, often an internal one the attacker cannot reach directly.
The classic cloud target is the metadata service at 169.254.169.254, which can return temporary IAM credentials.
- Use an allowlist of permitted hosts or schemes, not a blocklist.
- Resolve DNS yourself, then block private, loopback and link-local ranges, and connect to the checked IP to avoid DNS rebinding.
- Disable redirects or revalidate after each redirect.
- Enforce IMDSv2 and restrict egress at the network level.
Take quiz
the instance metadata service at 169.254.169.254
the public DNS root servers
the CDN edge logs
the user's browser cache
hiding the endpoint name
a blocklist of a few bad hostnames
an allowlist of permitted destinations
using GET instead of POST
31. Why should secrets never be stored in source code?
Source code is copied widely: every clone, fork, CI cache and backup holds it, and Git history keeps secrets even after you delete the line. A leaked API key in a public repo is often abused within minutes by automated scanners.
Secrets also cannot be rotated cleanly when they are baked into a release, and they give every developer production access.
Keep them in a secrets manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault), inject them at runtime, prefer short-lived dynamic credentials, and add pre-commit and CI scanning such as gitleaks. If one leaks, rotate it first, then clean history.
Take quiz
nothing, the delete fixed it
rotate the secret immediately, because history still contains it
rename the repository
only restart the server
hard-code them in a config file in Git
email them to the team
embed them in the Docker image layer
fetch short-lived credentials from a secrets manager at runtime
32. How does mutual TLS (mTLS) work?
In normal TLS only the server presents a certificate. In mutual TLS the server also requests a client certificate, and both sides verify each other against a trusted CA before any data is exchanged.
- Client connects and the server sends its certificate and a
CertificateRequest. - Client sends its certificate and proves possession of the private key.
- Server validates the chain, expiry and revocation, then maps the certificate identity to a service or user.
It is common for service-to-service traffic, where a service mesh like Istio or Linkerd issues short-lived workload certificates automatically. The hard part is not the handshake but certificate issuance, rotation and revocation at scale.
Take quiz
only the client is authenticated
mTLS needs no CA
the server also verifies a client certificate
mTLS uses no encryption
issuing and rotating certificates at scale
naming the cipher suite
compressing packets
choosing the port number
33. What is zero trust and how does it differ from perimeter security?
Perimeter security assumes anything inside the corporate network is trusted. Zero trust assumes no implicit trust anywhere: every request is authenticated, authorized and evaluated in context, regardless of network location.
| Aspect | Perimeter model | Zero trust |
| Trust basis | Network location | Identity, device health, context |
| Internal traffic | Mostly trusted | Verified every time |
| Access scope | Broad, VPN gives network access | Per-application, least privilege |
| Breach impact | Easy lateral movement | Limited by microsegmentation |
Its principles are verify explicitly, use least privilege and assume breach. It is a strategy, not a single product.
Take quiz
only external users need MFA
a VPN solves everything
internal networks are always safe
no request is trusted just because of its network location
share one admin login
assume breach
skip device checks for employees
trust the office network
34. How do you secure a CI/CD pipeline?
A pipeline can build and deploy to production, so it is a prime target. Treat it as production infrastructure.
- Protect secrets: use OIDC federation for short-lived cloud credentials instead of stored keys.
- Least privilege for runners and tokens, scoped per job.
- Branch protection, mandatory reviews and signed commits.
- Pin dependencies and actions by version or commit SHA.
- Run SAST, secrets scanning and dependency checks as required gates.
- Sign build artifacts and verify signatures at deploy time.
- Use ephemeral, isolated runners, and never run untrusted pull request code with secrets.
Take quiz
OIDC federation with short-lived credentials
putting them in the README
sharing them via chat
encoding the keys in Base64
tags are always encrypted
it removes the need for reviews
a tag can be moved to malicious code later
SHAs make jobs run faster
35. What is the difference between RBAC and ABAC?
RBAC grants permissions through roles: a user is assigned the editor role and inherits what editors can do. ABAC decides using attributes of the user, resource, action and environment, for example "doctors may read records of patients in their own department during working hours".
| Aspect | RBAC | ABAC |
| Decision basis | Role membership | Attributes and policies |
| Granularity | Coarse to medium | Very fine |
| Complexity | Simple to audit | Harder to design and test |
| Risk | Role explosion | Policy errors, attribute quality |
Many systems use RBAC as the base and add attribute conditions where roles alone get too numerous.
Take quiz
RBAC alone with a single role
ABAC
Discretionary file permissions
Plain Basic authentication
policies cannot be audited
it cannot use groups
no way to assign users
role explosion
36. How does envelope encryption work?
In envelope encryption your data is encrypted with a unique data encryption key (DEK), and the DEK is itself encrypted by a key encryption key (KEK) that lives in a KMS or HSM. You store the encrypted DEK next to the data.
flowchart LR
A["App requests data key"] --> B["KMS generates DEK"]
B --> C["KMS returns plaintext DEK + encrypted DEK"]
C --> D["App encrypts data with plaintext DEK"]
D --> E["Store ciphertext + encrypted DEK"]
E --> F["Discard plaintext DEK from memory"]
To decrypt, the app sends the encrypted DEK to the KMS, receives the plaintext DEK and decrypts locally. This avoids sending large data to the KMS, limits KMS calls, and lets you rotate the KEK by re-wrapping small DEKs instead of re-encrypting all data.
Take quiz
the user's session cookie
the plaintext DEK
the DEK, encrypted by the KEK
the KMS root password
only the small DEKs need re-wrapping, not the bulk data
the KMS stops encrypting
DEKs never change
all data is deleted and recreated
37. What is a software supply chain attack and how do you mitigate it?
A supply chain attack compromises something you trust and consume, such as an open-source package, build tool, container base image or update channel, so the malicious code reaches you through a normal install. Examples are typosquatted packages, hijacked maintainer accounts and tampered build systems.
- Pin versions and use lockfiles with integrity hashes.
- Generate and review an SBOM to know what you ship.
- Scan dependencies continuously and use a private proxy or registry.
- Sign artifacts (Sigstore/cosign) and verify provenance, aiming at SLSA levels.
- Build in hermetic, isolated environments with reviewed pipeline changes.
Take quiz
a backup of the database
a firewall rule set
a list of employee passwords
an inventory of the components inside your software
a lost laptop
a typosquatted package that looks like a popular library
a flood of SYN packets
an expired office badge
38. How do you secure containers and Kubernetes?
Security spans the image, the runtime and the cluster.
- Images: minimal base images, scan for CVEs, sign images, never bake in secrets.
- Containers: run as non-root, drop capabilities, read-only root filesystem, no privileged mode.
- Cluster: RBAC with least privilege, restricted service account tokens, API server not publicly exposed.
- Network: default-deny
NetworkPolicyand mTLS between services. - Policy: enforce Pod Security Standards and admission control (OPA Gatekeeper, Kyverno).
- Secrets: encrypt etcd and use an external secrets manager.
securityContext: runAsNonRoot: true allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: ["ALL"]
Take quiz
running as non-root with capabilities dropped
mounting the Docker socket
running with privileged: true
using the latest tag only
allows all traffic between pods
scans images for CVEs
blocks all pod traffic until explicitly allowed
encrypts etcd
39. What happens when a private key is compromised?
Anyone holding the key can impersonate the owner, sign malicious content or decrypt traffic that did not use forward secrecy. The key must be treated as burned, no matter how unlikely misuse seems.
- Generate a new key pair on clean infrastructure.
- Get a new certificate issued and deploy it.
- Revoke the old certificate with the CA (CRL or OCSP).
- Find the root cause: how was it exposed, and what else lived in the same place?
- Review logs for the exposure window and look for signed artifacts to re-issue.
Revocation checking is unreliable in many clients, so short-lived certificates and keys held in an HSM reduce this exposure window.
Take quiz
delete the server logs
replace the key pair and revoke the certificate
change only the website theme
keep using it until it expires
they remove the need for keys
they cannot be revoked
they make TLS faster by default
a stolen key becomes useless quickly even if revocation fails
40. How does a Content Security Policy work?
A Content Security Policy (CSP) is an HTTP response header that tells the browser which sources it may load scripts, styles, images and frames from. If injected script comes from a non-allowed source, or is inline without permission, the browser blocks it. This limits the damage of XSS.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
Avoid 'unsafe-inline' and wildcards, since they defeat the purpose. Use per-response nonces or hashes for inline scripts, and start with Content-Security-Policy-Report-Only to find breakage before enforcing.
Take quiz
SQL injection in the database layer
packet loss
the impact of XSS by restricting script sources
password reuse
'unsafe-inline' for scripts
frame-ancestors 'none'
object-src 'none'
a per-request nonce
41. What is the difference between IDS and IPS?
An Intrusion Detection System (IDS) watches traffic or hosts and raises alerts. An Intrusion Prevention System (IPS) sits inline and can actively block or drop malicious traffic.
| Aspect | IDS | IPS |
| Placement | Out of band (mirror/TAP) | Inline in the traffic path |
| Action | Alert and log | Block, reset, drop |
| Risk | Attack may succeed before response | False positive blocks legitimate traffic |
| Latency impact | None | Adds some latency, can be a failure point |
Detection methods are signature-based (known patterns) or anomaly-based (deviation from a baseline). Many products can run in either mode, and teams often start in detect mode to tune rules.
Take quiz
a packet sniffer on a mirror port
a syslog server
IDS
IPS
it never adds latency
false positives can block legitimate traffic
it cannot detect any attacks
it only logs events
42. Explain the lifecycle of security incident response?
The widely used NIST model has four phases, and the loop feeds back into preparation.
flowchart LR
A[Preparation] --> B["Detection and Analysis"]
B --> C["Containment, Eradication, Recovery"]
C --> D["Post-Incident Activity"]
D --> A
- Preparation: runbooks, logging, on-call, tooling, tested backups.
- Detection and analysis: triage alerts, confirm an incident, scope it, set severity.
- Containment, eradication, recovery: isolate hosts, remove the attacker's access and persistence, restore from known-good state.
- Post-incident: blameless review, lessons learned, detection and control improvements.
Preserve evidence before wiping systems, and keep communication with legal, management and customers coordinated.
Take quiz
containment
preparation
requirements gathering
post-incident review
rebuilding is not allowed
logs cannot be copied
it is needed for root-cause analysis and possible legal action
evidence speeds up the restore
43. How do you design API security and rate limiting?
API security starts with strong authentication (OAuth 2.0/OIDC or mTLS) and object-level authorization on every request, since broken object-level authorization is the top API risk.
Rate limiting protects availability and slows abuse such as credential stuffing, scraping and enumeration.
- Limit by identity, API key and IP, with stricter limits on login and password reset.
- Use algorithms like token bucket or sliding window, and return
429withRetry-After. - Validate request schema, size and content type.
- Return only needed fields to avoid excessive data exposure.
- Log and alert on abnormal patterns, and keep an inventory of all API versions.
Take quiz
301
429
204
502
missing favicon
verbose HTML comments
slow DNS lookups
broken object-level authorization
44. How do you prioritize vulnerabilities beyond the CVSS score?
CVSS measures technical severity in general, not risk to your environment. A critical CVSS on an isolated test box may matter less than a medium issue on an internet-facing payment service.
Add context to build a risk-based ranking:
- Exploitability: is it in CISA KEV, or is there a public exploit? Check EPSS probability.
- Exposure: internet-facing, internal, or reachable only after other steps.
- Asset value: data sensitivity and business criticality.
- Compensating controls: WAF rules, segmentation, authentication in front.
- Reachability: is the vulnerable code path actually used?
Then set SLAs per tier, for example 48 hours for actively exploited internet-facing issues.
Take quiz
all CVEs ever published
approved vendor patches
vulnerabilities known to be exploited in the wild
only low severity bugs
it may be on an exposed, high-value asset with a public exploit
medium always means higher priority
CVSS scores are random
critical scores are always false positives
45. How does PKI certificate chain validation work?
When a client receives a server certificate, it builds a chain from that leaf certificate through any intermediate CAs up to a root CA that is already in its trust store.
- Verify each certificate's signature using the issuer's public key.
- Check validity dates and that intermediates have
CA:TRUEand allowed key usage. - Match the hostname against the Subject Alternative Name.
- Check revocation through OCSP, stapled OCSP or CRL.
- Confirm the chain ends in a trusted root.
Roots are kept offline and sign only intermediates, so a compromised intermediate can be revoked without replacing the root in every device.
openssl s_client -connect example.com:443 -showcerts
Take quiz
Issuer Organization
Signature Algorithm only
Serial Number
Subject Alternative Name
browsers require roots to be unplugged
a root compromise would affect trust everywhere, so intermediates sign instead
offline keys sign faster
roots expire every hour
46. When would you choose an HSM over a cloud KMS?
A KMS is a managed key service with an API, policies and audit logs, backed by HSMs run by the provider. A dedicated HSM (or cloud HSM) is single-tenant hardware where you control the keys and the partition.
| Factor | Cloud KMS | Dedicated HSM |
| Control | Provider-managed, shared infrastructure | Customer-controlled, single tenant |
| Compliance | Often FIPS 140-2/3 Level 2-3 | Needed for strict Level 3 or specific mandates |
| Effort and cost | Low, pay per use | Higher, you manage availability and users |
| Typical use | Envelope encryption, app secrets | Root CA keys, payment PIN, code signing |
Choose KMS by default. Choose a dedicated HSM when regulation, a payment standard, or a requirement that the provider cannot access the key material demands it.
Take quiz
protecting a root CA or code-signing key under strict compliance
caching web pages
hosting static images
storing a feature flag
an unencrypted config file
a USB drive in a drawer
a cloud KMS
a shared spreadsheet
47. What is a TOCTOU race condition vulnerability?
Time-of-check to time-of-use (TOCTOU) is a race condition where a program checks a condition and then acts on it later, but the state changes in between. An attacker wins the race to swap the resource after the check passes.
Classic file example: a program checks that a path is a normal file the user owns, then opens it. Between those steps the attacker replaces it with a symlink to /etc/shadow.
The same pattern appears in web apps, such as double-spending a coupon or withdrawing funds with parallel requests.
- Make check and use atomic: open first, then check the file descriptor (
fstat). - Use database transactions, row locks or unique constraints.
- Use idempotency keys for repeated requests.
Take quiz
the certificate expires
the state changes between the check and the use
the password is too short
the data is not hashed
adding a CAPTCHA only
a longer coupon code
hiding the coupon field
a transaction with a unique constraint or row lock
48. How do you design secure session management?
A session ID is a bearer credential, so anyone holding it is that user. Design the lifecycle around protecting and limiting it.
- Generate IDs with a cryptographically secure random generator, at least 128 bits.
- Set cookies with
Secure,HttpOnlyandSameSite. - Regenerate the ID on login and privilege change to stop session fixation.
- Use idle and absolute timeouts, and invalidate server-side on logout.
- Re-authenticate for sensitive actions like changing email or payment details.
- Let users see and revoke active sessions.
Set-Cookie: sid=9f3c...; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=1800
Take quiz
using shorter usernames
disabling HTTPS
regenerating the session ID after login
storing the ID in the URL
stops JavaScript from reading the cookie
forces the cookie to be sent over HTTP only
encrypts the cookie value
blocks all cross-site requests
49. What is insecure deserialization and how do you prevent it?
Insecure deserialization happens when an application rebuilds objects from untrusted serialized data. If the format can instantiate arbitrary classes, the attacker crafts data that triggers dangerous code during deserialization, using "gadget chains" in existing libraries, which often ends in remote code execution.
Java native serialization, Python pickle, PHP unserialize and .NET BinaryFormatter are well-known risky examples.
- Do not deserialize untrusted data with native object formats.
- Use plain data formats such as JSON with strict schemas.
- Sign serialized data (HMAC) and verify before parsing.
- Apply type allowlists, and run with low privileges.
# Dangerous: executes attacker-controlled code on load import pickle obj = pickle.loads(untrusted_bytes)
Take quiz
a length limit on the request
a strict JSON schema validator
an HMAC check
Python pickle.loads
a chain of firewalls
existing classes combined so deserialization triggers attacker-chosen behavior
a set of TLS ciphers
a list of network routes
50. How would you design a secure multi-tenant SaaS architecture?
The core goal is tenant isolation: one customer must never read or affect another customer's data or availability.
| Layer | Approach |
| Identity | Tenant ID in the token claims, validated server-side, never taken from client input |
| Data | Separate databases or schemas for high isolation, or shared tables with enforced row-level security |
| Encryption | Per-tenant keys in KMS, enabling tenant-specific revocation |
| Compute | Resource quotas, rate limits per tenant, noisy-neighbor protection |
| Network | Segmentation and private connectivity options for large customers |
| Operations | Tenant-scoped audit logs, admin access with just-in-time approval |
Add automated cross-tenant access tests to CI, since the typical bug is a missing tenant filter in one query. Choose the isolation level by risk and cost, and document it for customers.