Secure Coding in C and C++
Second Edition
Robert C. Seacord
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
Software Engineering Institute | Carnegie Mellon
The SEI Series in Software Engineering
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations
appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
CMM, CMMI, Capability Maturity Model, Capability Maturity Modeling, Carnegie Mellon, CERT, and CERT Coordination Center are
registered in the U.S. Patent and Trademark Office by Carnegie Mellon University.
ATAM; Architecture Tradeoff Analysis Method; CMM Integration; COTS Usage-Risk Evaluation; CURE; EPIC; Evolutionary Process for
Integrating COTS Based Systems; Framework for Software Product Line Practice; IDEAL; Interim Profile; OAR; OCTAVE; Operationally
Critical Threat, Asset, and Vulnerability Evaluation; Options Analysis for Reengineering; Personal Software Process; PLTP; Product Line Technical
Probe; PSP; SCAMPI; SCAMPI Lead Appraiser; SCAMPI Lead Assessor; SCE; SEI; SEPG; Team Software Process; and TSP are service
marks of Carnegie Mellon University.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations
appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no
responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of
the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic
versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more
information, please contact:
U.S. Corporate and Government Sales
(800) 382-3419
corpsales@pearsontechgroup.com
For sales outside the United States, please contact:
International Sales
international@pearsoned.com
Visit us on the Web: informit.com/aw
Library of Congress Cataloging Control Number: 2013932290
Copyright © 2013 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the
publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education,
Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290.
ISBN-13: 978-0-321-82213-0
ISBN-10: 0-321-82213-7
Text printed in the United States on recycled paper at Edwards Brothers Malloy in Ann Arbor, Michigan.
First printing, March 2013
To my wife, Rhonda, and our children, Chelsea and Jordan
Contents
Foreword
Preface
Acknowledgments
About the Author
Chapter 1 Running with Scissors
1.1 Gauging the Threat
What Is the Cost?
Who Is the Threat?
Software Security
1.2 Security Concepts
Security Policy
Security Flaws
Vulnerabilities
Exploits
Mitigations
1.3 C and C++
A Brief History
What Is the Problem with C?
Legacy Code
Other Languages
1.4 Development Platforms
Operating Systems
Compilers
1.5 Summary
1.6 Further Reading
Chapter 2 Strings
2.1 Character Strings
String Data Type
UTF-8
Wide Strings
String Literals
Strings in C++
Character Types
Sizing Strings
2.2 Common String Manipulation Errors
Improperly Bounded String Copies
Off-by-One Errors
Null-Termination Errors
String Truncation
String Errors without Functions
2.3 String Vulnerabilities and Exploits
Tainted Data
Security Flaw:
Buffer Overflows
Process Memory Organization
Stack Management
Stack Smashing
Code Injection
Arc Injection
Return-Oriented Programming
2.4 Mitigation Strategies for Strings
String Handling
C11 Annex K Bounds-Checking Interfaces
Dynamic Allocation Functions
C++
Invalidating String Object References
Other Common Mistakes in
Usage
2.5 String-Handling Functions
C99
C11 Annex K Bounds-Checking Interfaces:
Dynamic Allocation Functions
C99
and
and
and
2.6 Runtime Protection Strategies
Detection and Recovery
Input Validation
Object Size Checking
Visual Studio Compiler-Generated Runtime Checks
Stack Canaries
Stack-Smashing Protector (ProPolice)
Operating System Strategies
Detection and Recovery
Nonexecutable Stacks
W^X
PaX
Future Directions
2.7 Notable Vulnerabilities
Remote Login
Kerberos
2.8 Summary
2.9 Further Reading
Chapter 3 Pointer Subterfuge
3.1 Data Locations
3.2 Function Pointers
3.3 Object Pointers
3.4 Modifying the Instruction Pointer
3.5 Global Offset Table
3.6 The
Section
3.7 Virtual Pointers
3.8 The
and
3.9 The
Function
3.10 Exception Handling
Functions
Structured Exception Handling
System Default Exception Handling
3.11 Mitigation Strategies
Stack Canaries
W^X
Encoding and Decoding Function Pointers
3.12 Summary
3.13 Further Reading
Chapter 4 Dynamic Memory Management
4.1 C Memory Management
C Standard Memory Management Functions
Alignment
and Variable-Length Arrays
4.2 Common C Memory Management Errors
Initialization Errors
Failing to Check Return Values
Dereferencing Null or Invalid Pointers
Referencing Freed Memory
Freeing Memory Multiple Times
Memory Leaks
Zero-Length Allocations
DR #400
4.3 C++ Dynamic Memory Management
Allocation Functions
Deallocation Functions
Garbage Collection
4.4 Common C++ Memory Management Errors
Failing to Correctly Check for Allocation Failure
Improperly Paired Memory Management Functions
Freeing Memory Multiple Times
Deallocation Function Throws an Exception
4.5 Memory Managers
4.6 Doug Lea’s Memory Allocator
Buffer Overflows on the Heap
4.7 Double-Free Vulnerabilities
Writing to Freed Memory
RtlHeap
Buffer Overflows (Redux)
4.8 Mitigation Strategies
Null Pointers
Consistent Memory Management Conventions
phkmalloc
Randomization
OpenBSD
The jemalloc Memory Manager
Static Analysis
Runtime Analysis Tools
4.9 Notable Vulnerabilities
CVS Buffer Overflow Vulnerability
Microsoft Data Access Components (MDAC)
CVS Server Double-Free
Vulnerabilities in MIT Kerberos 5
4.10 Summary
Chapter 5 Integer Security