Secure Coding In C And C - Carnegie Mellon University

2y ago
13 Views
2 Downloads
2.30 MB
146 Pages
Last View : 2m ago
Last Download : 3m ago
Upload by : Albert Barnett
Transcription

Secure Codingin C and C Second Edition

The SEI Series in Software EngineeringSoftware Engineering Institute of Carnegie Mellon University and Addison-WesleyVisit informit.com/sei for a complete list of available publications.The SEI Series in Software Engineering is a collaborative undertaking of theCarnegie Mellon Software Engineering Institute (SEI) and Addison-Wesley to developand publish books on software engineering and related topics. The common goal of theSEI and Addison-Wesley is to provide the most current information on these topics in aform that is easily usable by practitioners and students.Titles in the series describe frameworks, tools, methods, and technologies designed tohelp organizations, teams, and individuals improve their technical or management capabilities. Some books describe processes and practices for developing higher-quality software, acquiring programs for complex systems, or delivering services more effectively.Other books focus on software and system architecture and product-line development.Still others, from the SEI’s CERT Program, describe technologies and practices neededto manage software and network security risk. These and all titles in the series addresscritical problems in software engineering for which practical solutions are available.Make sure to connect with us!informit.com/socialconnect

Secure Codingin C and C Second EditionRobert C. SeacordUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico City

The SEI Series in Software EngineeringMany 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, thedesignations have been printed with initial capital letters or in all capitals.CMM, CMMI, Capability Maturity Model, Capability Maturity Modeling, Carnegie Mellon, CERT, and CERTCoordination 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; SCAMPILead Appraiser; SCAMPI Lead Assessor; SCE; SEI; SEPG; Team Software Process; and TSP are service marks ofCarnegie 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, thedesignations 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 impliedwarranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidentalor consequential damages in connection with or arising out of the use of the information or programs containedherein.The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or specialsales, 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-3419corpsales@pearsontechgroup.comFor sales outside the United States, please contact:International Salesinternational@pearsoned.comVisit us on the Web: informit.com/awLibrary of Congress Cataloging Control Number: 2013932290Copyright 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. Toobtain 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-0ISBN-10:0-321-82213-7Text 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

This page intentionally left blank

out the AuthorChapter 1xxviiRunning with Scissors11.151.21.31.4Gauging the ThreatWhat Is the Cost?Who Is the Threat?Software Security6811Security Concepts12Security PolicySecurity FlawsVulnerabilitiesExploitsMitigations1414151617C and C 17A Brief HistoryWhat Is the Problem with C?Legacy CodeOther Languages19212425Development Platforms25Operating SystemsCompilers2626vii

viiiContents1.51.6Chapter 2SummaryFurther Reading2728Strings292.1Character Strings29String Data TypeUTF-8Wide StringsString LiteralsStrings in C Character TypesSizing Strings30323334363739Common String Manipulation Errors42Improperly Bounded String CopiesOff-by-One ErrorsNull-Termination ErrorsString TruncationString Errors without Functions4247484949String Vulnerabilities and Exploits50Tainted DataSecurity Flaw: IsPasswordOKBuffer OverflowsProcess Memory OrganizationStack ManagementStack SmashingCode InjectionArc InjectionReturn-Oriented n Strategies for Strings72String HandlingC11 Annex K Bounds-Checking InterfacesDynamic Allocation FunctionsC std::basic stringInvalidating String Object ReferencesOther Common Mistakes in basic string Usage7373768183String-Handling Functions8480gets()84C99C11 Annex K Bounds-Checking Interfaces: gets s()Dynamic Allocation Functionsstrcpy() and strcat()C99strncpy() and strncat()memcpy() and memmove()84strlen()8687898993100100

ixContents2.62.72.82.9Chapter 3Runtime Protection Strategies101Detection and RecoveryInput ValidationObject Size CheckingVisual Studio Compiler-Generated Runtime ChecksStack CanariesStack-Smashing Protector (ProPolice)Operating System StrategiesDetection and RecoveryNonexecutable StacksW XPaXFuture ble Vulnerabilities117Remote LoginKerberos117118SummaryFurther Reading118120Pointer Subterfuge1213.13.23.33.43.53.63.73.83.93.10Data LocationsFunction PointersObject PointersModifying the Instruction PointerGlobal Offset TableThe .dtors SectionVirtual PointersThe atexit() and on exit() FunctionsThe longjmp() FunctionException Handling122123124125127129131133134136Structured Exception HandlingSystem Default Exception Handling1371393.11 Mitigation StrategiesStack CanariesW XEncoding and Decoding Function PointersChapter 41391401401403.12 Summary3.13 Further Reading142143Dynamic Memory Management1454.1C Memory Management146C Standard Memory Management FunctionsAlignmentalloca() and Variable-Length Arrays146147149

