Secure Coding in C and C++
Author: Robert C Seacord
The CERT Coordination Center (CERT/CC) was formed by the Defense Advanced Research Projects Agency (DARPA) in November 1988 in response to the Morris worm incident, which brought ten percent of Internet systems to a halt in November 1988. The CERT/CC is located in Pittsburgh, Pennsylvania, at the Software Engineering Institute (SEI), a federally funded research and development center sponsored by the U.S. Department of Defense.
The initial focus of the CERT/CC was incident response and analysis. Incidents include successful attacks such as compromises and denial of service, as well as attack attempts, probes, and scans. Since 1988, the CERT/CC has received more than 22,665 hotline calls reporting computer security incidents or requesting information, and has handled more than 319,992 computer security incidents. The number of incidents reported each year continues to grow.
Responding to incidents, while necessary, is insufficient to secure the Internet and interconnected information systems. Analysis indicates that the majority of incidents are caused by trojans, social engineering, and the exploitation of software vulnerabilities, including software defects, design decisions, configuration decisions, and unexpected interactions between systems. The CERT/CC monitors public sources of vulnerability information and regularly receives reports of vulnerabilities. Since 1995, more than 16,726 vulnerabilities have been reported. When a report is received, the CERT/CC analyzes the potential vulnerability and works with technology producers to inform them of security deficiencies in their products and to facilitate and track their response to those problems.
Similar to incidentreports, vulnerability reports continue to grow at an alarming rate. While managing vulnerabilities pushes the process upstream, it is again insufficient to address the issues of Internet and information system security. To address the growing number of both vulnerabilities and incidents, it is increasingly apparent that the problem must be attacked at the source by working to prevent the introduction of software vulnerabilities during software development and ongoing maintenance. Analysis of existing vulnerabilities indicates that a relatively small number of root causes account for the majority of vulnerabilities. The goal of this book is to educate developers about these root causes and the steps that can be taken so that vulnerabilities are not introduced.Audience
Secure Coding in C and C++ should be useful to anyone involved in the development or maintenance of software in C and C++.
- For a C/C++ programmer, this book will teach you how to identify common programming errors that result in software vulnerabilities, understand how these errors are exploited, and implement a solution in a secure fashion.
- For a software project manager, this book identifies the risks and consequences of software vulnerabilities to guide investments in developing secure software.
- For a computer science student, this book will teach you programming practices that will help you to avoid developing bad habits and enable you to develop secure programs during your professional career.
- For a security analyst, this book provides a detailed description of common vulnerabilities, identifies ways to detect these vulnerabilities, practical avoidance strategies.
Organization and ContentSecure Coding in C and C++ provides practical advice on secure practices in C and C++ programming. Producing secure programs requires secure designs. However, even the best designs can lead to insecure programs if developers are unaware of the many security pitfalls inherent in C and C++ programming. This book provides a detailed explanation of common programming errors in C and C++ and describes how these errors can lead to code that is vulnerable to exploitation. The book concentrates on security issues intrinsic to the C and C++ programming languages and associated libraries. It does not emphasize security issues involving interactions with external systems such as databases and web servers, as these are rich topics on their own. The intent is that this book be useful to anyone involved in developing secure C and C++ programs regardless of the specific application.
Secure Coding in C and C++ is organized around functional capabilities commonly implemented by software engineers that have potential security consequences, such as formatted output and arithmetic operations. Each chapter describes insecure programming practices and common errors that can lead to vulnerabilities, how these programming flaws can be exploited, the potential consequences of exploitation, and secure alternatives. Root causes of software vulnerabilities, such as buffer overflows, integer type range errors, and invalid format strings, are identified and explained where applicable. Strategies for securely implementing functional capabilities are described in each chapter, as well as techniques for discovering vulnerabilities in existing code.
This book contains the following chapters:
- Chapter 1 provides an overview of the problem, introduces security terms and concepts, and provides insight as to why so many vulnerabilities are found in C and C++ programs.
- Chapter 2 describes string manipulation in C and C++, common security flaws, and resulting vulnerabilities including buffer overflow and stack smashing. Both code and arc injection exploits are examined.
- Chapter 3 introduces arbitrary memory write exploits that allows an attacker to write a single address to any location in memory. This chapter describes how these exploits can be used to execute arbitrary code on a compromised machine. Vulnerabilities resulting from arbitrary memory writes are discussed in later chapters.
- Chapter 4 describes dynamic memory management. Dynamically allocated buffer overflows, writing to freed memory, and double-free vulnerabilities are described.
- Chapter 5 covers integral security issues (security issues dealing with integers) including integer overflows, sign errors, and truncation errors.
- Chapter 6 describes the correct and incorrect use of formatted output functions. Both format string and buffer overflows vulnerabilities resulting from the incorrect use of these functions are described.
- Chapter 7 describes common vulnerabilities associated with file I/O including race conditions and time of creation, time of use (TOCTOU) vulnerabilities.
- Chapter 8 recommends specific development practices for improving the overall security of your C / C++ application. These recommendat the recommendations included in each chapter for addressing specific vulnerability classes.
Secure Coding in C and C++ contains hundreds of examples of secure and insecure code as well as sample exploits. Almost all of these examples are in C and C++, although comparisons are drawn with other languages. The examples are implemented for Windows and Linux operating systems. Unless otherwise stated, Microsoft Windows examples are compiled using Visual C++ .NET and tested on Windows 2000 Professional platform with an Intel Pentium 4 processor while Linux examples are compiled with GNU gcc/g++ and tested running Red Hat Linux 9 on an Intel Pentium 4 processor.
While the specific examples have typically been compiled and tested in one or more of these environments, vulnerabilities are evaluated to determine whether they are specific to or generalizable across compiler version, operating system, microprocessor, applicable C or C++ standards, little or big endian architectures, and execution stack architecture.
This book focuses on programming flaws in C and C++ that are the most common causes of software vulnerabilities. However, because of size and space constraints, not every potential source of vulnerabilities is covered.
Table of Contents:
Preface.
1. Running with Scissors.
Gauging the Threat.
Security Concepts
C and C++.
Development Platforms.
Summary.
For Further Reading.
2. Strings.
String Characteristics.
Common String Manipulation Errors.
String Vulnerabilities.
Process Memory Organization.
Stack Smashing.
Code Injection.
Arc Injection.
Mitigation Strategies.
Notable Vulnerabilities.
Summary.
For Further Reading.
3. Pointer Subterfuge.
Data Locations.
Function Pointers.
Data Pointers.
Modifying the Instruction Pointer.
Global Offset Table.
The .dtors Section.
Virtual Pointers.
The atexit() and on_exit() Functions.
The longjmp() Function.
Exception Handling.
Mitigation Strategies.
Summary.
For Further Reading.
4. Dynamic Memory Management.
Dynamic Memory Management.
Common Dynamic Memory Management Errors.
Doug Lea's Memory Allocator.
RtlHeap.
Mitigation Strategies.
Notable Vulnerabilities.
Summary.
For Further Reading.
5. Integer Security.
Integers.
Integer Conversions.
Integer Error Conditions.
Integer Operations.
Vulnerabilities.
Non-Exceptional Integer Logic Errors.
Mitigation Strategies.
Notable Vulnerabilities.
Summary.
For Further Reading.
6. Formatted Output.
Variadic Functions.
Formatted Output Functions.
Exploiting Formatted Output Functions.
Stack Randomization.
Mitigation Strategies.
Notable Vulnerabilities.
Summary.
For Further Reading.
7. File I/O.
Concurrency.
Time of Check, Time of Use.
Files as Locks and File Locking.
File System Exploits.
Mitigation Strategies.
Summary.
8. Recommended Practices.
Secure Software Development Principles.
Systems Quality Requirements Engineering.
Threat Modeling.
Use/Misuse Cases.
Architecture and Design.
Off-the-Shelf Software.
Compiler Checks.
Input Validation.
Data Sanitization.
Static Analysis.
Quality Assurance.
Memory Permissions.
Defense in Depth.
TSP-Secure.
Summary.
Further Reading.
References.
Acronyms.
Index.
Look this: Cooking with the Original Search Engine or Pick of the Crop Two
Edison's Eve: A Magical History of the Quest for Mechanical Life
Author: Gaby Wood
"Could an eighteenth-century mechanical duck really digest and excrete its food? Was "the Turk," a celebrated chess-playing and -winning machine fabricated in 1769, a dazzling piece of fakery, or could it actually think? Why was Thomas Edison obsessed with making a mechanical doll - a perfect woman, mass-produced? Can a twenty-first-century robot express human emotions of its own?" Taking up themes long familiar from the realms of fairy tales and science fiction, Gaby Wood traces the hidden prehistory of a modern idea - the thinking, hoaxes, and inventions that presaged contemporary robotics and the current experiments with artificial intelligence. Informed by the author's scientific and historical research, Edison's Eve is also a brilliant literary, cultural, and philosophical examination of the motives that have driven human beings to pursue the creation of mechanical life, and the effects of that pursuit - both in its successes and in its failures - on our sense of what makes us human.
The New York Times
Tracing the human fascination with robotics to the sophisticated mechanical toys of the Enlightenment, the author conjures a menagerie of bizarre and quixotic automatons, including chess-playing machines, artificial defecating ducks and Thomas Edison's doomed venture to mass-produce talking dolls.
The New Yorker
Embodying the confusions between what is "lifelike" and what is alive, robots have always held an anxious fascination. When eighteenth-century physicians described the body as a complex piece of machinery, the stage was set for inventors like Jacques de Vaucanson, who thrilled Paris with a flute-playing android, and Wolfgang von Kempelen, whose chess-playing automaton took on the best players of its time. Deftly balancing historical detail with provocative meditations on the reception accorded such marvels, Wood then traces the development of subsequent imitations of life, such as the talking doll designed by Thomas Edison and the magic-filled films of Georges Méliès. Her contention that in the twentieth century human freaks came to seem more uncanny than machines may not entirely persuade, but the exotic particulars -- especially those pertaining to a group of circus midgets called the Doll Family -- more than make up for this inconsistency.
John Glassie - Forbes
Our fear of human cloning and uppity, thinking computers may seem unique to our age, but this book shows that people have been trying to create artificial life, or play God, for a long time. Archytas of Tarentum, a contemporary of Plato, is said to have built a flying wooden pigeon, and Hero of Alexandria created a simulated human that, thanks to a special neck mechanism, defied all attempts at decapitation. Things really got busy in the Age of Reason, when sci-ence began to suggest that men were machines (with souls). In the 1730s, Jacques de Vaucanson built an elaborate flute-playing automaton that actually "breathed" air and delighted Parisian audiences with 12 different melodies. (Diderot saw the show and coined the term "androA de.") He soon topped himself with a mechanical duck that "ate food out of the exhibitor's hand, swallowed it, digested it and excreted it" before the likes of Louis XV and Voltaire. The Hungarian Wolfgang von Kempelen subsequently created a mechanical chess player that toured internationally over many decades, taking on Napoleon (who lost), Catherine the Great (who was disqualified for cheating) and Benjamin Franklin (out-come undocumented). This baffling wooden "Turk" rolled his eyes and moved game pieces with an ingeniously engi-neered arm. It (he) made ladies faint, whipped up widespread philosophical debate about the nature of intelligence and stirred Edgar Allan Poe into writing an exposA in which he asserted, rightly, that a human being had to be inside. Need-less to say, the area between science and spectacle, experiment and amusement, metaphysics and fun has historically been rather gray. There's even evidence that Thomas Edison developed thephonograph as a component for a talking doll he wanted to mass-produce. He did in fact create a metal doll with a tiny phonograph inside, the Eve of this book's title, but it was a huge commercial flop. (Recording technology, on the other hand, has done pretty well.) Simulations of life have always been creepy, if not downright frightening, even when meant to entertain. One day in 1895, in Paris, the first paying audience sat down to experience the Cinematograph. When the moving image of a train came rushing to-ward them, they ran right out of the theater. In the end, the author says, each of these inventions has been "a riddle, a fundamental challenge to our perception of what makes us human." And there are more of them on the way.
Publishers Weekly
In five entertaining chapters, British journalist Wood describes the ways humans have built machines to resemble themselves over the past three centuries. Wood begins with the dynamic creations of the 18th-century Frenchman Jacques de Vaucanson, explaining how his elaborate automatons, most notably a mechanical flute player and a mechanical duck apparently capable of eating and defecating, fascinated onlookers throughout Europe. She then moves to Wolfgang von Kempelen's chess-playing machine, constructed to look like a Turkish gentleman and capable of beating virtually any chess player in the 18th century, and Thomas Alva Edison's unsuccessful attempt to capture the American toy market by incorporating a version of his phonograph into the first talking doll. In her fourth chapter, Wood switches her attention from machines that look like humans to humans who look like machines. To wit, the Doll family: four midgets who toured with Ringling Brothers' Circus and appeared in The Wizard of Oz, in addition to other lesser known Hollywood productions. Some audiences refused to believe the Dolls were alive, assuming instead that they were sophisticated toys. Wood's anecdotes are delightful, though the book as a whole feels somewhat repetitive and short on analysis. She frequently reminds readers that these historical vignettes show the continuous struggle to determine what makes us human, but that's about as far as her commentary goes. (Aug.) Copyright 2002 Cahners Business Information.
Karen Reeds - KLIATT
It quacked like a duck, it flapped like a duck, it even pooped like a duck. So, how was this metal clockwork creature different from a real duck? The question perplexed its 18th-century audiences, and the quest to create imitations of life continues to bemuse and unnerve us. Gaby Wood, a staff writer for the London Observer, leads us through a splendid tour of modern robots, mechanical automata, Edison's talking dolls, Barnum & Bailey's living Doll Family, and the illusionary automata of Kempelen's Chess-Playing Turk, early photographers, movies, and magicians. Her research has turned up a remarkable range of historical and fictional examples of technology simulating life and vice versa. (I only regret the omission of Robertson Davies's use of the Talking Head tradition in The Deptford Trilogy). They are all fascinating in themselves, and her perceptive analysis connects them in wonderful ways. But it is the unfailing grace of Wood's writing and her willingness to put herself into the story that makes this a truly memorable book. Put this into the hands of high-school students as a model of first-rate prose and cultural history. If I were teaching English, history, film, sociology, psychology, philosophy, science, or computers-from middle school through grad school-I'd read parts aloud just for the fun of seeing where the discussion would go. Keep it in mind for adult book groups, too. KLIATT Codes: A-Recommended for advanced students and adults. 2002, Random House, Anchor, 304p. bibliog. index., Ages 17 to adult.
Booknews
Borrowing her title from the name of the talking doll manufactured by Thomas Edison, essayist Wood examines historical automata and the often-anxious reaction of the humans that came into contact with them. Recalling a mechanical duck that digested food; "The Turk," a mechanical chess player (secretly controlled by a human being); and Edison's Eve, she suggests that human reaction to these pre-robotic forms may offer clues to how we as a species will deal with the advent of advanced robotics and artificial intelligence. Annotation c. Book News, Inc., Portland, OR
Kirkus Reviews
British journalist Wood profiles roboticists with castration complexes and other men, both real and fictional, who thought they might somehow be able to create life. From Icarus to Dr. Frankenstein and beyond, these inventors display a mechanical ingenuity that appeals to the author almost as much as the Freudian aura of all their endeavors. Despite the title, Wood's favorite seems to be Jacques de Vaucanson, a French designer who crafted bizarre automata in the mid-18th century. His moving musicians on pedestals were the toast of Europe (one flutist had a 12-song repertoire), but his crowning achievement was a quacking, waddling, clockwork duck that could gobble up bits of food and, after an appropriate interval, defecate. By the time it was revealed that possibly green-dyed breadcrumbs were stored within the duck for effective release, Vaucanson had moved on to revolutionize French silk manufacture. Mechanical humanoids that could write poetry, play chess, tell fortunes, etc., may not have much in common with today's software-driven laboratory robots, but Wood finds the sentiments of compulsion and fascination ("They register emotions but do they realize what emotions they're registering?") to be a constant passed from tinkerer to cyberneticist. She has her way with Thomas Edison, finding the Wizard of Menlo Park to be an opportunistic misogynist who stuffed his newly minted phonograph into the body of a "talking doll" that sold for $10, about a week's wages for a factory worker. In the same vein, she introduces an obscure French novel whose Edison-like protagonist creates the perfect woman for a love-crazed client, annotating it with quotations from the real Thomas A. to buttress hercontention that he looked at a woman and saw a product that could be improved. A rigorously researched, clever, and obliquely feminist look at what happens over the ages when the Pygmalion complex is closeted in a well-equipped workshop.