Start free trial
Trending New Genres Authors
EnglishEnglish
EspañolSpanish
简体中文Chinese
繁體中文Chinese (Traditional)
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
Searching...
SoBrief
Writing Secure Code

Writing Secure Code

Build software that withstands attacks, from early risk analysis to testing and recovery.
by Michael Howard 2001 768 pages
4.01
372 ratings
Listen
Immersive
V2.3
Amazon Kindle Audible
Try Full Access for 3 Days
Unlock listening & more!
Continue

Key Takeaways

Assume every connected feature will be probed by someone.

Exposure is normal. Howard and LeBlanc begin from a blunt premise: networked software will face hostile input, whether or not its makers expect attention. A Microsoft test server placed online on a Friday was discovered and attacked by Monday. In separate trials, internet-connected machines set up to observe attackers were often found within days. The attacker needs one weak entry point; the developer must account for all of them.

Security is product quality. A compromised application can expose private data, interrupt service, damage customer trust, and trigger expensive repairs. The book reports an estimate of about $100,000 for a single security bulletin and its patch, before counting customer disruption or reputational harm. The right level of protection depends on what the software does and what its users stand to lose.

Analysis

The book’s strongest opening move is to replace the comforting question, “Who would target us?” with an engineering assumption about exposure. That resembles safety engineering, where a design is tested against foreseeable failure rather than the operator’s optimism. The argument is especially persuasive for services that remain reachable around the clock. Still, not every product merits the same investment. A threat model should connect the possible harm to the protected data, users, and operating context, rather than treating security as an unlimited mandate.

Train the whole team before the first security bug arrives.

Skills must spread. During Microsoft’s Windows Security Push, about 8,500 employees received security training in ten days, including developers, testers, program managers, and senior leaders. The goal was not merely to recruit a few specialists. Everyone involved in building the product needed to recognize how ordinary features could become attack routes and how to prevent defects at their source.

Practice changes what reviewers see. In an experiment described by the authors, two programmers first found 10 and 16 flaws in a thousand lines of C code. After a one-hour security lesson, they found 45 and 41 additional flaws. Training was paired with peer review, bug-focused work, and follow-up on defects so that lessons could change daily habits, not just fill a classroom.

Analysis

This account challenges the assumption that security expertise can be outsourced to a small review team. Shared vocabulary lets designers, developers, and testers notice different failure modes in the same feature. The experiment is a vivid illustration, not a broad scientific proof: it involves two people and one code sample. Its durable lesson is organizational. Training is most useful when paired with routine review, clear ownership, and feedback that helps people avoid repeating the same class of mistake.

Map threats before selecting security technologies.

Model the system first. A threat model is a structured account of what a system contains, how data moves through it, what could go wrong, and which risks deserve attention. A data flow diagram can identify processes, data stores, users, and the boundaries between trusted and untrusted parts. The team then asks how an attacker might impersonate someone, alter or expose data, disrupt service, or gain greater authority. STRIDE names this six-category way of organizing threats.

Rank before building defenses. Threat trees break a broad attack into the steps an attacker would need to accomplish. DREAD is a scoring method that compares possible damage, ease of repetition and exploitation, scope of affected users, and likelihood of discovery. The authors report that their teams found about half of security bugs through threat analysis. For a payroll service, for example, tracing employee data across a network reveals where interception is possible before a team chooses encryption.

Analysis

The practical contribution is sequencing: understand the system and its threats before choosing a fashionable control. This also makes security a design activity, rather than a layer of technology applied after decisions are fixed. Risk scores help teams compare work, but they can create false precision, especially when likelihood is hard to estimate. STRIDE and DREAD are best treated as prompts for disciplined discussion. Their value lies in surfacing overlooked paths, not in making subjective judgments look mathematically certain.

Turn off what users do not need, and shrink privileges.

Reduce what is exposed. The book’s SD3 model groups good practice into three aims: shape security into the design, choose cautious initial settings, and make the product manageable after installation. Secure defaults mean installing only commonly needed capabilities and leaving the rest off until someone deliberately enables them. The authors use an 80/20 heuristic: keep the small set of features most users need by default, and make the rest easy to add.

