Building Secure Systems
Security Engineering: Foundations and Failure Modes
What Security Means
Security is the ability to achieve a goal despite the presence of an adversary. An adversary may try to steal information, alter data, disrupt a service, or otherwise prevent a system from working as intended. A secure system aims to continue providing its intended functionality even when someone is actively trying to defeat it.
Security can be understood through three connected elements:
Policy: What the system is supposed to allow or prevent.
Threat model: What the designer assumes the adversary can and cannot do.
Mechanism: The hardware and software that enforce the policy under the threat model.
A system’s security depends on all three. A policy can be poorly chosen, a threat model can underestimate an attacker, or a mechanism can fail to enforce the policy correctly.
Security Policies
A security policy states the system’s desired protections and permissions. Important policy goals commonly concern:
Confidentiality: Information should be readable only by authorized parties. For example, a course’s grade file should be accessible only to authorized staff.
Integrity: Information should be changed only by authorized parties. For example, only authorized staff should be able to modify grades.
Availability: A service or resource should remain usable by authorized people. For example, a website should continue operating even if an attacker tries to overwhelm it with requests.
Policies need to be stated carefully. A system may provide confidentiality but fail at integrity, or preserve both while remaining vulnerable to denial-of-service attacks.
Threat Models
A threat model describes the adversary’s capabilities and the assumptions made about the environment. It might specify, for example, whether an attacker can send arbitrary network traffic, learn a user’s password, access a device physically, or compromise a software supplier.
Threat models are necessary because a system cannot realistically defend against an adversary who can do absolutely anything. However, overly optimistic assumptions can leave the system exposed. Designers should generally err on the side of caution and consider plausible ways an attacker might gain access or information.
Security Mechanisms
A security mechanism is the part of the system intended to enforce the policy. It may include software, hardware, cryptographic protocols, access controls, or combinations of these.
The intended result is that the mechanism enforces the policy as long as the threat model is accurate. If the mechanism has a bug, or if the threat model omits a capability the attacker actually has, the policy may not be achieved.
A security claim is meaningful only in the context of a specific policy, a specific threat model, and mechanisms that correctly enforce the policy.
Why Security Is Difficult
Security Is Often a Negative Goal
Many ordinary system requirements are relatively easy to test. If a system is supposed to let authorized users read a file, a test can check whether those users can read it.
Security often requires a stronger claim: no unauthorized user can read the file. That means considering not only the obvious access path, but also every alternative route an attacker might try. An attacker may guess a password, exploit a software flaw, steal a device, or take advantage of an interaction between services.
The difference is important:
Showing that a permitted action works requires testing some intended cases.
Showing that a forbidden action cannot work requires accounting for a broad range of possible attacks.
This makes security a difficult problem of excluding unwanted outcomes.
Security Design Is Iterative
Security is rarely established once and then finished. Designers discover weaknesses, revise assumptions, fix mechanisms, and test again. At each stage, the system may have a weakest link:
The threat model may omit a realistic attacker capability.
The policy may allow an unintended path to access.
The mechanism may contain a coding or design error.
Security therefore involves repeatedly asking where the system can fail and changing the design in response.
A Vulnerability Does Not Make Every System Useless
Every system has limits. Finding a condition under which a design fails does not mean that the design is worthless; it means that its safe operating conditions need to be understood. Security analysis helps identify those conditions so that a system is used appropriately and its weaknesses can be addressed.
Stronger security can also enable new functionality. For example, a browser sandbox can allow code to run with restricted access to the rest of a computer. With such protections, users may be able to run applications in a browser without trusting every program to behave safely. Security mechanisms can therefore make previously impractical services possible, not merely block attacks.
Policy Failures
A system can fail because its policy permits an unsafe form of access, even if the software correctly implements that policy.
Account-Recovery Questions Can Weaken Authentication
A website may normally allow access only to someone who knows the account password. If the website also permits access to someone who can answer recovery questions, the effective policy becomes:
Access is allowed if the person knows the password or can answer the recovery questions.
The recovery process has therefore added another way into the account. If the answers are easy to discover—for example, from public information—the account may be less secure than it appears. Recovery procedures should be treated as part of the authentication policy, not as harmless administrative features.
Weaknesses Can Compose Across Services
A more complex problem arises when several services each offer a reasonable-looking recovery feature, but together they create an attack path. Consider a sequence involving an email account, a cloud account, and an online shopping account:
An attacker asks the email provider to reset a password. The provider sends a recovery link to a backup email account.
The attacker does not yet control the backup email account, but can try to reset its password through another service.
The backup-email service allows password recovery using information such as a billing address and the last digits of a payment card.
The attacker gains access to a shopping account, perhaps by adding a new card to it and then using that card to satisfy the shopping service’s password-reset check.
The shopping service reveals enough information about other cards on the account to satisfy the backup-email service’s recovery requirements.
Control of the backup email account then allows the attacker to follow the original recovery link and take over the primary email account.
Each service may have been designed with a locally plausible rule. The vulnerability appears in the composition of those rules: information or access gained through one system unlocks another.
This example illustrates why security must be assessed across connected services, not just one interface at a time. A recovery method should not depend on information that another service may reveal or let an attacker manufacture.
Threat-Model Failures
A system may have an appropriate policy and a technically correct mechanism but still fail because its assumptions about the adversary are wrong.
Human Behavior Is Hard to Predict
Systems often assume users will:
Choose strong, difficult-to-guess passwords.
Notice when a website is not the legitimate site they intended to visit.
Avoid clicking suspicious links.
Pay close attention to warnings and authentication prompts.
These assumptions are often unreliable. People may choose predictable passwords, click on convincing links, or enter credentials on a fraudulent site. A threat model that depends on every user consistently making ideal choices is likely to fail. Security should account for ordinary human behavior rather than assuming perfect attention or expertise.
Threat Models Can Become Outdated
An assumption that was reasonable when a system was designed may stop being safe as technology changes.
For example, a cryptographic key size that once seemed difficult to search may become vulnerable as computers grow faster or specialized hardware becomes available. A system designed around a particular key size must be reassessed over time; security does not remain constant just because the original design was once acceptable.
Threat models may also change when new information becomes available. If an attacker might be able to tamper with a device’s hardware, installing software defenses may not be enough. The appropriate level of protection depends on the adversary being considered: defending against casual snooping may require different measures from defending against a powerful, well-resourced attacker.
A System May Rely on Too Many Trusted Authorities
Secure web connections use certificates to bind a website’s name to a cryptographic key. A browser relies on certificate authorities to make and sign these claims.
A weakness in this design is that a browser may trust many certificate authorities. If any trusted authority can issue a certificate for any domain name, the browser’s security depends on all of those authorities behaving correctly. Compromising or misleading even one of them can potentially allow an attacker to impersonate a website.
The underlying threat-model mistake is assuming that every authority in a large, distributed set will remain trustworthy and secure. A system’s real security can be limited by its least trustworthy dependency.
The Software Supply Chain Is Part of the Threat Model
A secure program can be compromised before it is even built. Suppose an operating system’s source code is stored on a poorly secured development server. An attacker who changes the source code there may insert a back door. When researchers or developers later build the operating system, the resulting software inherits the malicious change.
This shows that security depends not only on the running program, but also on how its source code is stored, reviewed, built, and distributed. The origin and integrity of software must be included in the threat model.
Mechanism Failures
Even when the policy and threat model are sensible, the mechanism may fail to enforce the policy.
Inconsistent Password-Guessing Limits
A common defense against password guessing is to limit repeated login attempts. After a small number of failures, the system may require the user to wait before trying again. This slows down an attacker who is trying many likely passwords.
A service may apply this protection to most login interfaces but accidentally omit it from one interface. If that interface allows unlimited attempts, an attacker can make a large number of guesses through that route, even though other routes are protected.
The overall system is only as strong as its least-protected interface. Every route to the same account or resource must enforce the relevant security checks consistently.
Missing Access-Control Checks
A site might require users to log in before showing their account page, then use a URL containing an account identifier to select which account to display. If the site checks only that the identifier is valid, but not that the account belongs to the logged-in user, someone may be able to change the identifier and view another person’s information.
The required check is not simply “does this account exist?” It is “is the current user authorized to access this account?” This class of failure demonstrates that authentication—establishing who the user is—is not enough. The mechanism must also perform authorization—determining what that user may access.
Weak or Repeated Randomness in Cryptographic Systems
Cryptographic systems often depend on unpredictable values. A pseudorandom number generator (PRNG) can expand a secret random seed into a stream of values that appear unpredictable, but this works only if the generator is initialized correctly with enough randomness.
If a software library fails to initialize a PRNG, or initializes it with a predictable value such as all zeros, different users or devices may generate the same supposedly random values. An attacker who can predict those values may be able to predict cryptographic keys or other secrets built from them.
Bitcoin provides an example of how sensitive cryptographic protocols can be to randomness. A Bitcoin private key controls the ability to spend the associated funds. In addition, some signature schemes require a fresh random value, called a nonce, for each signature. If a nonce is reused in certain schemes, the private key can be recovered from the signatures. Thus, even if the private key was initially generated securely, mistakes in the randomness used for signing can expose it.
Cryptographic correctness depends on details such as initialization, unpredictability, and avoiding reuse where the protocol requires fresh values.
Encoding Differences and Ambiguous Data
Security problems can arise when two parts of a system interpret the same bytes differently.
Length-Prefixed and Null-Terminated Strings
One kind of certificate encoding stores a name together with its length. A program written in C commonly represents a string by ending it with a zero byte, written as \0. These two conventions can disagree about where a name ends.
Suppose an attacker is allowed to obtain a certificate for a subdomain they control. They may request a name that begins with a legitimate website’s name, followed by a zero byte and then the attacker-controlled domain. The certificate authority may interpret the full, length-prefixed name as belonging to the attacker’s domain. A browser that treats the name as a C-style string may stop at the zero byte and interpret it as the legitimate website’s name.
The security failure comes from inconsistent interpretation:
One component sees the complete encoded name.
Another component stops at the embedded zero byte.
Whenever components encode or parse data differently, an attacker may be able to find an input that one component accepts but another understands in a different way. Careful, consistent validation and encoding are essential.
Buffer Overflows
A buffer overflow occurs when a program writes more data into a fixed-size memory region than that region can hold. In programs written in C, this can corrupt nearby memory and sometimes let an attacker take control of program execution.
How a Buffer Overflow Happens
Consider a function with a fixed-size buffer intended to hold a request. If the program reads input into that buffer without checking the input length, an attacker can provide more bytes than the buffer can contain.
A function such as gets is unsafe because it reads input without knowing the destination buffer’s capacity. If the buffer holds 128 bytes but the input is longer, the extra bytes continue into adjacent memory.
In a typical stack-based function, the stack may contain:
Local variables, including the buffer.
Saved register or frame information.
A return address, which tells the program where to continue after the function finishes.
The precise layout depends on the compiler, architecture, and calling convention. If overflowing input reaches control information such as the return address, the attacker may replace it with a value of their choosing.
From a Crash to Control of Execution
If a buffer overflow fills the return address with invalid data, the program may crash when the function returns. A crash is a sign of memory corruption, but it is not the only possible outcome.
If an attacker can control the overwritten return address, they may redirect execution to a chosen location. The attacker may try to:
Jump to useful code already present in the program.
Redirect execution to code supplied as part of the input, if the system allows it to execute.
Arrange the surrounding stack data so the program continues in a useful way rather than crashing immediately.
Historically, attackers often tried to run injected code that launched a command shell; such injected code became known as shellcode. A successful exploit requires more than merely overwriting a return address: the attacker must account for the program’s subsequent behavior, including how values are used and where later returns will go.
Memory Layout and Stack Direction
Some systems arrange the stack so that it grows toward lower memory addresses; others may use different conventions. Reversing the direction does not, by itself, eliminate overflow risks. A buffer can still be adjacent to sensitive data or control information, and nested function calls can introduce additional return addresses and stack frames.
The important security property is not simply which direction the stack grows. It is whether untrusted input can exceed a buffer’s bounds and corrupt data that influences the program’s behavior.
Defenses and Their Limits
The primary fix is to prevent the overflow in the program itself:
Use input operations that enforce the destination’s capacity.
Check input lengths before copying or parsing data.
Avoid unsafe functions that cannot know the size of the destination buffer.
Review boundary cases, including the largest and smallest inputs.
Operating systems and hardware also provide defenses:
Non-executable memory: Data regions such as the stack can be marked as non-executable. This prevents an attacker from simply placing code in a buffer and jumping to it.
Code-reuse attacks: Non-executable memory does not prevent an attacker from redirecting execution to code that is already executable, such as existing library or program instructions. Return-to-library attacks are one example.
These defenses make exploitation harder but do not repair the underlying programming mistake. The most direct solution is to correct the code, while system-level defenses provide additional layers of protection.
Why Small Details Matter
In security, seemingly minor implementation details can determine whether a system’s policy is actually enforced. Examples include:
Forgetting to limit password guesses on one interface.
Failing to check that an account identifier belongs to the logged-in user.
Mishandling a random-number generator’s initialization.
Interpreting an encoded string differently from another component.
Writing beyond the end of a buffer.
A reliable way to evaluate a system is to examine its edge cases: unusually large or small inputs, repeated requests, malformed data, and values that different components might interpret differently. Security depends on how the entire system behaves, not merely on its ordinary cases.
Reducing the Trusted Computing Base
A system is difficult to secure if every component must behave perfectly for the policy to hold. A stronger design tries to make security depend on a small number of carefully protected components.
The trusted computing base (TCB) is the set of components that must be correct and trustworthy for the system’s security guarantees to hold. Reducing the TCB means arranging the system so that fewer components can violate the policy. Other parts of the system may still contain bugs, but those bugs should not automatically grant access to protected resources.
A smaller, well-defined TCB makes security easier to reason about and limits the consequences of failures elsewhere in the system.

Ask anything
We've read this whole study set, so questions about it get the best answers.