Writing Secure Code

Book description

Keep black-hat hackers at bay with the tips and techniques in this entertaining, eye-opening book! Developers will learn how to padlock their applications throughout the entire development process—from designing secure applications to writing robust code that can withstand repeated attacks to testing applications for security flaws. Easily digested chapters reveal proven principles, strategies, and coding techniques. The authors—two battle-scarred veterans who have solved some of the industry’s toughest security problems—provide sample code in several languages. This edition includes updated information about threat modeling, designing a security process, international issues, file-system issues, adding privacy to applications, and performing security code reviews. It also includes enhanced coverage of buffer overruns, Microsoft .NET security, and Microsoft ActiveX development, plus practical checklists for developers, testers, and program managers.

Table of contents

  1. Table of Contents
  2. Dedication
  3. Introduction
    1. Who Should Read This Book
    2. Organization of This Book
    3. Installing and Using the Sample Files
    4. System Requirements
    5. Support Information
    6. Acknowledgments
  4. I. Contemporary Security
    1. 1. The Need for Secure Systems
      1. Applications on the Wild Wild Web
      2. The Need for Trustworthy Computing
      3. Getting Everyone’s Head in the Game
        1. Using Tact to Sell Security to the Organization
          1. Secure Products Are Quality Products
          2. The Media (and Your Competition) Leap on Security Issues
          3. People Shy Away from Products That Don’t Work As Advertised
          4. Don’t Be a Victim
          5. Security Vulnerabilities Are Expensive to Fix
        2. Using Subversion
      4. Some Ideas for Instilling a Security Culture
        1. Get the Boss to Send an E-Mail
        2. Nominate a Security Evangelist
          1. Stay Abreast of Security Issues
          2. Interviewing Security People
          3. Provide Ongoing Security Education
          4. Provide Bug Triaging
      5. The Attacker’s Advantage and the Defender’s Dilemma
        1. Principle #1: The defender must defend all points; the attacker can choose the weakest point.
        2. Principle #2: The defender can defend only against known attacks; the attacker can probe for unknown vulnerabilities.
        3. Principle #3: The defender must be constantly vigilant; the attacker can strike at will.
        4. Principle #4: The defender must play by the rules; the attacker can play dirty.
      6. Summary
    2. 2. The Proactive Security Development Process
      1. Process Improvements
      2. The Role of Education
        1. Resistance to Mandatory Training
        2. Ongoing Training
        3. Advancing the Science of Security
        4. Education Proves the More Eyes Fallacy
        5. Now the Evidence!
      3. Design Phase
        1. Security Questions During Interviews
        2. Define the Product Security Goals
        3. Security Is a Product Feature
        4. Making Time for Security
        5. Threat Modeling Leads to Secure Design
        6. Build End-of-Life Plans for Insecure Features
        7. Setting the Bug Bar
        8. Security Team Review
      4. Development Phase
        1. Be Hardcore About Who Can Check In New Code (Check-Ins Checked)
        2. Security Peer Review of New Code (Check-Ins Checked)
        3. Define Secure Coding Guidelines
        4. Review Old Defects
        5. External Security Review
        6. Security Push
        7. Be Mindful of Your Bug Counts
        8. Keep Track of Bug Metrics
        9. No Surprises and No Easter Eggs!
      5. Test Phase
      6. Shipping and Maintenance Phases
        1. How Do You Know When You’re Done?
        2. Response Process
        3. Accountability
      7. Summary
    3. 3. Security Principles to Live By
      1. SD3: Secure by Design, by Default, and in Deployment
        1. Secure by Design
        2. Secure by Default
        3. Secure in Deployment
      2. Security Principles
        1. Learn from Mistakes
        2. Minimize Your Attack Surface
        3. Employ Secure Defaults
        4. Use Defense in Depth
        5. Use Least Privilege
          1. Separation of Privilege
        6. Backward Compatibility Will Always Give You Grief
        7. Assume External Systems Are Insecure
        8. Plan on Failure
        9. Fail to a Secure Mode
        10. Remember That Security Features != Secure Features
        11. Never Depend on Security Through Obscurity Alone
        12. Don’t Mix Code and Data
        13. Fix Security Issues Correctly
      3. Summary
    4. 4. Threat Modeling
      1. Secure Design Through Threat Modeling
        1. Assemble the Threat-Modeling Team
        2. Decompose the Application
          1. Formally Decomposing the Application
        3. Determine the Threats to the System
          1. Using STRIDE to Categorize Threats
          2. Threat Trees
            1. Small enhancements to make threat trees more readable
          3. Items to Note While Threat Modeling
        4. Rank the Threats by Decreasing Risk
          1. Using DREAD to Calculate Risk
          2. Bringing It All Together: Decomposition, Threat Trees, STRIDE, and DREAD
          3. Bubbling Up the Overall Risk
          4. Going Over the Threat-Modeling Process One More Time
        5. Choose How to Respond to the Threats
          1. Option One: Do Nothing
          2. Option Two: Warn the User
          3. Option Three: Remove the Problem
          4. Option Four: Fix the Problem
        6. Choose Techniques to Mitigate the Threats
      2. Security Techniques
        1. Authentication
          1. Basic Authentication
          2. Digest Authentication
          3. Forms-Based Authentication
          4. Microsoft Passport
          5. Windows Authentication
            1. NTLM authentication
            2. Kerberos v5 authentication
          6. X.509 Certificate Authentication
          7. IPSec
          8. RADIUS
        2. Authorization
          1. Access Control Lists
          2. Privileges
          3. IP Restrictions
          4. Server-Specific Permissions
        3. Tamper-Resistant and Privacy-Enhanced Technologies
          1. SSL/TLS
          2. IPSec
          3. DCOM and RPCs
          4. Encrypting File System
        4. Protect Secrets, or Better Yet, Don’t Store Secrets
        5. Encryption, Hashes, MACs, and Digital Signatures
        6. Auditing
        7. Filtering, Throttling, and Quality of Service
        8. Least Privilege
      3. Mitigating the Sample Payroll Application Threats
      4. A Cornucopia of Threats and Solutions
      5. Summary
  5. II. Secure Coding Techniques
    1. 5. Public Enemy #1: The Buffer Overrun
      1. Stack Overruns
      2. Heap Overruns
      3. Array Indexing Errors
      4. Format String Bugs
      5. Unicode and ANSI Buffer Size Mismatches
        1. A Real Unicode Bug Example
      6. Preventing Buffer Overruns
        1. Safe String Handling
          1. strcpy
          2. strncpy
          3. sprintf
          4. _snprintf
          5. Standard Template Library Strings
          6. gets and fgets
          7. Using Strsafe.h
        2. A Word of Caution About String-Handling Functions
      7. The Visual C++ .NET /GS Option
      8. Summary
    2. 6. Determining Appropriate Access Control
      1. Why ACLs Are Important
        1. A Diversion: Fixing the Registry Code
      2. What Makes Up an ACL?
      3. A Method of Choosing Good ACLs
        1. Effective Deny ACEs
      4. Creating ACLs
        1. Creating ACLs in Windows NT 4
        2. Creating ACLs in Windows 2000
        3. Creating ACLs with Active Template Library
      5. Getting the ACE Order Right
      6. Be Wary of the Terminal Server and Remote Desktop SIDs
      7. NULL DACLs and Other Dangerous ACE Types
        1. NULL DACLs and Auditing
        2. Dangerous ACE Types
          1. Everyone (WRITE_DAC)
          2. Everyone (WRITE_OWNER)
          3. Everyone (FILE_ADD_FILE)
          4. Everyone (DELETE)
          5. Everyone (FILE_DELETE_CHILD)
          6. Everyone (GENERIC_ALL)
        3. What If I Can’t Change the NULL DACL?
      8. Other Access Control Mechanisms
        1. .NET Framework Roles
        2. COM+ Roles
        3. IP Restrictions
        4. SQL Server Triggers and Permissions
        5. A Medical Example
        6. An Important Note About Access Control Mechanisms
      9. Summary
    3. 7. Running with Least Privilege
      1. Least Privilege in the Real World
        1. Viruses and Trojans
          1. Back Orifice
          2. SubSeven
          3. FunLove Virus
          4. ILoveYou Virus
        2. Web Server Defacements
      2. Brief Overview of Access Control
      3. Brief Overview of Privileges
        1. SeBackupPrivilege Issues
        2. SeRestorePrivilege Issues
        3. SeDebugPrivilege Issues
        4. SeTcbPrivilege Issues
        5. SeAssignPrimaryTokenPrivilege and SeIncreaseQuotaPrivilege Issues
        6. SeLoadDriverPrivilege Issues
        7. SeRemoteShutdownPrivilege Issues
        8. SeTakeOwnershipPrivilege Issues
      4. Brief Overview of Tokens
      5. How Tokens, Privileges, SIDs, ACLs, and Processes Relate
        1. SIDs and Access Checks, Privileges and Privilege Checks
      6. Three Reasons Applications Require Elevated Privileges
        1. ACL Issues
          1. Opening Resources for GENERIC_ALL
        2. Privilege Issue
        3. Using LSA Secrets
      7. Solving the Elevated Privileges Issue
        1. Solving ACL Issues
        2. Solving Privilege Issues
        3. Solving LSA Issues
      8. A Process for Determining Appropriate Privilege
        1. Step 1: Find Resources Used by the Application
        2. Step 2: Find Privileged APIs Used by the Application
        3. Step 3: Which Account Is Required?
        4. Step 4: Get the Token Contents
        5. Step 5: Are All the SIDs and Privileges Required?
        6. Step 6: Adjust the Token
          1. Allow Less-Privileged Accounts to Run Your Application
          2. Use Restricted Tokens
            1. Removing privileges
            2. Specifying restricting SIDs
            3. Applying a deny-only attribute to SIDs
          3. When to Use Restricted Tokens
          4. Restricted Token Sample Code
          5. Software Restriction Policies and Windows XP
          6. Permanently Removing Unneeded Privileges
      9. Low-Privilege Service Accounts in Windows XP and Windows .NET Server 2003
      10. The Impersonate Privilege and Windows .NET Server 2003
      11. Debugging Least-Privilege Issues
        1. Why Applications Fail as a Normal User
        2. How to Determine Why Applications Fail
          1. The Windows Event Viewer
          2. RegMon and FileMon
      12. Summary
    4. 8. Cryptographic Foibles
      1. Using Poor Random Numbers
        1. The Problem: rand
        2. Cryptographically Random Numbers in Win32
        3. Cryptographically Random Numbers in Managed Code
        4. Cryptographically Random Numbers in Web Pages
      2. Using Passwords to Derive Cryptographic Keys
        1. Measuring the Effective Bit Size of a Password
      3. Key Management Issues
        1. Long-Term and Short-Term Keys
        2. Use Appropriate Key Lengths to Protect Data
        3. Keep Keys Close to the Source
          1. The CryptGenKey and CryptExportKey Functions
      4. Key Exchange Issues
      5. Creating Your Own Cryptographic Functions
      6. Using the Same Stream-Cipher Encryption Key
        1. Why People Use Stream Ciphers
        2. The Pitfalls of Stream Ciphers
        3. What If You Must Use the Same Key?
      7. Bit-Flipping Attacks Against Stream Ciphers
        1. Solving Bit-Flipping Attacks
        2. When to Use a Hash, Keyed Hash, or Digital Signature
          1. Creating a Keyed Hash
            1. Forgetting to use a key
            2. Using the same key to encrypt data and key-hash data
            3. Basing K2 on K1
          2. Creating a Keyed Hash
          3. Creating a Digital Signature
      8. Reusing a Buffer for Plaintext and Ciphertext
      9. Using Crypto to Mitigate Threats
      10. Document Your Use of Cryptography
      11. Summary
    5. 9. Protecting Secret Data
      1. Attacking Secret Data
      2. Sometimes You Don’t Need to Store a Secret
        1. Creating a Salted Hash
        2. Using PKCS #5 to Make the Attacker’s Job Harder
      3. Getting the Secret from the User
      4. Protecting Secrets in Windows 2000 and Later
        1. A Special Case: Client Credentials in Windows XP
      5. Protecting Secrets in Windows NT 4
      6. Protecting Secrets in Windows 95, Windows 98, Windows Me, and Windows CE
        1. Getting Device Details Using PnP
      7. Not Opting for a Least Common Denominator Solution
      8. Managing Secrets in Memory
        1. A Compiler Optimization Caveat
        2. Encrypting Secret Data in Memory
      9. Locking Memory to Prevent Paging Sensitive Data
      10. Protecting Secret Data in Managed Code
        1. Managing Secrets in Memory in Managed Code
      11. Raising the Security Bar
        1. Storing the Data in a File on a FAT File System
        2. Using an Embedded Key and XOR to Encode the Data
        3. Using an Embedded Key and 3DES to Encrypt the Data
        4. Using 3DES to Encrypt the Data and Storing a Password in the Registry
        5. Using 3DES to Encrypt the Data and Storing a Strong Key in the Registry
        6. Using 3DES to Encrypt the Data, Storing a Strong Key in the Registry, and ACLing the File and the Registry Key
        7. Using 3DES to Encrypt the Data, Storing a Strong Key in the Registry, Requiring the User to Enter a Password, and ACLing the File and the Registry Key
      12. Trade-Offs When Protecting Secret Data
      13. Summary
    6. 10. All Input Is Evil!
      1. The Issue
      2. Misplaced Trust
      3. A Strategy for Defending Against Input Attacks
      4. How to Check Validity
        1. Tainted Variables in Perl
      5. Using Regular Expressions for Checking Input
        1. Be Careful of What You Find—Did You Mean to Validate?
      6. Regular Expressions and Unicode
      7. A Regular Expression Rosetta Stone
        1. Regular Expressions in Perl
        2. Regular Expressions in Managed Code
          1. C# Example
          2. Visual Basic .NET Example
          3. Managed C++ Example
        3. Regular Expressions in Script
        4. Regular Expressions in C++
      8. A Best Practice That Does Not Use Regular Expressions
      9. Summary
    7. 11. Canonical Representation Issues
      1. What Does Canonical Mean, and Why Is It a Problem?
      2. Canonical Filename Issues
        1. Bypassing Napster Name Filtering
        2. Vulnerability in Apple Mac OS X and Apache
        3. DOS Device Names Vulnerability
        4. Sun Microsystems StarOffice /tmp Directory Symbolic-Link Vulnerability
        5. Common Windows Canonical Filename Mistakes
          1. 8.3 Representation of Long Filenames
          2. NTFS Alternate Data Streams
          3. Trailing Characters
          4. \\?\ Format
          5. Directory Traversal and Using Parent Paths (..)
            1. Walking out of the current directory
            2. Will the real filename please stand up?
          6. Absolute vs. Relative Filenames
          7. Case-Insensitive Filenames
          8. UNC Shares
          9. When Is a File Not a File? Mailslots and Named Pipes
          10. When Is a File Not a File? Device Names and Reserved Names
      3. Canonical Web-Based Issues
        1. Bypassing AOL Parental Controls
        2. Bypassing eEye’s Security Checks
        3. Zones and the Internet Explorer 4 “Dotless-IP Address” Bug
        4. Internet Information Server 4.0 ::$DATA Vulnerability
        5. When is a Line Really Two Lines?
        6. Yet Another Web Issue—Escaping
          1. 7-Bit and 8-Bit ASCII
          2. Hexadecimal Escape Codes
          3. UTF-8 Variable-Width Encoding
          4. How UTF-8 Encodes Data
          5. UCS-2 Unicode Encoding
          6. Double Encoding
          7. HTML Escape Codes
      4. Visual Equivalence Attacks and the Homograph Attack
      5. Preventing Canonicalization Mistakes
        1. Don’t Make Decisions Based on Names
        2. Use a Regular Expression to Restrict What’s Allowed in a Name
        3. Stopping 8.3 Filename Generation
        4. Don’t Trust the PATH—Use Full Path Names
        5. Attempt to Canonicalize the Name
        6. Calling CreateFile Safely
      6. Web-Based Canonicalization Remedies
        1. Restrict What Is Valid Input
        2. Be Careful When Dealing with UTF-8
        3. ISAPIs—Between a Rock and a Hard Place
      7. A Final Thought: Non-File-Based Canonicalization Issues
        1. Server Names
        2. Usernames
      8. Summary
    8. 12. Database Input Issues
      1. The Issue
      2. Pseudoremedy #1: Quoting the Input
      3. Pseudoremedy #2: Use Stored Procedures
      4. Remedy #1: Never Ever Connect as sysadmin
      5. Remedy #2: Building SQL Statements Securely
        1. Building SQL Stored Procedures Securely
      6. An In-Depth Defense in Depth Example
      7. Summary
    9. 13. Web-Specific Input Issues
      1. Cross-Site Scripting: When Output Turns Bad
        1. Sometimes the Attacker Doesn’t Need a <SCRIPT> Block
        2. The Attacker Doesn’t Need the User to Click a Link!
      2. Other XSS-Related Attacks
        1. XSS Attacks Against Local Files
          1. HTML Help Files
        2. XSS Attacks Against HTML Resources
      3. XSS Remedies
        1. Encoding Output
        2. Adding Double Quotes Around All Tag Properties
        3. Inserting Data in the innerText Property
        4. Forcing the Codepage
        5. The Internet Explorer 6.0 SP1 HttpOnly Cookie Option
        6. Internet Explorer “Mark of the Web”
        7. Internet Explorer <FRAME SECURITY> Attribute
        8. ASP.NET 1.1 ValidateRequest configuration option
      4. Don’t Look for Insecure Constructs
      5. But I Want Users to Post HTML to My Web Site!
      6. How to Review Code for XSS Bugs
      7. Other Web-Based Security Topics
        1. eval() Can Be Bad
        2. HTTP Trust Issues
          1. REFERER Errors
        3. ISAPI Applications and Filters
          1. Sensitive Data in Cookies and Fields
        4. Be Wary of “Predictable Cookies”
        5. SSL/TLS Client Issues
      8. Summary
    10. 14. Internationalization Issues
      1. The Golden I18N Security Rules
      2. Use Unicode in Your Application
      3. Prevent I18N Buffer Overruns
        1. Words and Bytes
      4. Validate I18N
        1. Visual Validation
        2. Do Not Validate Strings with LCMapString
        3. Use CreateFile to Validate Filenames
      5. Character Set Conversion Issues
      6. Use MultiByteToWideChar with MB_PRECOMPOSED and MB_ERR_INVALID_CHARS
      7. Use WideCharToMultiByte with WC_NO_BEST_FIT_CHARS
      8. Comparison and Sorting
      9. Unicode Character Properties
      10. Normalization
      11. Summary
  6. III. Even More Secure Coding Techniques
    1. 15. Socket Security
      1. Avoiding Server Hijacking
      2. TCP Window Attacks
      3. Choosing Server Interfaces
      4. Accepting Connections
      5. Writing Firewall-Friendly Applications
        1. Use One Connection to Do the Job
        2. Don’t Require the Server to Connect Back to the Client
        3. Use Connection-Based Protocols
        4. Don’t Multiplex Your Application over Another Protocol
        5. Don’t Embed Host IP Addresses in Application-Layer Data
        6. Make Your Application Configurable
      6. Spoofing and Host-Based and Port-Based Trust
      7. IPv6 Is Coming!
      8. Summary
    2. 16. Securing RPC, ActiveX Controls, and DCOM
      1. An RPC Primer
        1. What Is RPC?
        2. Creating RPC Applications
          1. Compiling the Code
        3. How RPC Applications Communicate
          1. Context Handles and State
      2. Secure RPC Best Practices
        1. Use the /robust MIDL Switch
        2. Use the [range] Attribute
        3. Require Authenticated Connections
          1. Client-Side Settings
          2. Server-Side Settings
          3. A Note Regarding Kerberos Support
          4. Performance of Different Security Settings
        4. Use Packet Privacy and Integrity
        5. Use Strict Context Handles
        6. Don’t Rely on Context Handles for Access Checks
        7. Be Wary of NULL Context Handles
        8. Don’t Trust Your Peer
        9. Use Security Callbacks
        10. Implications of Multiple RPC Servers in a Single Process
          1. Consider Adding an Annotation for Your Endpoint
        11. Use Mainstream Protocols
      3. Secure DCOM Best Practices
        1. DCOM Basics
        2. Application-Level Security
        3. DCOM User Contexts
          1. Run as the Launching User
          2. Run as the Interactive User
          3. Run as the Local System Account
          4. Run as a Specific User
        4. Programmatic Security
        5. Sources and Sinks
      4. An ActiveX Primer
      5. Secure ActiveX Best Practices
        1. What ActiveX Components Are Safe for Initialization and Safe for Scripting?
        2. Best Practices for Safe for Initialization and Scripting
          1. Is Your Control Safe?
          2. Limit Domain Usage
          3. Using SiteLock
          4. Setting the Kill Bit
      6. Summary
    3. 17. Protecting Against Denial of Service Attacks
      1. Application Failure Attacks
      2. CPU Starvation Attacks
      3. Memory Starvation Attacks
      4. Resource Starvation Attacks
      5. Network Bandwidth Attacks
      6. Summary
    4. 18. Writing Secure .NET Code
      1. Code Access Security: In Pictures
      2. FxCop: A “Must-Have” Tool
      3. Assemblies Should Be Strong-Named
        1. Strong-Named Assemblies and ASP.NET
      4. Specify Assembly Permission Requirements
        1. Request Minimal Permission Set
        2. Refuse Unneeded Permissions
        3. Request Optional Permissions
      5. Overzealous Use of Assert
      6. Further Information Regarding Demand and Assert
      7. Keep the Assertion Window Small
      8. Demands and Link Demands
        1. An Example LinkDemand Security Bug
      9. Use SuppressUnmanagedCodeSecurityAttribute with Caution
      10. Remoting Demands
      11. Limit Who Uses Your Code
      12. No Sensitive Data in XML or Configuration Files
      13. Review Assemblies That Allow Partial Trust
      14. Check Managed Wrappers to Unmanaged Code for Correctness
      15. Issues with Delegates
      16. Issues with Serialization
      17. The Role of Isolated Storage
      18. Disable Tracing and Debugging Before Deploying ASP.NET Applications
      19. Do Not Issue Verbose Error Information Remotely
      20. Deserializing Data from Untrusted Sources
      21. Don’t Tell the Attacker Too Much When You Fail
      22. Summary
  7. IV. Special Topics
    1. 19. Security Testing
      1. The Role of the Security Tester
      2. Security Testing Is Different
      3. Building Security Test Plans from a Threat Model
        1. Decompose the Application
        2. Identify the Component Interfaces
        3. Rank the Interfaces by Potential Vulnerability
        4. Ascertain the Data Structures Used by Each Interface
        5. Attacking Applications with STRIDE
        6. Attacking with Data Mutation
          1. The Data and the Container
            1. Perturbing the container
            2. Perturbing the data
          2. Random data
          3. Partially incorrect data
          4. Taking it further—use different sizes
          5. Special Characters
          6. On-the-Wire Attacks
        7. Before Testing
        8. Building Tools to Find Flaws
          1. Testing Sockets-Based Applications
          2. Testing HTTP-Based Server Applications
          3. Testing Named Pipes Applications
          4. Testing COM, DCOM, ActiveX, and RPC Applications
          5. Testing ActiveX Controls in <OBJECT> tags
          6. Testing File-Based Applications
          7. Testing Registry-Based Applications
          8. Testing Command Line Arguments
          9. Testing XML Payloads
          10. Testing SOAP Services
          11. Testing for Cross-Site Scripting and Script-Injection Bugs
      4. Testing Clients with Rogue Servers
      5. Should a User See or Modify That Data?
      6. Testing with Security Templates
      7. When You Find a Bug, You’re Not Done!
      8. Test Code Should Be of Great Quality
      9. Test the End-to-End Solution
      10. Determining Attack Surface
        1. Determine Root Attack Vectors
        2. Determine Bias For Attack Vectors
        3. Count the Biased Vectors in the Product
      11. Summary
    2. 20. Performing a Security Code Review
      1. Dealing with Large Applications
      2. A Multiple-Pass Approach
      3. Low-Hanging Fruit
      4. Integer Overflows
        1. A Related Issue: Integer Underflows
      5. Checking Returns
      6. Perform an Extra Review of Pointer Code
      7. Never Trust the Data
      8. Summary
    3. 21. Secure Software Installation
      1. Principle of Least Privilege
      2. Clean Up After Yourself!
      3. Using the Security Configuration Editor
      4. Low-Level Security APIs
        1. Using the Windows Installer
      5. Summary
    4. 22. Building Privacy into Your Application
      1. Malicious vs. Annoying Invasions of Privacy
      2. Major Privacy Legislation
        1. Personally Identifiable Information
        2. The EU Directives on Data Protection
        3. Safe Harbor Principles
          1. Notice
          2. Choice
          3. Onward Transfer
          4. Access
          5. Security
          6. Data Integrity
          7. Enforcement
        4. Other Privacy Legislation
      3. Privacy vs. Security
      4. Building a Privacy Infrastructure
        1. The Role of the Chief Privacy Officer
        2. The Role of the Privacy Advocate
      5. Designing Privacy-Aware Applications
        1. Including Privacy in the Development Process
          1. Privacy Specification Template
          2. Privacy Review Template
          3. Privacy Policy Statement
          4. P3P Content
        2. Exploring Privacy Features
          1. Implementing P3P
          2. Privacy for Client-Side Applications
          3. Cover Your Tracks
          4. Don’t Phone Home
          5. Protecting the Application from the Application Users
            1. Limiting access to your application
            2. Leaving a paper trail
          6. Privacy Through Obfuscation and Encryption
          7. Protecting the Transfer of Data
          8. Putting the Pieces Together
      6. Summary
    5. 23. General Good Practices
      1. Don’t Tell the Attacker Anything
      2. Service Best Practices
        1. Security, Services, and the Interactive Desktop
        2. Service Account Guidelines
          1. LocalSystem
          2. Network Service
          3. LocalService
          4. Domain Accounts
          5. Local Accounts
      3. Don’t Leak Information in Banner Strings
      4. Be Careful Changing Error Messages in Fixes
      5. Double-Check Your Error Paths
      6. Keep It Turned Off!
      7. Kernel-Mode Mistakes
        1. High-Level Security Issues
        2. Handles
        3. Symbolic Links
        4. Quota
        5. Serialization Primitives
        6. Buffer-Handling Issues
        7. IRP Cancellation
      8. Add Security Comments to Code
      9. Leverage the Operating System
      10. Don’t Rely on Users Making Good Decisions
      11. Calling CreateProcess Securely
        1. Do Not Pass NULL for lpApplicationName
        2. Use Quotes Around the Path to Executable in lpCommandLine
      12. Don’t Create Shared/Writable Segments
        1. In a .def File
        2. In a .h* or .c* File
        3. On the Linker Command Line
      13. Using Impersonation Functions Correctly
      14. Don’t Write User Files to \Program Files
      15. Don’t Write User Data to HKLM
      16. Don’t Open Objects for FULL_CONTROL or ALL_ACCESS
      17. Object Creation Mistakes
      18. Care and Feeding of CreateFile
      19. Creating Temporary Files Securely
      20. Implications of Setup Programs and EFS
      21. File System Reparse Point Issues
      22. Client-Side Security Is an Oxymoron
      23. Samples Are Templates
      24. Dogfood Your Stuff!
      25. You Owe It to Your Users If…
      26. Determining Access Based on an Administrator SID
      27. Allow Long Passwords
      28. Be Careful with _alloca
        1. ATL Conversion Macros
      29. Don’t Embed Corporate Names
      30. Move Strings to a Resource DLL
      31. Application Logging
      32. Migrate Dangerous C/C++ to Managed Code
    6. 24. Writing Security Documentation and Error Messages
      1. Security Issues in Documentation
        1. The Basics
        2. Threat Mitigation Through Documentation
        3. Documenting Security Best Practices
          1. Threat #4: ISOAP_xxx Account Has Many Privileges
          2. Threat #13: Client <-- --> Server Communication Is Insecure
          3. Threat #14: By Default, SOAP-Server Is Accessible to Everyone
          4. Threat #19: Most of Our Testing Is with Single-Purpose Servers
      2. Security Issues in Error Messages
      3. A Typical Security Message
      4. Information Disclosure Issues
        1. Informed Consent
        2. Progressive Disclosure
        3. Be Specific
        4. Consider Not Asking the Question
        5. Usability Test Your Security Messages
      5. A Note When Reviewing Product Specifications
      6. Security Usability
      7. Summary
  8. V. Appendixes
    1. A. Dangerous APIs
      1. APIs with Buffer Overrun Issues
        1. strcpy, wcscpy, lstrcpy, _tcscpy, and _mbscpy
        2. strcat, wcscat, lstrcat, _tcscat, and _mbscat
        3. strncpy, wcsncpy, _tcsncpy, lstrcpyn, and _mbsnbcpy
        4. strncat, wcsncat, _tcsncat, and _mbsnbcat
        5. memcpy and CopyMemory
        6. sprintf and swprintf
        7. _snprintf and _snwprintf
        8. printf family
        9. strlen, _tcslen, _mbslen, and wcslen
        10. gets
        11. scanf(“%s”,…), _tscanf, and wscanf
        12. Standard Template Library stream operator (&gt;&gt;)
        13. MultiByteToWideChar
        14. _mbsinc, _mbsdec, _mbsncat, _mbsncpy, _mbsnextc, _mbsnset, _mbsrev, _mbsset, _mbsstr, _mbstok, _mbccpy, and _mbslen
      2. APIs with Name-Squatting Issues
        1. CreateDirectory, CreateEvent, CreateFile, CreateFileMapping, CreateHardLink, Create­Job­Object, CreateMailslot, CreateMutex, CreateNamedPipe, CreateSemaphore, CreateWaitableTimer, MoveFile, and classes that wrap these APIs
      3. APIs with Trojaning Issues
        1. CreateProcess(NULL,…), CreateProcessAsUser, and CreateProcessWithLogon
        2. WinExec and ShellExecute
        3. LoadLibrary, LoadLibraryEx, and SearchPath
      4. Windows Styles and Control Types
        2. TTM_GETTEXT
        4. ES_PASSWORD
      5. Impersonation APIs
        1. SetSecurityDescriptorDacl(…,…,NULL,…)
      6. APIs with Denial of Service Issues
        1. InitializeCriticalSection and EnterCriticalSection
        2. _alloca and related functions and macros
        3. TerminateThread and TerminateProcess
      7. Networking API Issues
        1. bind
        2. recv
        3. send
        4. NetApi32 calls
      8. Miscellaneous APIs
        1. IsBadReadPtr, IsBadWritePtr, IsBadCodePtr, IsBadStringPtr, IsBadHugeReadPtr, and IsBadHugeWritePtr
        2. CopyFile and MoveFile
    2. B. Ridiculous Excuses We’ve Heard
      1. No one will do that!
      2. Why would anyone do that?
      3. We’ve never been attacked.
      4. We’re secure—we use cryptography.
      5. We’re secure—we use ACLs.
      6. We’re secure—we use a firewall.
      7. We’ve reviewed the code, and there are no security bugs.
      8. We know it’s the default, but the administrator can turn it off.
      9. If we don’t run as administrator, stuff breaks.
      10. But we’ll slip the schedule!
      11. It’s not exploitable!
      12. But that’s the way we’ve always done it.
      13. If only we had better tools….
    3. C. A Designer’s Security Checklist
    4. D. A Developer’s Security Checklist
      1. General
      2. Web and Database-Specific
      3. RPC
      4. ActiveX, COM, and DCOM
      5. Crypto and Secret Management
      6. Managed Code
    5. E. A Tester’s Security Checklist
      1. A Final Thought
    6. F. Annotated Bibliography
  9. G. About the Author
  10. About the Authors
  11. Copyright

Product information

  • Title: Writing Secure Code
  • Author(s): Michael Howard and David LeBlanc
  • Release date: December 2002
  • Publisher(s): Microsoft Press
  • ISBN: 0735617228