Limit the damage. Least privilege means a process receives only the permissions needed for its task. If an attacker takes over a service running as SYSTEM, the compromise can reach far beyond the service’s job. The book points to services and web code that once ran with excessive authority. Separating privileged administration from routine work can confine a successful attack instead of handing it the whole machine.

Analysis

Secure defaults and least privilege work together: one reduces the number of doors, the other limits what a break-in can reach. This is a form of containment familiar from safety design, where systems are built to prevent one failure from cascading. The difficult part is usability. A feature that is off by default can frustrate users or break dependent software, so the setting must be understandable and straightforward to change. A safe default is strongest when it reduces exposure without turning routine setup into a puzzle.

Validate input at one controlled boundary, not wherever convenient.

Trust begins at the boundary. A trust boundary separates data controlled by the application from data supplied by users, files, clients, or other systems. An input chokepoint is the designated route through which a source’s data must pass before entering trusted processing. This makes validation consistent and gives reviewers a clear place to inspect assumptions. A client-side check is not enough: an attacker can bypass the client and send a request directly to the server.

Accept what is valid. A database query assembled by joining user text into SQL can be changed by crafted input, potentially exposing or modifying records. Parameterized queries keep data separate from query instructions, while a database account with limited permissions reduces the consequences of a mistake. For web pages, validate what input is allowed and encode data before displaying it, since ordinary text can otherwise be interpreted as script.

Analysis

A single, visible validation boundary makes an abstract rule operational. It also reflects a useful principle from systems design: responsibility should be assigned at interfaces, where assumptions cross from one component to another. The boundary does not eliminate the need for context-specific safeguards. A string safe for a database may not be safe for HTML, and syntactically valid input may still violate business rules. Validation, output encoding, and authorization answer different questions and should not be mistaken for interchangeable protections.

Never authorize by a name until every representation is resolved.

Names can deceive. Canonicalization is the process of converting equivalent representations into a standard form. Security checks based on an unprocessed filename or URL can disagree with the component that eventually opens it. Windows long filenames can have short 8.3 aliases; an encoded URL can conceal directory traversal characters; and an IIS flaw once allowed a request for an alternate data stream to reveal source code instead of processed output.

Prefer the resource itself. The safest approach is to use operating-system access controls rather than deciding permissions from a filename. When a name must be checked, define a narrow set of valid forms, normalize it using the relevant system component, and reject anything outside the policy. The book’s example of a supposedly protected directory being accessed through a different capitalization shows how one component’s comparison rules can diverge from the file system’s.

Analysis

Canonicalization failures are really coordination failures: two layers interpret the same string differently, while the security decision is made between those interpretations. The same pattern appears whenever data is decoded, normalized, or rewritten in transit. A useful design question is therefore not simply whether input was checked, but whether it was checked in the same representation the resource handler will use. Strict allowlists reduce ambiguity, though they may reject legitimate names, particularly in international or legacy environments.

Bound every buffer, and treat compiler defenses as backup.

Memory errors become control errors. In C and C++, copying unchecked input past a buffer can overwrite nearby data and redirect execution. The book demonstrates that stack overflows are not the only danger: heap corruption, off-by-one writes, unchecked array indexes, format-string mistakes, and Unicode-versus-byte size confusion can also alter program behavior. Safer string functions help only when their limits and return values are used correctly. A character count is not always a byte count.

Complexity can be attacked too. A function that repeatedly shifts a string while removing duplicate characters took about 36 minutes to process a one-million-character input on the authors’ test machine; a linear-time approach took about 20 milliseconds. The Visual C++ /GS option can catch some stack overwrites, but it does not prevent heap attacks or every pointer error. It is a backup, not a substitute for bounds checks and testing.

Analysis

This chapter connects memory safety to both correctness and computational complexity. A function can avoid corrupting memory yet still be exploitable through disproportionate CPU or resource use. Modern memory-safe languages can remove many classes of low-level errors, but they do not automatically solve authorization, parsing, denial of service, or unsafe native boundaries. The book’s advice remains valuable even where its APIs are obsolete: measure lengths carefully, check failures, simplify complex routines, and never interpret a compiler mitigation as proof of safety.