xContents4.2Common C Memory Management Errors151Initialization ErrorsFailing to Check Return ValuesDereferencing Null or Invalid PointersReferencing Freed MemoryFreeing Memory Multiple TimesMemory LeaksZero-Length AllocationsDR #400151153155156157158159161C Dynamic Memory Management162Allocation FunctionsDeallocation FunctionsGarbage Collection164168169Common C Memory Management Errors172Failing to Correctly Check for Allocation FailureImproperly Paired Memory Management FunctionsFreeing Memory Multiple TimesDeallocation Function Throws an Exception1721721761794.54.6Memory ManagersDoug Lea’s Memory Allocator180182Buffer Overflows on the Heap1854.7Double-Free Vulnerabilities191Writing to Freed MemoryRtlHeapBuffer Overflows (Redux)195196204Mitigation Strategies212Null PointersConsistent Memory Management ConventionsphkmallocRandomizationOpenBSDThe jemalloc Memory ManagerStatic AnalysisRuntime Analysis Tools212212213215215216217218Notable Vulnerabilities222CVS Buffer Overflow VulnerabilityMicrosoft Data Access Components (MDAC)CVS Server Double-FreeVulnerabilities in MIT Kerberos 52222232232244.34.44.84.9Chapter 54.10 Summary224Integer Security2255.15.2Introduction to Integer SecurityInteger Data Types225226Unsigned Integer Types227

xiContents5.35.45.5229231235237240241241Integer Conversions246Converting IntegersInteger Conversion RankInteger PromotionsUsual Arithmetic ConversionsConversions from Unsigned Integer TypesConversions from Signed Integer TypesConversion Implications246246247249250253256Integer cationDivision and RemainderShifts258260267269274279Integer ion and Truncation ErrorsNonexceptional Integer Logic Errors283283285287Mitigation Strategies288Integer Type SelectionAbstract Data TypesArbitrary-Precision ArithmeticRange CheckingPrecondition and Postcondition TestingSecure Integer LibrariesOverflow DetectionCompiler-Generated Runtime ChecksVerifiably In-Range OperationsAs-If Infinitely Ranged Integer ModelTesting and 7Formatted Output3096.16.2Variadic FunctionsFormatted Output Functions310313Format Strings3145.65.7Chapter 6WraparoundSigned Integer TypesSigned Integer RangesInteger OverflowCharacter TypesData ModelsOther Integer Types

xiiContents6.36.46.5GCCVisual C 318318Exploiting Formatted Output Functions319Buffer OverflowOutput StreamsCrashing a ProgramViewing Stack ContentViewing Memory ContentOverwriting MemoryInternationalizationWide-Character Format String Vulnerabilities320321321322324326331332Stack Randomization332Defeating Stack RandomizationWriting Addresses in Two WordsDirect Argument Access332334335Mitigation Strategies337Exclude User Input from Format StringsDynamic Use of Static ContentRestricting Bytes WrittenC11 Annex K Bounds-Checking Interfacesiostream versus stdioTestingCompiler ChecksStatic Taint AnalysisModifying the Variadic Function ImplementationExec ShieldFormatGuardStatic Binary Analysis3383383393406.6 Notable VulnerabilitiesWashington University FTP DaemonCDE ToolTalkEttercap Version NG-0.7.2Chapter 73413423423433443463463473483483483496.7 Summary6.8 Further allelism354355Data ParallelismTask Parallelism357359Performance Goals359Amdahl’s Law361Common Errors362Race Conditions3627.37.4

xiiiContents7.57.67.77.8Chapter 8Corrupted ValuesVolatile Objects364365Mitigation Strategies368Memory ModelSynchronization PrimitivesThread Role Analysis (Research)Immutable Data StructuresConcurrent Code Properties368371380383383Mitigation Pitfalls384DeadlockPrematurely Releasing a LockContentionThe ABA Problem386391392393Notable Vulnerabilities399DoS Attacks in Multicore Dynamic Random-Access Memory(DRAM) SystemsConcurrency Vulnerabilities in System Call Wrappers399400Summary401File I/O4038.18.28.38.48.5File I/O Basics403File SystemsSpecial Files404406File I/O Interfaces407Data StreamsOpening and Closing FilesPOSIXFile I/O in C 408409410412Access Control413UNIX File PermissionsProcess PrivilegesChanging PrivilegesManaging PrivilegesManaging Permissions413415417422428File Identification432Directory TraversalEquivalence ErrorsSymbolic LinksCanonicalizationHard LinksDevice FilesFile Attributes432435437439442445448Race Conditions450Time of Check, Time of Use (TOCTOU)451

