Threat Modeling and Attack Surface Analysis Questions
Systematically identifying how a system can be attacked and where its exposure lies. Covers structured methodologies (STRIDE, PASTA, DREAD, OCTAVE, attack trees), enumerating and reducing attack surface, mapping trust boundaries and data flows via DFDs, profiling likely threat actors, and prioritizing identified threats by likelihood and impact during design. Includes applying this methodology to specific architectural substrates (cloud-native and serverless, microservices, ML/AI systems, IoT, CI/CD pipelines, cryptographic subsystems) and operationalizing it as a recurring program (SDLC integration, governance, tooling, KPIs). The proactive 'think like an attacker before you build' discipline: distinct from live penetration testing (the adversarial validation of a built system), from runtime detection/monitoring (recognizing an attack already in progress), and from implementing the resulting security controls (a separate design-and-build discipline).
Propose a quantitative scoring system to prioritize cryptographic threats: define likelihood and impact factors specific to crypto (exploitability, attacker resources, required cryptanalytic effort, data sensitivity, cryptographic lifetime), give a scoring formula or matrix, and justify weighting choices using two example threats.
Sample Answer
Direct answer
A quantitative scoring system for cryptographic threats needs to split its five natural inputs, exploitability, attacker resources required, required cryptanalytic effort, data sensitivity, and cryptographic lifetime, into a likelihood side (the first three, since they describe how hard the threat is to pull off right now) and an impact side (the last two, since they describe how bad it is if it succeeds). Multiplying a 1-5 likelihood score by a 1-5 impact score gives a simple, defensible priority ranking, but a naive version of that formula systematically under-ranks one important class of crypto threat: attacks that are not feasible today but whose required secrecy window is long, which is why the worked example below deliberately includes a check beyond the raw multiplication.
Structured elaboration
Sorting the five named factors into likelihood and impact.
- Likelihood factors (how achievable is exploitation right now):
- Exploitability (E, 1-5): how straightforward exploitation is once the weakness is identified, given current knowledge and tooling.
- Attacker resources required (AR, 1-5): how much compute, specialized hardware, or organizational capability (nation-state versus individual) exploitation demands; scored so a HIGHER number means MORE resources are needed, which is why it gets inverted before combining, since more required resources means LOWER likelihood.
- Required cryptanalytic effort (CE, 1-5): how novel or difficult the underlying cryptanalysis itself is, independent of raw compute; also inverted before combining for the same reason as attacker resources.
- Impact factors (how bad is it if the threat succeeds):
- Data sensitivity (DS, 1-5): the harm from the protected data being exposed or forged.
- Cryptographic lifetime (CL, 1-5): how long the data or key must remain protected; a longer required lifetime raises impact because it widens the window during which a future improvement in attacker capability could still compromise something that was supposedly already safe.
Scoring formula. Combine the three likelihood factors, inverting the two that are framed as "resistance," and the two impact factors, into a single risk score:
L=3E+(6−AR)+(6−CE),I=2DS+CL,RawScore=L×I
RawScore ranges from 1 to 25; normalizing to a 0-10 scale, Score10=25RawScore×10, keeps it comparable to other risk scoring already in use elsewhere in the organization.
Worked example
Threat A: nonce reuse in an AES-GCM (Advanced Encryption Standard, Galois/Counter Mode) implementation, enabling forgery and partial plaintext recovery once a nonce repeats. Scores: E=5 (once identified, exploitation is well-documented and requires no novel research), AR=1 (a standard laptop suffices), CE=1 (a known algebraic technique, not new cryptanalysis).
L=35+(6−1)+(6−1)=35+5+5=5.0
Impact side: DS=4 (exposes session-level traffic integrity and confidentiality, serious but not a full historical archive), CL=2 (short-lived session keys, narrow exposure window).
I=24+2=3.0,RawScore=5.0×3.0=15.0,Score10=2515.0×10=6.0
Threat B: harvest-now-decrypt-later against RSA-2048 key exchange protecting 20-year-retention health records, where an adversary collects encrypted traffic today intending to decrypt it once a sufficiently capable quantum computer exists. Scores: E=1 (not exploitable today, no such computer exists yet), AR=5 (requires a nation-state-scale, currently nonexistent capability), CE=5 (requires a fundamentally new computational capability, not incremental cryptanalysis).
L=31+(6−5)+(6−5)=31+1+1=1.0
Impact side: DS=5 (protected health information, highest sensitivity), CL=5 (a 20-year regulatory retention requirement, the longest lifetime on the scale).
I=25+5=5.0,RawScore=1.0×5.0=5.0,Score10=255.0×10=2.0
Naive multiplication ranks Threat A (score 6.0) well above Threat B (score 2.0), because Threat A's likelihood dominates the product even though Threat B's impact factors are both at the maximum. This is exactly the failure mode a quantitative crypto-risk model needs to catch rather than trust blindly: for any threat where CL is high, apply a second, purpose-built check before accepting a low raw score, using Mosca's inequality, a widely used post-quantum migration planning heuristic. If X+Y>Z, where X is the required data confidentiality lifetime, Y is the time needed to migrate to quantum-safe cryptography, and Z is the time until a cryptographically relevant quantum computer plausibly exists, the organization has a problem regardless of how low today's raw likelihood score reads. For Threat B, illustrative planning figures: X=20 years (the retention requirement), Y=5 years (an illustrative estimate for migrating this system's key exchange to a post-quantum algorithm), and treating Z as genuinely uncertain but illustratively bounded around 15 years for this exercise:
X+Y=20+5=25>15=Z
The inequality holds, flagging Threat B as urgent to begin migration planning for now, despite its raw multiplicative score of 2.0 ranking it below Threat A. Threat A needs no such override, since a short cryptographic lifetime means there is no long future window for a currently-infeasible capability to catch up to it.
Trade-offs and pitfalls
The central pitfall, deliberately built into the worked example above, is trusting a single multiplicative likelihood-times-impact score without checking it against a lifetime-aware overlay for any threat where cryptographic lifetime is high; naive multiplication structurally discounts low-likelihood-today, high-future-impact threats exactly when a long lifetime is the reason they deserve more attention, not less. A second pitfall is picking scores for exploitability, attacker resources, and cryptanalytic effort without documenting the reasoning behind each number, since these are judgment calls (unlike, say, a directly measured CVSS metric) and an unscored justification makes the model impossible for another reviewer to sanity-check or recalibrate as the underlying assumptions age, particularly for anything touching quantum timelines, which are inherently uncertain and will need periodic revisiting. A third is applying Z (the estimated time until a cryptographically relevant quantum computer exists) as if it were a precise, known figure; it is a genuinely contested estimate across the field, so a defensible practice is to run the inequality check at a conservative (shorter) Z for the highest-lifetime data and treat the result as a planning trigger rather than a certainty.
Explain common risk scoring models used with threat modeling: CVSS, DREAD, and modern alternatives or best practices. Discuss strengths and weaknesses of each, and describe how you'd choose or combine models to communicate risk to both technical teams and business stakeholders.
Sample Answer
Direct answer
Common Vulnerability Scoring System (CVSS) and DREAD (Damage potential, Reproducibility, Exploitability, Affected users, Discoverability) answer different questions, CVSS is a standardized technical severity score, DREAD is a lightweight, team-scored relative-priority tool, and neither alone tells you whether something is actually likely to be attacked. A modern addition, the Exploit Prediction Scoring System (EPSS), closes that specific gap by estimating the probability of real-world exploitation. The strongest practice combines a standardized severity or exploitability signal with an organization-specific business-impact rating, then presents that combination differently to technical and business audiences rather than reporting the same raw number to both.
Structured elaboration
CVSS. A standardized, vendor-neutral score from 0 to 10, maintained by the Forum of Incident Response and Security Teams (FIRST), based on exploitability and impact metrics: attack vector, attack complexity, privileges required, user interaction, scope, and impact on confidentiality, integrity, and availability for the base score, with optional temporal and environmental metric groups that adjust the score for real-world exploit maturity and the specific deployment context. Strengths: standardized and widely adopted, giving a shared, comparable vocabulary across security teams, vendors, and researchers, and technically precise about exploit mechanics. Weaknesses: the base score alone does not reflect the actual likelihood of exploitation against a specific system or the asset's business importance, so a 9.8 against an internal system with no interesting data can rank the same as a 9.8 against a crown-jewel payment system unless the environmental metrics are actually used, which many organizations skip, and speaking a raw CVSS number directly to business stakeholders does not naturally translate into a business decision without added context.
DREAD. Each of the five factors, damage potential, reproducibility, exploitability, affected users, and discoverability, is rated on a scale and combined, commonly averaged, into a single relative score. It was originally developed for lightweight, rater-driven relative prioritization rather than as a standardized industry benchmark. Strengths: simple and fast to apply, and each of its five factors is easy to explain in plain language, how bad, how repeatable, how hard to pull off, how many affected, how easy to find, which can actually make it more approachable to a mixed audience than CVSS's more technical metric vocabulary. Weaknesses: subjective, since ratings depend heavily on who is scoring, unlike CVSS's more structured metric definitions, so scores from different raters or teams are not reliably comparable to each other, and it lacks CVSS's broad industry standardization, a DREAD score is really only meaningful within one team's own consistent rating practice, not across organizations or against externally published scores.
A modern alternative: EPSS. A data-driven score estimating the probability that a vulnerability will actually be exploited in the wild within a near-term window, based on observed exploitation activity and vulnerability characteristics, also maintained by FIRST. Strength: it directly addresses CVSS's biggest practical gap, distinguishing "severe if exploited" from "likely to actually be exploited," the same realized-risk signal that matters for prioritizing a large backlog of findings. Weakness: it is a probability of exploitation, not a measure of impact to a specific organization, so it needs to be combined with asset criticality or business impact rather than used alone. The broader best practice, regardless of which specific score, is to combine a standardized technical or exploitability signal (CVSS and, where available, EPSS) with an organization-specific business-impact rating, rather than relying on any single score as a complete answer.
Choosing and combining scores for two audiences. For technical stakeholders, engineers and security analysts, lead with the standardized, precise scores: CVSS's metric breakdown to explain exactly why something is severe, which specific vector, what privilege is needed, and, where relevant, EPSS or observed-exploitation status to explain urgency. This audience wants the mechanism, not just a label. For business stakeholders, executives, product, or compliance leadership, translate the same underlying findings into business terms: likelihood expressed as "how likely, in plain terms, and why" rather than a raw percentage, and impact expressed in terms the business already tracks, regulatory exposure, customer-facing downtime, or a financial-loss magnitude tier, rather than a confidentiality, integrity, and availability breakdown. A small number of prioritized tiers, critical, high, medium, low, communicates far better to this audience than the underlying numeric scores themselves. The bridge between the two: maintain one underlying scoring approach and present two views of it, a detailed technical view for engineers and a summarized tiered view for business stakeholders, rather than two disconnected narratives that can drift apart or contradict each other when someone compares them.
Worked example
(Illustrative scenario, not a specific published vulnerability.) Consider a hypothetical flaw in a cryptographic library: a weak pseudo-random number generator used for session-key generation, producing predictable keys under specific conditions.
CVSS v3.1 (illustrative): the flaw is reachable over the network, needs no privileges and no user interaction, and breaks the confidentiality of session data without directly altering it, which is the vector AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N and a base score of 7.5. Quote the vector, not just the number: the vector is what makes the score reproducible by anyone who wants to recompute it, and it is exactly the mechanism-level detail the technical audience below is asking for.
DREAD (illustrative, each factor rated 1-10, then averaged): Damage 8 (compromised session keys enable session hijacking); Reproducibility 6 (requires specific, not universal, conditions to trigger predictable output); Exploitability 7 (once conditions are known, exploitation is straightforward); Affected users 9 (affects any session using the library under the vulnerable configuration); Discoverability 5 (requires cryptographic analysis to notice, not immediately obvious from black-box testing).
DREAD average=58+6+7+9+5=535=7.0EPSS (illustrative): a low-to-moderate initial exploitation probability, since weaponizing the flaw requires cryptographic expertise, flagged for ongoing re-monitoring because EPSS updates as real-world exploitation activity is observed, and a public proof-of-concept would likely raise it quickly.
To technical stakeholders: "CVSS 7.5, vector AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N, so network-reachable, low complexity, no privileges needed, breaking confidentiality via predictable session-key generation; exploitation probability currently low but expected to rise if a public proof-of-concept for the random-number-generator weakness appears."
To business stakeholders: "A high-severity flaw in how we generate session keys could let an attacker hijack user sessions under specific conditions. Current real-world exploitation likelihood is low but could rise quickly, and because this touches every session across the platform, we are prioritizing a fix within the critical remediation window rather than the normal patch cycle."
Trade-offs and pitfalls
Reporting a raw DREAD or CVSS number to business stakeholders with no translation is a common failure; "it's a 7.0" means nothing to someone who does not work with the scale daily, and repeatedly doing this trains business stakeholders to tune out security reporting entirely. Relying on CVSS base score alone for prioritization, ignoring exploitation evidence and business impact, systematically over-invests in high-severity-but-unlikely findings and under-invests in moderate-severity-but-actively-exploited ones. DREAD's subjectivity means using it for cross-team or cross-organization comparison, for example benchmarking one team's DREAD scores against a vendor's, is not meaningful; it is only self-consistent within one team's own disciplined rating practice. For cryptographic findings specifically, discoverability and exploitability ratings can be systematically mis-scored by raters without cryptographic expertise, rating a subtle cryptographic weakness as hard to discover and low priority when it is actually well known in the cryptographic research community, so pull in genuine cryptographic expertise for that specific factor rather than defaulting to a generalist's intuition.
Perform a focused threat model on key management for a SaaS product that uses HSMs to sign tokens and encrypt customer data at rest. Identify threats to key confidentiality, integrity, and availability; propose operational controls (rotation, backup, split knowledge, access controls), HSM deployment patterns (single-region vs multi-region, cloud HSM vs on-prem), and discuss trade-offs between latency, cost, and security.
Sample Answer
Direct answer
A focused threat model on hardware security module (HSM) based key management has to score threats separately against each leg of the confidentiality, integrity, availability (CIA) triad, because the controls that protect one leg often do little for another: encrypting key backups protects confidentiality but does nothing for availability if the only HSM holding the live key fails, and dual control protects integrity of key operations but does not by itself protect the key from ever being extracted. The strongest architectures combine operational controls (rotation, backup, split knowledge, access control) with a deployment pattern (single-region vs multi-region, cloud HSM vs on-premises) chosen deliberately for the latency, cost, and security trade-offs the business actually needs, not a default.
Structured elaboration
Threats by CIA leg.
- Confidentiality: the key material itself is extracted or exported in usable form. The main threats are a compromised HSM administrator abusing legitimate export/backup functionality, a firmware or supply-chain compromise of the HSM itself, and side-channel attacks against key operations (timing, power analysis) on lower-assurance hardware.
- Integrity: the key is used to sign or encrypt something it should not, without the key itself being stolen. The main threats are an attacker who compromises the application or service account authorized to call the HSM (so they get to use the key, not steal it), and insufficient authorization checks inside the HSM's policy layer letting a valid credential perform an operation it should not be allowed to perform (for example, a service account scoped for encryption also being able to sign).
- Availability: the key becomes unusable when needed, whether through HSM hardware failure, network partition between the application and a remote HSM, accidental key deletion, or an expired/misrotated key with no valid predecessor still trusted by relying parties.
Operational controls.
- Rotation: define a rotation interval per key class based on how much data or how many operations a compromise would expose, and, critically, plan the overlap window where both the old and new key are valid so in-flight signed tokens or previously encrypted data are not orphaned. Rotation without a tested rollover procedure is a common way availability incidents get created by the rotation itself.
- Backup: key backups must be encrypted under a separate backup key (never stored as extractable plaintext, even "for disaster recovery"), stored in a physically or logically separate location from the primary HSM, and restore-tested on a schedule, not just written and assumed good.
- Split knowledge (and dual control): no single individual should hold enough key-share or credential material alone to reconstruct or use a key outside the HSM's policy engine. This is usually implemented via HSM-native multi-person authorization (an m-of-n quorum of key custodians required to perform sensitive operations like key export or policy change), which protects against both a single malicious insider and a single compromised credential.
- Access control: application-layer access to HSM operations should be scoped per service and per operation (a service that only needs to verify signatures should not hold a credential that can also sign), logged with non-repudiation (the HSM's own audit log, not just the calling application's), and reviewed on the same cadence as any other privileged-access control.
HSM deployment patterns.
- Single-region vs multi-region: single-region minimizes latency and operational complexity but makes the HSM (and, by extension, everything that depends on that key) a regional single point of failure; multi-region replication or clustering trades added complexity and, for some HSM architectures, higher latency on writes or key-state synchronization, for regional failover. Cost moves differently here than it does for stateless compute, and it belongs in the decision explicitly: an HSM is a dedicated appliance or a dedicated cloud instance that is paid for whether or not it is signing anything, so an active-active two-region cluster is roughly double the standing key-management spend of a single region before any cross-region networking, and it does not get cheaper when traffic is low. That is why multi-region is worth justifying per key class rather than adopting as a blanket posture.
- Cloud HSM vs on-premises: a cloud provider's managed HSM service shifts hardware lifecycle, patching, and physical security to the provider (commonly validated to FIPS 140-2 or the newer FIPS 140-3 standard at Level 2 or Level 3, depending on the offering) and typically integrates natively with that provider's identity and access management, at the cost of some loss of physical control and, for the highest-assurance use cases, a trust dependency on the provider's own operational security. On-premises HSMs give full physical control and can meet stricter regulatory or contractual requirements that mandate customer-controlled hardware, at the cost of the organization owning the full operational burden (physical security, firmware patching, spares, staffing 24/7 coverage). The two options also differ in the SHAPE of their cost, not only its size, which matters more than the headline number: cloud HSM is operating expenditure billed per instance-hour with no capital outlay and the option to add or remove capacity, while on-premises is a capital purchase of appliances plus spares, amortized over years, whose recurring cost sits mostly in staffing rather than in the hardware. On-premises can genuinely be cheaper at sustained high call volume and is usually more expensive at low or spiky volume, which is the reverse of the common intuition that owning the hardware must be the cheaper option.
Worked example
Trace a single scenario through both axes: a SaaS product needs an HSM-backed key to sign customer-facing authentication tokens, where a token-signing outage directly blocks every customer login. Availability is the dominant concern for this specific key, more than for a key used only for periodic batch encryption, because the blast radius of unavailability is immediate and customer-visible. That pushes the deployment choice toward multi-region cloud HSM over a single on-premises unit: a single on-premises HSM, even a well-managed one, represents a hardware single point of failure that a token-signing service cannot tolerate, while a multi-region cloud HSM cluster trades a modest latency increase on the signing call (an extra network hop to the HSM endpoint, and potentially cross-region key-state synchronization overhead) for regional failover. The cost side of that choice deserves to be said out loud rather than waved through: multi-region roughly doubles the standing HSM spend, and the honest justification is not that the money is negligible, it is that what the money buys is the removal of a single hardware failure that would take every customer login offline. Framed that way it is a comparison the business can actually make and sign off on, rather than a security-team assertion that redundancy is simply required.
Layer the operational controls onto that choice: rotate the signing key on a defined interval with an overlap window so tokens signed just before rotation remain verifiable until they naturally expire, require dual control (a two-person HSM-native quorum) for any operation that would export or delete the key, encrypt backups under a separate backup key stored in a different logical boundary than the primary key material, and scope access so the token-issuing service can only sign, while a separate, more restricted credential is the only one authorized to rotate or delete keys. This combination directly maps back to the CIA threats above: dual control and scoped access address the integrity threat (a compromised token-issuing service account still cannot rotate or export the key), encrypted, tested backups plus multi-region deployment address the availability threat, and restricting who can invoke export operations at all, combined with the HSM's own non-exportable-by-design key storage, addresses the confidentiality threat.
Trade-offs and pitfalls
The most common mistake is optimizing purely for confidentiality (extraction resistance) while quietly under-investing in availability, because "the key was stolen" is a more dramatic incident to imagine than "the key became unusable," even though an unavailable signing key can take down an entire authentication path just as effectively as a stolen one, and faster. A second pitfall is treating cloud HSM and on-premises HSM as a purely technical decision when it is often a regulatory or contractual one; some data-residency or key-custody requirements mandate customer-controlled hardware regardless of the latency or cost case for a managed service, so the deployment pattern needs to be checked against compliance obligations before the engineering trade-off is even relevant. A third is implementing split knowledge only on paper (a documented policy that two people are supposed to be present) rather than enforced by the HSM's own multi-person authorization quorum; a policy that depends on human process discipline rather than the hardware's own access-control mechanism is not actually split knowledge, it is a procedure that can be, and eventually will be, skipped under operational pressure. Finally, multi-region deployment for availability can quietly weaken the confidentiality story if key material or key-derivation secrets are replicated across regions with different physical security postures; the deployment pattern chosen for availability needs to be re-evaluated against the confidentiality threat model, not assumed to be free.
You manage a service storing PII across an RDBMS, an object store, and an in-memory cache. Apply STRIDE focusing on Information Disclosure and Tampering: identify where and how sensitive data can leak or be tampered with, and propose an encryption and key-management architecture (including KMS usage, rotation, access control, and performance trade-offs).
Sample Answer
Direct answer
Applying STRIDE's Information Disclosure and Tampering categories separately to a relational database (RDBMS), an object store, and an in-memory cache matters because personally identifiable information (PII) leaks and gets modified through different mechanisms in each: the RDBMS is exposed mainly through query-layer access and backups, the object store through overly broad bucket policies and pre-signed URLs, and the cache through its usually-weaker default access model and the fact that data there is often copied out of the encrypted-at-rest system entirely. A workable encryption and key-management architecture uses envelope encryption with a central key management service (KMS), per-datastore access scoping, and a rotation plan, and treats the cache as a datastore that must hold ciphertext like the other two rather than as a performance layer exempt from the policy. The latency objection to encrypting the cache is real, but it is answered by WHERE the data key is held, not by conceding the cache to plaintext.
Structured elaboration
Information Disclosure and Tampering, mapped per datastore:
| Datastore | Information Disclosure risk | Tampering risk |
|---|---|---|
| RDBMS | Direct query access by an over-privileged application role or a compromised credential; PII exposed in ad hoc analyst queries or in a snapshot/backup that is less tightly controlled than the live database | An attacker or over-privileged process with write access modifies PII fields directly, or a SQL injection point in an upstream service writes attacker-controlled data into a PII column |
| Object store | An object-store bucket or prefix with a misconfigured policy (public, or overly broad principal grant) exposes stored PII documents; a pre-signed URL with an excessive expiry or a leaked pre-signed URL grants read access outside the intended flow | An attacker with write access (compromised credential, overly broad bucket policy) overwrites or replaces a stored object, for example swapping a legitimate document with a malicious or falsified one under the same key |
| In-memory cache | Cache entries are frequently unencrypted by default (encryption trades off against the cache's whole purpose, low-latency reads) and often live on shared infrastructure with a weaker default access-control model than the primary datastore; a compromised cache node or an operator with cache-admin access can read cached PII directly | An attacker who can write to the cache (weak authentication on the cache protocol, or a compromised service with cache write access) poisons cached PII, and because many services trust cache reads without re-validating against the source of truth, a poisoned cache entry can silently serve tampered PII to legitimate requests |
Encryption and key-management architecture.
Use envelope encryption everywhere PII is written: a central KMS holds and protects a small number of long-lived key-encryption keys (KEKs), while each record, object, or cache entry is encrypted under its own data-encryption key (DEK), which is itself encrypted by a KEK and stored alongside the ciphertext. This bounds the blast radius of a single leaked DEK to the data it actually protects, while keeping the expensive, access-controlled operation (calling the KMS) infrequent rather than on every read.
- RDBMS: column-level or field-level encryption for PII columns specifically (not full-disk encryption alone, which protects against a stolen physical disk but does nothing against a live, authenticated query reading the column in plaintext), with the DEK-per-tenant or DEK-per-sensitivity-class pattern so a single compromised DEK does not expose every customer's PII at once.
- Object store: server-side encryption with the KMS-managed key at write time, bucket policies scoped to least privilege per service, and short-lived, narrowly scoped pre-signed URLs (minutes, not days) generated only for the specific object and action needed, since a pre-signed URL is effectively a bearer credential for as long as it is valid.
- In-memory cache: encrypt PII fields before they enter the cache (application-layer encryption of the specific fields, not relying on the cache's own at-rest encryption, if any) so the cache only ever stores ciphertext plus the wrapped DEK reference, and cache invalidation on the source record's update includes invalidating the cached ciphertext so a rotated key does not leave stale plaintext-equivalent data reachable.
KMS usage, rotation, access control. Every DEK-unwrap operation goes through the KMS's access-control policy, which is where authorization actually lives (not application-level checks alone, which a compromised application process could bypass); scope KMS grants per service and per key-purpose, the same least-privilege principle as the datastore access controls themselves, so a service that only needs to decrypt cannot also request new key material or export raw key bytes. Rotate KEKs on a defined interval (commonly annually to a few years for infrequently-changing KEKs, since KMS providers typically support rotating the KEK while keeping older KEK versions available to decrypt DEKs wrapped under them) and rotate DEKs more frequently or per-write, since DEKs are cheap to generate and rotating them limits how much data any single DEK compromise exposes.
Performance trade-offs. The RDBMS and object store can absorb encryption's overhead reasonably well: column-level encryption adds CPU cost per row and can complicate range queries and indexing on encrypted columns (an encrypted column generally cannot be efficiently range-queried or sorted by the database engine itself), and object-store server-side encryption is close to free since it happens at the storage layer. The cache is the outlier: its entire value proposition is sub-millisecond reads, and calling out to a KMS or even doing local decryption on every cache hit can erode a meaningful fraction of that latency budget. The practical resolution is to decrypt once per process and hold the DEK (not the KMS-wrapped key) in memory for the service's lifetime or a bounded window, so the expensive KMS call happens rarely, while the cheap local decryption happens on each read, accepting that this keeps live plaintext-equivalent key material in the consuming service's process memory as a residual risk, mitigated by process isolation and short DEK lifetimes rather than eliminated. Be precise about which process that is: the DEK belongs in the service that reads and decrypts, never in the caching tier itself. A cache holding both the ciphertext and the key that opens it is storing plaintext with extra steps, and it would give back exactly the protection this design was built to gain.
Worked example
Trace one concrete flow: a customer support tool reads a customer's profile, which the RDBMS stores with an encrypted PII column (address, encrypted under a DEK wrapped by a KEK in the KMS), and caches the decrypted profile for 5 minutes to avoid re-querying the database on every support-tool page load. Under this design, the Information Disclosure risk in the RDBMS is addressed (a raw database dump exposes only ciphertext), but the cache now holds plaintext PII for up to 5 minutes, meaning the cache inherits the disclosure risk the database no longer has. If the cache's access control is weaker than the database's (a common real-world pattern, since caches are often treated as purely a performance layer rather than a data-sensitivity boundary), this flow has effectively moved the weakest link from the database to the cache rather than eliminating it. The fix that keeps the performance benefit without reintroducing the disclosure risk is to cache the encrypted form (ciphertext plus wrapped-DEK reference) instead of the decrypted profile, decrypting only in the requesting service's own memory at read time; the cache still saves the database round trip, but a compromised cache no longer directly yields plaintext PII.
Trade-offs and pitfalls
The most common mistake is applying full-disk or storage-layer encryption everywhere and treating that as equivalent to field-level protection against Information Disclosure; storage-layer encryption defends against a stolen disk or snapshot, not against an authenticated read path, which is the more common real-world disclosure path for all three datastores. A second is under-protecting the cache specifically, on the reasoning that "it's just a performance layer," when in practice the cache is frequently the datastore with the weakest access control and the one most likely to hold decrypted PII copied out of a properly encrypted source. A third pitfall on the Tampering side is trusting cache reads without re-validating against the source of truth for anything security-sensitive; a poisoned cache entry can silently serve tampered data to every subsequent reader until the entry's time-to-live (TTL) expires, so cache entries for sensitive fields should carry a way to detect tampering (an integrity tag alongside the ciphertext) even though the cache itself is not the system of record. Finally, KMS access-control scoping is easy to get right for who can decrypt and easy to get wrong for who can rotate, export, or delete key material; those higher-privilege KMS operations deserve tighter, more actively monitored access than routine decrypt calls, since abusing them can be far more damaging than any single record-level disclosure.
You are designing threat modeling for a small web service that stores user secrets (API keys and encrypted documents). Describe the step-by-step threat-modeling process you would apply, including assets, actors, entry points, trust boundaries, potential attack scenarios, and practical mitigations for each major risk.
Sample Answer
Direct answer
Threat modeling a small web service that stores user secrets (API keys and encrypted documents) follows a repeatable sequence: list what actually needs protecting, list who interacts with the system, map every place an outsider can reach it, mark where trust level changes as data moves through the system, walk each entry point for a realistic attack scenario, and propose a specific mitigation for each one. The step that most often gets rushed on a small service like this is trust boundaries, because it is tempting to treat "our backend" as one uniform trusted zone, when in practice the boundary between "authenticated as some user" and "authorized to see this specific user's secrets" is exactly where the highest-impact bugs tend to live.
Structured elaboration
1. Assets. What actually needs protecting, ranked by what a compromise would cost: user API keys (secrets that, if leaked, let an attacker impersonate the user to whatever third-party service the key belongs to), the encrypted documents and the keys used to encrypt them, user session tokens and credentials, and the service's own master key or key-management-service (KMS) key used to protect everything else.
2. Actors. Who legitimately or illegitimately interacts with the system: the authenticated end user (owns their own secrets, should never reach anyone else's), an external, unauthenticated attacker attempting to reach the service directly, and the service's own operators or administrators, who hold elevated access and are therefore both a legitimate actor and a potential insider-risk actor.
3. Entry points. Every place an outsider can touch the system: the login/authentication endpoint, the application programming interface (API) endpoints that create, retrieve, or delete a user's stored API keys, the document upload and download endpoints, and any administrative panel used for support or operations.
4. Trust boundaries. Where the level of trust actually changes, not merely where a network hop happens: the boundary between the public internet and the authentication layer (nothing is trusted yet); the boundary between "successfully authenticated" and "authorized for this specific resource," which is the boundary a small service most often gets wrong, since being logged in proves who you are but says nothing about which records you should be allowed to touch; and the boundary between the application backend and the KMS or database holding the actual secret material, which should require its own scoped credential rather than inheriting the application's general database access.
5. Attack scenarios, one plausible path per major risk:
- Credential stuffing against the login endpoint, using credentials leaked from an unrelated breach, to gain a legitimate session and then reach that user's own stored secrets legitimately (from the system's point of view).
- Broken authorization on the key-retrieval endpoint (an insecure direct object reference, where the endpoint checks that a request is authenticated but not that the requested key actually belongs to the requesting user), letting an authenticated attacker enumerate and read other users' API keys just by changing an identifier in the request.
- Secrets leaking into logs or error messages, where a stack trace or debug log inadvertently includes a plaintext API key or document content during a failure, creating a copy of the secret outside the system's actual protection boundary.
- Admin panel compromise, where an attacker who gains access to an operator account (phishing, credential reuse) inherits whatever broad access that panel grants, potentially including the ability to read secrets directly rather than only manage accounts.
6. Mitigations, mapped to the scenarios above:
- Rate limiting and multi-factor authentication (MFA) on the login endpoint blunts credential stuffing even when the attacker holds valid, leaked credentials.
- Explicit per-resource authorization checks on every key and document endpoint (confirming the authenticated user actually owns the specific record requested, not only that they are logged in) closes the broken-authorization path; this needs to be enforced consistently for every operation, not only the ones that seemed obviously sensitive during initial development.
- Structured logging with automatic secret redaction, and treating any logging or error-handling code path that touches a secret value as security-sensitive code requiring its own review, prevents the accidental-leak path.
- Scoping admin access narrowly (support staff should not, by default, be able to view raw secret values, only metadata needed for support) and requiring a separate, logged, deliberate action for the rare case where raw access is genuinely needed, reduces both the insider-risk surface and the value of a single compromised admin account.
Worked example
Trace the broken-authorization scenario concretely, since it is the one most specific to this exact system and the easiest to introduce accidentally. The API key retrieval endpoint is implemented as GET /api/keys/{keyId}, and the handler checks that the request carries a valid session token before returning the key, but does not check that keyId belongs to the session's user, an easy omission when the same handler pattern is copied from an earlier endpoint that happened not to need per-owner scoping. An authenticated attacker, who only needs their own valid, low-privilege account to reach the endpoint at all, can then increment or guess keyId values across other users' records and retrieve API keys that were never theirs, entirely within what looks like a normal authenticated request from the system's perspective, since authentication succeeded correctly every time. The mitigation is not "add more authentication," since the failure was never in authentication, it was in authorization: the fix is adding an explicit ownership check, confirming the key referenced by keyId belongs to the authenticated session's user before returning it, and applying that same check pattern to every other resource-scoped endpoint (documents, any future secret type) rather than fixing this one endpoint in isolation.
Trade-offs and pitfalls
The most common mistake on a service like this is conflating authentication with authorization, treating "the request has a valid session" as equivalent to "the request should see this specific data," which is exactly the gap the worked example exploits; the two checks need to be separate, deliberate steps on every resource-scoped endpoint. A second pitfall is under-scoping trust boundaries to only the perimeter (public internet versus backend) and skipping the internal one between "authenticated" and "authorized," which is where this class of bug actually lives on most small services, not at the network edge. A third, easy to miss on a small team, is treating logging and error handling as separate from the security review process; the code path that formats an error message is not obviously security-sensitive, but if it can ever include a secret value in its output, it is exactly as sensitive as the code that stores that secret in the first place, and deserves the same scrutiny.
Unlock Full Question Bank
Get access to all 7 Threat Modeling and Attack Surface Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.