Use proven cryptography, and keep secrets scarce and short-lived.

Encryption is not a cure-all. Cryptography can protect confidentiality, authenticate identities, and detect tampering, but it cannot repair a buffer overflow or a badly designed permission system. The authors warn against home-built algorithms and predictable random-number generators such as common implementations of rand. Use established operating-system or framework services for randomness and cryptographic operations, and pair encryption with a message authentication code or signature when tampering matters.

Protect the key, not just the data. A key embedded in an executable can be recovered, and a secret passed through many functions is exposed to more code. Prefer not to store a secret at all when a verifier will do. Where storage is necessary, Windows’ Data Protection API can protect data for a user or machine, subject to appropriate access controls. Keep plaintext in memory only as long as needed, then clear it using a method the compiler will not optimize away.

Analysis

The chapter’s central correction is to move attention from algorithm branding to the entire key lifecycle. Strong encryption provides little protection if a key is hard-coded, reused carelessly, or exposed to processes with broad access. This systems view is more useful than treating cryptography as a single feature checkbox. There is also a practical limit: software cannot fully protect secrets from an administrator or malicious code running with the same user’s authority. The design goal is to reduce exposure and match protection to the threat.

Test like an attacker, then fix the whole class of bug.

Exercise every interface. Security testing checks whether defenses withstand misuse, not merely whether features work normally. Start with the threat model, identify interfaces and the data they receive, then vary that data: make it malformed, oversized, missing, duplicated, out of order, or valid with a malicious addition. Test under ordinary user privileges as well as administrative ones. A service that crashes on hostile input can deny service, even if no data is stolen.

Turn discoveries into prevention. When a flaw appears, look for related defects, add regression tests, and identify the underlying assumption that failed. The authors describe a product team that spent four hours tracing a recurring bug pattern, then found and fixed four more instances in under twenty person-hours. The original programmer should participate in the repair, so the team learns instead of simply transferring the bug to someone else.

Analysis

Adversarial testing is strongest when it is systematic rather than theatrical. Random fuzzing can expose crashes, while carefully structured mutations reach deeper code paths that basic invalid input never exercises. Neither approach proves the absence of flaws, so results need to feed code review, design changes, and regression suites. The book also treats testing as part of an ongoing response system: vulnerabilities will still emerge after release, and the quality of triage, fixes, and customer communication shapes the real security outcome.

Make privacy visible, minimize collection, and explain real risks.

Privacy is a product obligation. The book’s Safe Harbor discussion organizes responsible data handling around notice, user choice, limits on sharing, access, security, data accuracy, and enforcement. Applications should collect only information needed for a stated purpose, let people review or correct it, and protect it from both unauthorized access and improper alteration. Privacy is related to security, but it also governs what authorized people do with information.

Make choices understandable. A privacy policy should explain what data is collected, why, how long it is kept, and with whom it is shared. The book describes P3P as a machine-readable way for websites to communicate privacy practices. Documentation and error messages matter too: users need clear consequences and workable guidance, not jargon or a vague warning. A secure default should not depend on users discovering a crucial instruction in a manual.

Analysis

Privacy adds a governance question that access control alone cannot answer: even if a person is authorized to see data, should that person collect or use it for this purpose? Data minimization reduces both exposure and the burden of managing consent, retention, and deletion. Clear notices help, but disclosure is not a substitute for restraint. The chapter’s emphasis on understandable choices is also a human-factors insight: a policy that users cannot interpret may satisfy a process while failing to support meaningful control.

Analysis

Writing Secure Code is a practical engineering manual organized around one premise: connected software must be designed for adversarial use, not merely checked for ordinary correctness. Its broadest contribution is a chain of responsibility. Teams learn the risks, model data flows and trust boundaries, choose proportionate controls, implement them with defensive coding, test hostile cases, and maintain a response process after release. The stories make that chain concrete, from an unannounced server attacked within a weekend to programmers finding many more defects after a short security lesson.