xivContents8.68.7Chapter 9Create without ReplaceExclusive AccessShared Directories453456458Mitigation Strategies461Closing the Race WindowEliminating the Race ObjectControlling Access to the Race ObjectRace Detection Tools462467469471Summary472Recommended Practices4739.19.29.39.49.59.6The Security Development Lifecycle474TSP-SecurePlanning and TrackingQuality Management477477479Security TrainingRequirements480481Secure Coding StandardsSecurity Quality Requirements EngineeringUse/Misuse Cases481483485Design486Secure Software Development PrinciplesThreat ModelingAnalyze Attack SurfaceVulnerabilities in Existing CodeSecure WrappersInput ValidationTrust 495496497498501502503Implementation503Compiler Security FeaturesAs-If Infinitely Ranged (AIR) Integer ModelSafe-Secure C/C Static AnalysisSource Code Analysis Laboratory (SCALe)Defense in Depth503505505506510511Verification512Static AnalysisPenetration TestingFuzz TestingCode AuditsDeveloper Guidelines and Checklists512513513515516

xvContents9.79.8Independent Security ReviewAttack Surface Review516517SummaryFurther Reading518518References519Acronyms539Index545

This page intentionally left blank

ForewordSociety’s increased dependency on networked software systems has beenmatched by an increase in the number of attacks aimed at these systems.These attacks—directed at governments, corporations, educational institutions, and individuals—have resulted in loss and compromise of sensitivedata, system damage, lost productivity, and financial loss.While many of the attacks on the Internet today are merely a nuisance,there is growing evidence that criminals, terrorists, and other maliciousactors view vulnerabilities in software systems as a tool to reach their goals.Today, software vulnerabilities are being discovered at the rate of over 4,000per year. These vulnerabilities are caused by software designs and implementations that do not adequately protect systems and by development practicesthat do not focus sufficiently on eliminating implementation defects thatresult in security flaws.While vulnerabilities have increased, there has been a steady advancein the sophistication and effectiveness of attacks. Intruders quickly developexploit scripts for vulnerabilities discovered in products. They then use thesescripts to compromise computers, as well as share these scripts so that otherattackers can use them. These scripts are combined with programs that automatically scan the network for vulnerable systems, attack them, compromisethem, and use them to spread the attack even further.With the large number of vulnerabilities being discovered each year,administrators are increasingly overwhelmed with patching existing systems.Patches can be difficult to apply and might have unexpected side effects. Afterxvii

xviiiForeworda vendor releases a security patch it can take months, or even years, before 90to 95 percent of the vulnerable computers are fixed.Internet users have relied heavily on the ability of the Internet communityas a whole to react quickly enough to security attacks to ensure that damageis minimized and attacks are quickly defeated. Today, however, it is clear thatwe are reaching the limits of effectiveness of our reactive solutions. Whileindividual response organizations are all working hard to streamline andautomate their procedures, the number of vulnerabilities in commercial software products is now at a level where it is virtually impossible for any but thebest-resourced organizations to keep up with the vulnerability fixes.There is little evidence of improvement in the security of most products;many software developers do not understand the lessons learned about thecauses of vulnerabilities or apply adequate mitigation strategies. This is evidenced by the fact that the CERT/CC continues to see the same types of vulnerabilities in newer versions of products that we saw in earlier versions.These factors, taken together, indicate that we can expect many attacksto cause significant economic losses and service disruptions within even thebest response times that we can realistically hope to achieve.Aggressive, coordinated response continues to be necessary, but we mustalso build more secure systems that are not as easily compromised. About Secure Coding in C and C Secure Coding in C and C addresses fundamental programming errors in Cand C that have led to the most common, dangerous, and disruptive software vulnerabilities recorded since CERT was founded in 1988. This bookdoes an excellent job of providing both an in-depth engineering analysis ofprogramming errors that have led to these vulnerabilities and mitigationstrategies that can be effectively and pragmatically applied to reduce or eliminate the risk of exploitation.I have worked with Robert since he first joined the SEI in April, 1987.Robert is a skilled and knowledgeable software engineer who has proven himself adept at detailed software vulnerability analysis and in communicatinghis observations and discoveries. As a result, this book provides a meticuloustreatment of the most common problems faced by software developers andprovides practical solutions. Robert’s extensive background in software development has also made him sensitive to trade-offs in performance, usability,and other quality attributes that must be balanced when developing secure

