Secure Coding in C and C++ String VulnerabilitiesNoteIssuesStringsC-Style StringsC++ StringsCommon String Manipulation ErrorsUnbounded String CopiesCopying and ConcatenationSimple SolutionC++ Unbounded CopySlide 12Null-Termination ErrorsFrom ISO/IEC 9899:1999String TruncationWrite Outside Array BoundsOff-by-One ErrorsImproper Data SanitizationProgram StacksStack SegmentStack FramesSubroutine CallsSubroutine InitializationSubroutine ReturnReturn to Calling FunctionExample ProgramStack Before Call to IsPasswordOK()Stack During IsPasswordOK() CallStack After IsPasswordOK() CallWhat is a Buffer Overflow?Buffer OverflowsSmashing the StackThe Buffer Overflow 1The Buffer Overflow 2The VulnerabilityWhat Happened ?String AgendaCode InjectionMalicious Argument./vulprog < exploit.binMal Arg Decomposed 1Slide 42Mal Arg Decomposed 2Mal Arg Decomposed 3Malicious CodeSample Shell CodeCreate a ZeroShell CodeSlide 49Slide 50Arc Injection (return-into-libc)Vulnerable ProgramExploitStack Before and After Overflowget_buff() ReturnsSlide 56Slide 57Slide 58f() ReturnsSlide 60Slide 61Slide 62g() ReturnsSlide 64Slide 65Slide 66Why is This Interesting?Mitigation StrategiesStatic approach Statically Allocated BuffersInput ValidationStatic Prevention Strategiesstrlcpy() and strlcat()Size MattersString Truncationstrlcpy() and strlcat() SummarySlide 76ISO/IEC “Security” TR 24731ISO/IEC “Security” TR 24731 Goalsstrcpy_s() Functionstrcpy_s() ExampleISO/IEC TR 24731 SummaryDynamic approach Dynamically Allocated BuffersPrevention strategies SafeStrsafestr_t typeError HandlingSafeStr ExampleManaged StringsBlack ListingWhite ListingString SummarySecure Coding in C and C++String VulnerabilitiesLecture 4Jan 25, 2011Acknowledgement: These slides are based on author Seacord’s original presentationNoteIdeas presented in the book generalize but examples are specific toMicrosoft Visual StudioLinux/GCC32-bit Intel Architecture (IA-32)IssuesStringsBackground and common issuesCommon String Manipulation ErrorsString VulnerabilitiesMitigation StrategiesStringsComprise most of the data exchanged between an end user and a software systemcommand-line argumentsenvironment variablesconsole inputSoftware vulnerabilities and exploits are caused by weaknesses instring representationstring managementstring manipulationC-Style StringsStrings are a fundamental concept in software engineering, but they are not a built-in type in C or C++.C-style strings consist of a contiguous sequence of characters terminated by and including the first null character. A pointer to a string points to its initial character. String length is the number of bytes preceding the null characterThe string value is the sequence of the values of the contained characters, in order.The number of bytes required to store a string is the number of characters plus one (x the size of each character)h e l l o \0lengthC++ StringsThe standardization of C++ has promoted the standard template class std::basic_string and its char instantiation std::string The basic_string class is less prone to security vulnerabilities than C-style strings.C-style strings are still a common data type in C++ programsImpossible to avoid having multiple string types in a C++ program except in rare circumstances there are no string literals no interaction with the existing libraries that accept C-style strings OR only C-style strings are usedCommon String Manipulation ErrorsProgramming with C-style strings, in C or C++, is error prone. Common errors includeUnbounded string copiesNull-termination errorsTruncationWrite outside array boundsOff-by-one errorsImproper data sanitizationUnbounded String CopiesOccur when data is copied from a unbounded source to a fixed length character array1.intmain(void){2.charPassword[80];3.puts("Enter8characterpassword:");4.gets(Password);...5.}Copying and Concatenation It is easy to make errors when copying and concatenating strings because standard functions do not know the size of the destination buffer1.intmain(intargc,char*argv[]){2.charname[2048];3.strcpy(name,argv[1]);4.strcat(name,"=");5.strcat(name,argv[2]);...6.}Simple SolutionTest the length of the input using strlen() and dynamically allocate the memory 1.intmain(intargc,char*argv[]){2.char*buff=(char*)malloc(strlen(argv[1])+1);3.if(buff!=NULL){4.strcpy(buff,argv[1]);5.printf("argv[1]=%s.\n",buff);6.}7.else{/*Couldn'tgetthememory-recover*/8.}9.return0;10.}C++ Unbounded CopyInputting more than 11 characters into following the C++ program results in an out-of-bounds write:1.#include<iostream.h>2.intmain(void){3.charbuf[12];4.cin>>buf;5.cout<<"echo:"<<buf<<endl;6.}1.#include<iostream.h>2.intmain(){3.charbuf[12];3.cin.width(12);4.cin>>buf;5.cout<<"echo:"<<buf<<endl;6.}Simple SolutionThe extraction operation can be limited to a specified number of characters if ios_base::width is set to a value>0After a call to the extraction operation the value of the width field is reset to 0Null-Termination ErrorsAnother common problem with C-style strings is a failure to properly null terminate intmain(intargc,char*argv[]){chara[16];charb[16];charc[32];strcpy(a,"0123456789abcdef“);strcpy(b,"0123456789abcdef”);strcpy(c,a);..}From ISO/IEC 9899:1999The strncpy function char*strncpy(char*restricts1,constchar*restricts2,size_tn);copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1*)*Thus, if there is no null character in the first n characters of the array pointed to by s2, the result will not be null-terminated.String TruncationFunctions that restrict the number of bytes are
View Full Document