The book is strongest when it turns security from specialist folklore into repeatable work. Threat modeling links design to testing; secure defaults reduce dependence on administrators; least privilege limits the damage of inevitable flaws; and postmortems turn incidents into institutional learning. Its insistence that features unrelated to security can still contain security defects is especially important. A payroll service, a file utility, or a game can all become an attack route simply because they accept input or run with authority.

Its scoring systems and checklists are useful prompts, not guarantees. DREAD ratings can make subjective judgments seem more exact than they are, while attack-surface counts do not measure code quality or the likelihood of a particular exploit. Their real value is comparative: they help teams ask what changed, what remains exposed, and what deserves review first. Likewise, security cannot be reduced to more checks. Excessive warnings, burdensome defaults, and impractical controls can push users toward insecure workarounds.

The second edition is rooted in early-2000s Microsoft platforms, and many named APIs, operating-system behaviors, and implementation details are historically specific. Readers should not treat every code sample as current implementation guidance. The durable value lies in its reasoning: distrust external data, minimize authority and exposure, use established security mechanisms, test assumptions, and design for recovery. In that sense, it is less a catalog of timeless APIs than a disciplined method for making software harder to misuse and easier to defend.

Summary in 30 Seconds
Connected software needs security built into design, coding, testing, and maintenance. Threat analysis helps teams prioritize defenses, and the authors report it uncovered about half of their security bugs. After a one-hour lesson, two programmers found 45 and 41 additional flaws in a thousand lines of C. Restricting features and permissions limits damage; bounded inputs, established cryptography, and attacker-focused tests reduce common weaknesses. One inefficient routine took 36 minutes on a million characters, while a linear approach took about 20 milliseconds.
Contains spoilers

Last updated:

Report Issue

Review Summary

4.01 out of 5
Average of 372 ratings from Goodreads and Amazon.

Writing Secure Code receives mixed reviews, with an average rating of 4.01/5. Readers appreciate its coverage of security principles and threat modeling but criticize its focus on Windows and C programming. Many find the content dated, especially for modern languages and platforms. Some praise its real-world examples and general security practices, while others note its limited applicability beyond Windows development. The book is seen as a good starting point for learning about security vulnerabilities, though its relevance has diminished since its 2001 publication.

Your rating:
4.44
136 ratings
Want to read the full book?

Glossary

SD3

Three security design aims

A development model that asks teams to build security into the design, ship with cautious default settings, and support secure operation after deployment. The three aims address different stages: architecture, initial exposure, and ongoing administration. Together they discourage treating security as a late patch or a one-time code review.

STRIDE

Threat-category checklist

A framework for examining six broad threat classes: identity impersonation, data alteration, denial of actions, information exposure, service disruption, and privilege escalation. Teams apply the categories to processes, data stores, users, and data flows in a system model. STRIDE helps make threat discovery systematic, though it does not itself rank or mitigate risks.

DREAD

Threat ranking method

A risk-scoring method that considers the potential damage, reproducibility, exploitability, affected users, and discoverability of a threat. Teams assign ratings and combine them to prioritize investigation and mitigation. The method is useful for comparing issues consistently, but its scores rely on judgment and should not be mistaken for precise probabilities.

Threat model

Structured attack analysis

A documented analysis of a system’s components, data flows, trust boundaries, assets, possible attacks, and defenses. It helps a team identify which risks matter most and connect them to design choices and test plans. A threat model should evolve as the product, deployment environment, and understanding of attacks change.

Trust boundary

Trusted and untrusted divide

A point in an application architecture where data or control passes between components with different levels of trust. Data crossing from a user, network, file, or external service into trusted processing should be treated as untrusted until checked. Making these boundaries explicit helps developers locate validation and authorization responsibilities.

Relative attack surface quotient (RASQ)

Weighted exposure count

A comparative measure created in the book to estimate an application’s exposure by counting attack vectors and applying a severity weight to each. Examples include open sockets, privileged services, weak permissions, and enabled features. RASQ can help compare versions of the same product, but it does not measure code quality or establish absolute security.