xixForewordcode. In addition to Robert’s abilities, this book also represents the knowledgecollected and distilled by CERT operations and the exceptional work of theCERT/CC vulnerability analysis team, the CERT operations staff, and the editorial and support staff of the Software Engineering Institute.—Richard D. PethiaCERT Director

This page intentionally left blank

PrefaceCERT was formed by the Defense Advanced Research Projects Agency(DARPA) in November 1988 in response to the Morris worm incident, whichbrought 10 percent of Internet systems to a halt in November 1988. CERTis located in Pittsburgh, Pennsylvania, at the Software Engineering Institute(SEI), a federally funded research and development center sponsored by theU.S. Department of Defense.The initial focus of CERT was incident response and analysis. Incidentsinclude successful attacks such as compromises and denials of service, as wellas attack attempts, probes, and scans. Since 1988, CERT has received morethan 22,665 hotline calls reporting computer security incidents or requestinginformation 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 theInternet and interconnected information systems. Analysis indicates that themajority of incidents is caused by trojans, social engineering, and the exploitation of software vulnerabilities, including software defects, design decisions,configuration decisions, and unexpected interactions among systems. CERTmonitors public sources of vulnerability information and regularly receivesreports of vulnerabilities. Since 1995, more than 16,726 vulnerabilities havebeen reported. When a report is received, CERT analyzes the potential vulnerability and works with technology producers to inform them of securitydeficiencies in their products and to facilitate and track their responses tothose problems.11. CERT interacts with more than 1,900 hardware and software developers.xxi

xxiiPrefaceSimilar to incident reports, vulnerability reports continue to grow at analarming rate.2 While managing vulnerabilities pushes the process upstream,it is again insufficient to address the issues of Internet and information systemsecurity. To address the growing number of both vulnerabilities and incidents,it is increasingly apparent that the problem must be attacked at the source byworking to prevent the introduction of software vulnerabilities during softwaredevelopment and ongoing maintenance. Analysis of existing vulnerabilitiesindicates that a relatively small number of root causes accounts for the majorityof vulnerabilities. The goal of this book is to educate developers about these rootcauses and the steps that can be taken so that vulnerabilities are not introduced.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trade-marks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed

Related Documents:

8 Bernd Girod: EE368b Image and Video Compression Introduction no. 15 Outline EE368b n Some fundamental results of information theory n Scalar quantization and vector quantization n Human visual perception n Predictive coding n Transform coding n Resolution pyramids and subband coding n Interframe coding n Motion estimation n Motion compensated coding n Coding standards JPEG, H.261, H.263 and MPEG

a speci c, commonly used, case of secure computation. To implement secure computation and secure key storage on mobile platforms hardware solutions were invented. One commonly used solution for secure computation and secure key storage is the Secure Element [28]. This is a smart card like tamper resistant

Coding ClinicReferences 1 Injury and Poisoning Coding Clinic 4Q 2008 ICD-9-CM Official Guidelines for Coding and Reporting Effective October 1, 2008 Chapter 17: Injury and Poisoning (800-999) Coding of Injuries When coding injuries, assign separate codes for ea

Source Coding Techniques 1. Fixed Length Coding In fixed length coding technique all symbols assigned with equal length because the coding don’t take the probability in account. The benefit of the fixed length code is ease of applied (easy in coding and decoding) Example1: Let x { x 1,x 2, ,x 16} where pi 1/16 for all i , find ζ

1.2 Employment outcomes of coding bootcamp training 2 2 Employment and the coding skills shortage 5 2.1 Background: ICTs and employment 6 2.2 ICT skills shortages 7 2.3 Summary 13 3 Learning to code: Adoption of the coding bootcamp model 13 3.1 Coding bootcamp models in developing countries 14 3.2 Coding bootcamp business models 18

CERT C Coding Standard The CERT C Secure Coding Standard was developed at the request of, and in concert with, the C Standards Committee. The 1st edition (a/ka/ CERT C:2008) was published in 14 October 2008. The 2nd edition of The CERT C Coding Standard (a/k/a CERT C:2014) was published in 2014. updated to support C11

Secure Shell is a protocol that provides authentication, encryption and data integrity to secure network communications. Implementations of Secure Shell offer the following capabilities: a secure command-shell, secure file transfer, and remote access to a variety of TCP/IP applications via a secure tunnel.

64. 64. Abstract. This design guide details the secure data center solution based on the Cisco Application Center Infrastructure (ACI). The Cisco Secure Firewall and Cisco Secure Application Deliver Controller (ADC) solutions are used to secure access to the workloads in an ACI data center. Target Audience.