Data Protection API (DPAPI)

Operating-system data protection

Windows functions that encrypt and authenticate data so an application can store sensitive information without implementing its own key-management scheme. Protection can be associated with a user or, with a machine-level option, the computer. DPAPI raises the difficulty of unauthorized access, but stored data still requires appropriate access controls and does not protect against code already running with the user’s authority.

Input chokepoint

Controlled validation entry

A designated route through which data from a particular source must pass before it enters trusted application logic. Validation at this point reduces inconsistent checks scattered across code and gives reviewers a clear place to inspect how assumptions are established. Separate sources may need separate chokepoints, such as one for network input and another for configuration files.

FAQ

What's Writing Secure Code about?

  • Focus on Security: Writing Secure Code by Michael Howard emphasizes the importance of secure software development practices to prevent vulnerabilities.
  • Comprehensive Guidance: It covers a wide range of topics, including secure coding techniques, threat modeling, and access control mechanisms.
  • Real-World Examples: The book provides practical advice and real-world examples, particularly from Microsoft's security initiatives, to illustrate key concepts.

Why should I read Writing Secure Code?

  • Enhance Security Knowledge: The book fills the gap in traditional programming education by focusing on secure coding practices.
  • Practical Insights: It offers practical advice and techniques that can be directly applied to real-world software development.
  • Prevent Costly Mistakes: By understanding the principles outlined, you can avoid common pitfalls that lead to security vulnerabilities.

What are the key takeaways of Writing Secure Code?

  • Security is Everyone's Responsibility: Security should be a priority for all team members, not just those in specialized roles.
  • Proactive Security Development: The book advocates for a proactive approach, including threat modeling and secure coding practices.
  • Continuous Learning: Ongoing education and awareness are crucial as the landscape of software security is constantly evolving.

What are the best quotes from Writing Secure Code and what do they mean?

  • "Security is a top priority": This quote emphasizes integrating security into every aspect of software design and implementation.
  • "You cannot build a secure system until you understand your threats": It highlights the importance of threat modeling in the software development lifecycle.
  • "Don't fix only those bugs that you think are exploitable": This advocates for addressing all vulnerabilities, regardless of perceived severity.

How does Writing Secure Code define security testing?

  • Verification Process: Security testing verifies that an application can withstand attacks and that its security mechanisms function correctly.
  • Focus on Vulnerabilities: Unlike functional testing, it aims to demonstrate that vulnerabilities cannot be exploited.
  • Techniques and Methodologies: The book outlines various techniques, including threat modeling and data mutation, for effective security testing.

What is threat modeling in Writing Secure Code and why is it important?

  • Structured Security Analysis: Threat modeling helps identify potential security threats by analyzing an application's architecture and data flows.
  • Prioritizing Risks: It allows developers to prioritize security risks and determine which threats require mitigation.
  • Improving Understanding: The process enhances the team's understanding of the application, leading to better design decisions and fewer security flaws.

What are some common security vulnerabilities discussed in Writing Secure Code?

  • Buffer Overruns: These occur when data exceeds the allocated buffer size, potentially leading to arbitrary code execution.
  • SQL Injection: The book explains how attackers can manipulate SQL queries by injecting malicious input.
  • Cross-Site Scripting (XSS): It discusses how XSS attacks can occur when user input is not properly sanitized.

How does Writing Secure Code suggest preventing SQL injection?

  • Use Parameterized Queries: The book strongly recommends using parameterized queries instead of string concatenation to construct SQL statements.
  • Validate User Input: It emphasizes the importance of validating and sanitizing user input before processing it.
  • Limit Database Permissions: Limiting database permissions for application accounts reduces the potential impact of a successful SQL injection attack.

What is the significance of canonicalization in security according to Writing Secure Code?

  • Understanding Canonicalization: Canonicalization refers to converting data into a standard format to prevent security vulnerabilities.
  • Preventing Ambiguities: Improper canonicalization can lead to unexpected behaviors and vulnerabilities, such as path traversal attacks.
  • Strict Validation: The book advises implementing strict validation and normalization processes to ensure data is consistently interpreted securely.

How does Writing Secure Code address cross-site scripting (XSS)?

  • Input Sanitization: The book emphasizes the need for thorough input sanitization to prevent XSS attacks.
  • Output Encoding: It recommends encoding output data to prevent the execution of malicious scripts.
  • Security Testing: Regular security testing is encouraged to identify and remediate XSS vulnerabilities.

How does Writing Secure Code suggest handling sensitive data?

  • Use Encryption: The book recommends encrypting sensitive data both at rest and in transit to protect it from unauthorized access.
  • Limit Data Exposure: Developers should minimize the amount of sensitive data stored and shared.
  • Implement Access Controls: Proper access controls should be enforced to restrict who can view or modify sensitive data.

How can I apply the principles from Writing Secure Code in my development process?

  • Integrate Security into the SDLC: Make security a fundamental part of your software development lifecycle.
  • Conduct Regular Security Training: Ensure all team members are educated about security best practices and common vulnerabilities.
  • Implement Rigorous Testing: Adopt comprehensive testing methodologies, including security testing and threat modeling, to identify and address vulnerabilities.

About the Author

Michael Howard is a software security expert associated with Microsoft. He is known for his work in the field of secure coding practices and has authored multiple books on the subject. Howard's expertise lies primarily in Windows application security, as evident from the content of "Writing Secure Code." His background at Microsoft has influenced his approach to security, focusing on Windows-specific issues and C/C++ programming. Despite some criticism of the book's dated content, Howard's contributions to the field of software security are widely recognized. His work has helped shape security practices in Windows development and continues to be referenced in discussions about secure coding principles.

Download PDF

To save this Writing Secure Code summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.44 MB     Pages: 20

Download EPUB

To read this Writing Secure Code summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 1.46 MB     Pages: 25
Want to read the full book?
Follow
Listen
Home
Swipe
Library
Get App
Try Full Access for 3 Days
Listen, bookmark, and more
Compare Features Free Pro
📖 Read Summaries
Read unlimited summaries. Free users get 3 per month
🎧 Listen to Summaries
Listen to unlimited summaries in 40 languages
—
❤️ Unlimited Bookmarks
Free users are limited to 4
—
📜 Unlimited History
Free users are limited to 4
—
📥 Unlimited Downloads
Free users are limited to 1
—
Risk-Free Timeline
Today: Get Instant Access
Listen to full summaries of 26,000+ books. That's 12,000+ hours of audio!
Day 2: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 3: Your subscription begins
You'll be charged on Nov 24,
cancel anytime before.
Consume 2.8× More Books
2.8× more books Listening Reading
Our users love us
1M+ readers
Trustpilot Rating
TrustPilot
4.6 Excellent
This site is a total game-changer. I've been flying through book summaries like never before. Highly, highly recommend.
— Dave G
Worth my money and time, and really well made. I've never seen this quality of summaries on other websites. Very helpful!
— Em
Highly recommended!! Fantastic service. Perfect for those that want a little more than a teaser but not all the intricate details of a full audio book.
— Greg M
Save 62%
Yearly
$119.88 $44.99/year/yr
$3.75/mo
Monthly
$9.99/mo
Start a 3-Day Free Trial
3 days free, then $44.99/year. Cancel anytime.
Unlock a world of fiction & nonfiction books
26,000+ books for the price of 2 books
Read any book in 10 minutes
Discover new books like Tinder
Request any book if it's not summarized
Read more books than anyone you know
#1 app for book lovers
Lifelike & immersive summaries
30-day money-back guarantee
Download summaries in EPUBs or PDFs
Cancel anytime in a few clicks

Why one summary?

Scanner
Find a barcode to scan

⭐
⭐
⭐
We have a special gift for you
Open
38% off
DISCOUNT FOR YOU
⭐
⭐
⭐
$79.99
$49.99/year
Only $4.16 per month
Continue
2 taps to start, super easy to cancel
Settings
General
Widget
Loading...