You are on page 1of 44

DRAFT Secure C++ Coding Standards & Guidelines

Version 0.1 6 December 00!

Date o% C"ange Created by OCIO Security 6 Dec 2007 and SDMG Standards Divsion C"ange#Version $umber Table of Contents

Sections C"anged All

Descri&tion Initial Submission

'erson (ntering C"ange Pam Woodall and ob ro!n

D"A#$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%& Secure C'' Codin( %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%& Standards ) Guidelines%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%& $able o* Contents%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%2 & Introduction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%+ &%& Secure C'' Codin( Practices%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%+ &%2 Strin( Mani,ulation%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%6 &%2%& C'' std--strin(%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%6 &%& "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.0 2 /ISO0I1C 223ISO0I1C% ISO0I1C 2422 Second edition &2225&250& Pro(rammin( lan(ua(es 6 C% International Or(ani7ation *or Standardi7ation8 &222%/ISO0I1C 2439oint $ec:nical Committee ISO0I1C 9$CI; International Or(ani7ation *or Standardi7ation; and International 1lectrotec:nical Commission% Pro(rammin( <an(ua(es 6 C''% Geneva8 S!it7erland- ISO0I1C8 &224%/=ie(a 0>3=ie(a8 9o:n ) Messier8 Matt% Secure Pro(rammin( Coo?boo? *or C and C''- "eci,es *or Cry,to(ra,:y8 Aut:entication8 @et!or?in(8 In,ut =alidation ) More% Sebasto,ol8 CA- OA"eilly8 200> BIS @- 05+265 00>2.5>C%Pearson 1ducation8 Inc% Co,yri(:t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.0 &%2%2 *(etsBC and (etsDsBC%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%4 2%& "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.0 > /ISO0I1C 223ISO0I1C% ISO0I1C 2422 Second edition &2225&250& Pro(rammin( lan(ua(es 6 C% International Or(ani7ation *or Standardi7ation8 &222%/ISO0I1C 0.3ISO0I1C% ISO0I1C WD$" 2.7>& S,eci*ication *or Secure C <ibrary #unctions% International Or(ani7ation *or Standardi7ation8 200.%Pearson 1ducation8 Inc% Co,yri(:t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.0 &%2%> memc,yDsBC and memmoveDsBC%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&0 >%& "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.0 . /ISO0I1C 223ISO0I1C% ISO0I1C 2422 Second edition &2225&250& Pro(rammin( lan(ua(es 6 C% International Or(ani7ation *or Standardi7ation8 &222%/ISO0I1C 0.3ISO0I1C% ISO0I1C WD$" 2.7>& S,eci*ication *or Secure C <ibrary #unctions% International Or(ani7ation *or Standardi7ation8 200.%Pearson 1ducation8 Inc% Co,yri(:t%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.& &%2%. "untime Protection%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&2 &%2%+ Com,iler5Generated "untime C:ec?s %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&> &%2%6 @on51Eecutable Stac?s %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&> &%2%7 Stac?(a, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&> &%2%4 "untime ounds C:ec?ers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&. &%2%2 Canaries %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&+

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

&%2%&0 Stac? Smas:in( Protector BProPoliceC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&+ &%2%&& <ibsa*e and <ib=eri*y %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&7 .%& "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.& + / aratloo 003 aratloo8 A%; Sin(:8 @%; ) $sai8 $% F$rans,arent "un5$ime De*ense A(ainst Stac? Smas:in( Attac?s8G 2+&5262% Proceedin(s o* 2000 HS1@II Annual $ec:nical Con*erence% San Die(o8 CA8 9une &452>8 2000% er?eley8 CA- HS1@II Association8 2000%/ ulba 003 ulba ) Jil>r% y,assin( Stac?Guard and Stac?S:iel BPrac?8 =olume 0Ea Issue 0E>4 0+%0&%2000 0E0+/0E&03C% :tt,-00!!!%,:rac?%or(0,:rac?0+60 ,+650E0+ B2000C%/Co!an 243Co!an8 C%; Pu8 C%- Maier8 D%; Kinton8 K%; Wal,ole8 9%; a??e8 P%; eattie8 S%; Grier8 A%; Wa(le8 P%; ) L:an(8 M% FStac?(uard- Automatic ada,tive detection and ,revention o* bu**er5over*lo! attac?s8G 6>577% Proceedin(s o* t:e Sevent: HS1@II Security Sym,osium% San Antonio8 $I8 9anuary 265228 &224% er?eley8 CA- HS1@II Association8 &224%/Co!an 003Co!an8 Cris,in; Wa(le8 Perry; Pu8 Calton; eattie8 Steve; ) Wal,ole8 9onat:an% F u**er Over*lo!s- Attac?s and De*enses *or t:e =ulnerability o* t:e Decade8G &&25&22% Proceedin(s o* t:e DA"PA In*ormation Survivability Con*erence and 1E,osition BDISC1IN00C% Kilton Kead Island8 SC8 9anuary 2+5278 2000% <os Alamitos8 CA- I111 Com,utin( Society8 2000%/de "aadt 0>3$:eo de "aadt8 Advances in O,en SD8 ,resented at CanSecWest8 =ancouver8 Canada% A,ril 200> :tt,-00!!!%o,enbsd%or(0,a,ers0cs!0>0m(,0000&%:tml/1to: 0.31to:8 Kiroa?i ) Ooda8 J% Protectin( *rom stac?5smas:in( attac?s% :tt,-00 !!!%researc:%ibm%com0trl0,roPects0security0ss,0main%:tml B200.C% /9ones 2739ones8 "ic:ard W% M% ) Jelley8 Paul K% 9% F ac?!ards5com,atible bounds c:ec?in( *or arrays and ,ointers in C ,ro(rams8G &>526% Proceedin(s o* t:e $:ird International Wor?s:o, on Automatic Debu((in( BAAD1 HGN27C% <in?o,in(8 S!eden8 May 265278 &227% <in?o,in(8 S!eden<in?o,in(s Hniversitet8 &227%/"u!ase 0.3"u!ase8 OlatunPi ) <am8 M% S% FA Practical Dynamic u**er Over*lo! Detector8G &+25&62% Proceedin(s o* t:e &&t: Annual @et!or? and Distributed System Security Sym,osium% San Die(o8 CA8 #ebruary +56 200.% "eston8 =A- Internet Society8 200.% :tt,-00sui*%stan*ord%edu0,a,ers0tunPi0.%,d*%/Seacord 0+3"obert C% Seacord% Secure Codin( in C and C''% oston8 MA- Addison5Wesley8 200+%/Wa(le 0>3Wa(le8 Perry ) Co!an8 Cris,in% FStac?Guard- Sim,le Stac? Smas: Protection *or GCC8G 2.>52+6% Proceedin(s o* t:e GCC Develo,ers Summit% Otta!a8 Ontario8 Canada8 May 2+5278 200>%/Wilander 0>3Wilander8 9% ) Jam?ar8 M% FA Com,arison o* Publicly Available $ools *or Dynamic u**er Over*lo! Prevention8G &.25&62% Proceedin(s o* t:e &0t: @et!or? and Distributed System Security Sym,osium% San Die(o8 Cali*ornia8 #ebruary 6578 200>% "eston8 =A- Internet Society8 200>% :tt,-00!!!%ida%liu%se0QPo:!i0 researc:D,ublications0,a,erDndss200>DPo:nD!ilander%,d*%Pearson 1ducation8 Inc% Co,yri(:t%%%%%%%%%%%%%%.2 &%2%&2 Sa*eStr%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&7 +%& "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.> &%2%&> strc,yDsBC and strcatDsBC%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&2 +%2 "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.> &%2%&. strc,yBC and strcatBC%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%2& +%> "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.> &%2%&+ O,en SDAs strlc,yBC and strlcatBC%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%22 +%. "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.> &%2%&6 strnc,yDsBC and strncatDsBC%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%2> +%+ "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.> &%2%&7 strnc,yBC and strncatBC%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%26 +%6 "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.> &%2%&4 Strsa*e%:%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%27 Pa(e > o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

+%7 "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.> +%4 "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.. 2 Dynamic Memory Mana(ement%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>0 2%& Guard Pa(es%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>& +%2 "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.. 2%2 Kea, Inte(rity Detection%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>2 +%&0 "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.. 2%> @ull Pointers%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>> +%&& "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.. 2%. P:?malloc%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>. +%&2 "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.. 2%+ "andomi7ation%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>6 +%&> "e*erences %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%..

Pa(e . o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

ntroduction

A,,lication Code de*ects are a ,rimary cause o* commonly eE,loited so*t!are vulnerabilities% A number o* security eE,erts :ave analy7ed t:ousands o* vulnerability re,orts8 and determined t:at most a,,lication vulnerabilities stem *rom a relatively small number o* common codin( errors% y identi*yin( insecure codin( ,ractices and develo,in( secure alternatives8 develo,ers can ta?e ,ractical ste,s to reduce or eliminate vulnerabilities in t:e SD<C be*ore de,loyment% $:e intent o* t:is Secure Codin( Standard is to ,rovide direction and (uidance to HSP$O a,,lication develo,ers and ,ro(rammers to enable t:em to em,loy secure ,ro(rammin( rules and ,ractices in order to deliver sa*e8 reliable code% ConseRuently8 t:e rules contained in t:is document are reRuired *or all HSP$O code develo,ment% $:e ,rimary (oal o* de*inin( t:e Secure Codin( Standard is to or(ani7e sets o* codin( rules t:at are necessary to ensure security and can be used to :el, develo,ers understand t:e ?inds o* errors t:at :ave an im,act on security% y better understandin( :o! systems *ail8 develo,ers !ill better analy7e t:e systems t:ey create8 more readily identi*y and address security ,roblems !:en t:ey see t:em8 and (enerally avoid re,eatin( t:e same mista?es in t:e *uture%

1.1 Secure C++ Coding !ractices


"obert C% Seacord8 So*t!are 1n(ineerin( Institute /vita3 Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 Most so*t!are vulnerabilities are t:e result o* small but reoccurrin( ,ro(rammin( errors t:at could be easily avoided i* ,ro(rammers learned to reco(ni7e t:em and understand t:eir ,otential :arm% In ,articular8 t:e C and C'' ,ro(rammin( lan(ua(es :ave ,roved :i(:ly susce,tible to t:ese classes o* errors% $:is ?no!led(e area o* t:e uild Security In !eb site describes codin( ,ractices t:at can be used to miti(ate a(ainst t:ese common ,roblems in C and C''% Most o* t:e documents in t:is ?no!led(e area are eEcer,ted *rom t:e C1"$ boo? Secure Codin( in C and C'' /&38 !ritten by "obert C% Seacord !it: contributions *rom ot:er members o* t:e C1"$ Coordination Center% $:e miti(ation strate(ies included in t:is ?no!led(e area deal ,rimarily !it: vulnerabilities resultin( *rom ,ro(rammin( errors in strin( mani,ulation8 inte(er o,erations8 and dynamic memory mana(ement% #or a more com,lete descri,tion o* common ,ro(rammin( errors and t:e resultin( vulnerabilities8 ,lease see Secure Codin( in C and C''% Secure codin( reRuires an understandin( o* common ,ro(rammin( errors t:at lead to so*t!are vulnerabilities and t:e ?no!led(e and use o* alternative a,,roac:es t:at are less error ,rone% Secure codin( can also bene*it *rom t:e ,ro,er use o* so*t!are develo,ment tools8 includin( com,ilers% Com,ilers ty,ically :ave o,tions t:at allo! increased or s,eci*ic dia(nostics to be ,er*ormed on code durin( com,ilation% "esolvin( t:ese !arnin(s Bby correctin( t:e ,roblem or determinin( t:at t:e

Pa(e + o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

!arnin( is su,er*luousC can im,rove t:e security o* your de,loyed so*t!are system% Com,ilers can also ,rovide o,tions t:at in*luence runtime settin(s8 suc: as t:e 0GS *la( in Microso*t =isual Studio% Hnderstandin( available com,iler o,tions and ma?in( in*ormed decisions about !:ic: o,tions to use and !:ic: to omit can :el, eliminate vulnerabilities and miti(ate a(ainst runtime eE,loitation o* undiscovered or unresolved vulnerabilities% An eEam,le o* t:e use o* com,iler c:ec?s to miti(ate a(ainst inte(er vulnerabilities is described in Com,iler C:ec?s% 1Eam,les o* usin( ot:er static and dynamic analysis tools to discover and miti(ate vulnerabilities are described in "untime Analysis $ools and Kea, Inte(rity Detection% Miti(ation strate(ies are described8 includin( security8 ,er*ormance8 availability8 ease o* use8 and ot:er ?no!n Ruality attributes% We do not attem,t to describe t:e conditions under !:ic: one miti(ation strate(y is ,re*erred to anot:er% Instead8 !e assume t:at you Bt:e customer o* t:e in*ormationC ?no! !:at your reRuirements and constraints are and can ma?e an a,,ro,riate selection based on your analysis o* t:is in*ormation and t:e in*ormation contained in t:e re*erenced resources%

1. String )ani&ulation 1. .1 C++ std**string


Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 C'' ,ro(rammers :ave t:e o,tion o* usin( t:e standard std--strin( class de*ined in ISO0I1C &.442% $:e std--strin( (enerally ,rotects a(ainst bu**er over*lo!% De+elo&ment Conte,t Strin( mani,ulation Tec"nolog- Conte,t C''8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Standard C strin( mani,ulation *unctions are ,rone to ,ro(rammer mista?es t:at can result in bu**er over*lo! vulnerabilities% Descri&tion

Pa(e 6 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

Hnbounded strin( co,ies are not limited to t:e C ,ro(rammin( lan(ua(e% #or eEam,le8 i* a user in,uts more t:an && c:aracters into t:e C'' ,ro(ram s:o!n in #i(ure &8 an out5o*5bounds !rite !ill result% Figure 1. Vulnerable &rogram combining C and C++ standard strings & Sinclude Tiostream%:U int mainBC V c:ar bu*/&23; cin UU bu*; + cout TT Wec:o- W TT bu* TT endl; X $:e standard obPect cin is an instantiation o* t:e istream class% $:e istream class ,rovides member *unctions to assist in readin( and inter,retin( in,ut *rom a stream bu**er% All *ormatted in,ut is ,er*ormed usin( t:e eEtraction o,eratorUU% C'' also de*ines eEternal o,eratorUU overloaded *unctions t:at are (lobal *unctions and not members o* istream8 includin( istream) o,eratorUU Bistream) is8 c:arY strC; $:is o,erator eEtracts c:aracters and stores t:em in successive locations startin( at t:e location ,ointed to by str% 1Etraction ends !:en t:e neEt element is eit:er a valid !:ite s,ace or a null c:aracter8 or i* t:e end5o*5*ile is reac:ed% A null c:aracter is automatically a,,ended a*ter t:e eEtracted c:aracters% $:e eEtraction o,eration can be limited to a s,eci*ied number o* c:aracters Bt:ereby avoidin( t:e ,ossibility o* an out5o*5bounds !riteC i* t:e field width in:erited member BiosDbase--!idt:C is set to a value (reater t:an 0% In t:is case8 t:e eEtraction ends one c:aracter be*ore t:e count o* c:aracters eEtracted reac:es t:e value o* t:e *ield !idt:8 leavin( s,ace *or t:e endin( null c:aracter% A*ter a call to t:is eEtraction o,eration8 t:e value o* t:e *ield !idt: is reset to 0% #i(ure 2 contains an im,roved version o* t:e #i(ure & ,ro(ram t:at sets t:e *ield !idt: member to t:e len(t: o* t:e c:aracter array% Figure . (,tracting c"aracters using t"e %ield /idt" member & Sinclude Tiostream%:U int mainBC V c:ar bu*/&23; cin%!idt:B&2C; + cin UU bu*; cout TT Wec:o- W TT bu* TT endl; X W:ile settin( t:e *ield !idt: solves t:e bu**er over*lo! ,roblem8 it does not address t:e issue o* truncation% $:ere*ore8 uneE,ected ,ro(ram be:avior could result !:en t:e maEimum *ield !idt: is

Pa(e 7 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

reac:ed and t:e remainder o* c:aracters in t:e in,ut stream are consumed by t:e next call to t:e eEtractor o,erator% C'' ,ro(rammers :ave t:e o,tion o* usin( t:e standard std--strin( class de*ined in ISO0I1C &.442 /ISO0I1C 243% $:e std--strin( class is t:e c:ar instantiation o* t:e std--basicDstrin( tem,late class8 and it uses a dynamic a,,roac: to strin(s in t:at memory is allocated as reRuired6meanin( t:at in all cases8 si7eBC TZ ca,acityBC% $:e std--strin( class is convenient because t:e lan(ua(e su,,orts t:e class directly% Also8 many eEistin( libraries already use t:is class8 !:ic: sim,li*ies inte(ration% #i(ure > s:o!s anot:er solution to eEtractin( c:aracters *rom cin into a strin(8 usin( std--strin( instead o* a c:aracter array% $:is ,ro(ram is sim,le8 ele(ant8 :andles bu**er over*lo!s and strin( truncation8 and be:aves in a ,redictable *as:ion% Figure 0. (,tracting c"aracters %rom cin into a std**string ob1ect & Sinclude TiostreamU Sinclude Tstrin(U usin( names,ace std; int mainBC V + strin( str; cin UU str; cout TT Wstr &- W TT str TT endl; X $:e std--strin( (enerally ,rotects a(ainst bu**er over*lo!8 but t:ere are still situations in !:ic: ,ro(rammin( errors can lead to bu**er over*lo!s% W:ile C'' (enerally t:ro!s an outDo*Dran(e eEce,tion !:en an o,eration re*erences memory outside t:e bounds o* t:e strin(8 t:e subscri,t o,erator /3 B!:ic: does not ,er*orm bounds c:ec?in(C does not /=ie(a 0>3% Anot:er ,roblem occurs !:en convertin( std--strin( obPects to C5style strin(s% I* you use strin(--cDstrBC to do t:e conversion8 you (et a ,ro,erly null5terminated C5style strin(% Ko!ever8 i* you use strin(--dataBC8 !:ic: !rites t:e strin( directly into an array Breturnin( a ,ointer to t:e arrayC8 you (et a bu**er t:at is not null terminated% $:e only di**erence bet!een cDstrBC and dataBC is t:at cDstrBC adds a trailin( null byte% #inally8 many eEistin( C'' ,ro(rams and libraries :ave t:eir o!n strin( classes% $o use t:ese libraries8 you may :ave to use t:ese strin( ty,es or constantly convert bac? and *ort:% Suc: libraries are o* varyin( Ruality !:en it comes to security% It is (enerally best to use t:e standard library B!:en ,ossibleC or to understand t:e semantics o* t:e selected library% Generally s,ea?in(8 libraries s:ould be evaluated based on :o! easy or com,leE t:ey are to use8 t:e ty,e o* errors t:at can be made8 :o! easy t:ese errors are to ma?e8 and !:at t:e ,otential conseRuences may be% i

1. .

%gets23 and gets4s23

Pa(e 4 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

"obert C% Seacord8 So*t!are 1n(ineerin( Institute /vita3 $:e (etsBC *unction is a common source o* bu**er over*lo! vulnerabilities and s:ould never be used% $:e *(etsBC and (etsDsBC *unctions eac: o**er a more secure solution% De+elo&ment Conte,t "eadin( strin(s *rom standard in,ut Tec"nolog- Conte,t C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess% Ris. $:e (etsBC *unction is a common source o* bu**er over*lo! vulnerabilities and s:ould never be used% Pro(rams runnin( !it: elevated ,rivile(es8 includin( ,ro(rams t:at are out!ard *acin(8 can be used *or ,rivile(e escalation or to launc: a remote s:ell% Descri&tion $:ere are t!o alternative *unctions t:at can be used- *(etsBC and (etsDsBC% #i(ure & s:o!s :o! all t:ree *unctions are used% $:e *(etsBC *unction is de*ined in C22 /ISO0I1C 223 and :as similar be:avior to (etsBC % $:e *(etsBC *unction acce,ts t!o additional ar(uments- t:e number o* c:aracters to read and an in,ut stream% y s,eci*yin( stdin as t:e stream8 *(etsBC can be used to simulate t:e be:avior o* (etsBC 8 as s:o!n in lines 65&0 o* #i(ure &% $:e *(etsBC *unction8 :o!ever8 retains t:e ne!5line c:aracter8 !:ic: means t:at t:e *unction cannot be used as a direct re,lacement *or (etsBC% $:e *(etsBC *unction reads at most one less t:an t:e number o* c:aracters s,eci*ied *rom t:e stream into an array% @o additional c:aracters are read a*ter a ne!5line c:aracter or a*ter end5o*5*ile% A null c:aracter is !ritten immediately a*ter t:e last c:aracter read into t:e array% $:e C22 standard does not de*ine :o! *(etsBC be:aves i* t:e number o* c:aracters to read is s,eci*ied as 7ero or i* t:e ,ointer to t:e c:aracter array to be !ritten to is a null% $:e (etsDsBC *unction is de*ined by ISO0I1C WD$" 2.7>& to ,rovide a com,atible version o* (etsBC t:at is less ,rone to bu**er over*lo!% $:is *unction is closer to a direct re,lacement *or t:e (etsBC *unction in t:at it reads only *rom t:e stream ,ointed to by stdin% $:e (etsBC *unction8 :o!ever8 acce,ts an additional ar(ument o* rsi7eDt% I* t:is ar(ument is eRual to 7ero or (reater t:an "SIL1DMAI or i* t:e ,ointer to t:e c:aracter array to be !ritten to is a null8 t:en t:ere is dia(nosed unde*ined be:avior8 and Pa(e 2 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

no in,ut is ,er*ormed and t:e c:aracter array is not modi*ied% Ot:er!ise8 t:e *unction reads8 at most8 one less t:an t:e number o* c:aracters s,eci*ied8 and a null c:aracter is !ritten immediately a*ter t:e last c:aracter read into t:e array% <ines &&5&+ o* #i(ure & s:o! :o! (etsDsBC can be used in a ,ro(ram% Figure 1. 5se o% gets23 +s. %gets23 +s. gets4s23 &% Sde*ine H##SIL1 4 2% int DtmainBint ar(c8 D$CKA"Y ar(v/3CV >% c:ar bu**/ H##SIL13; 00 insecure use o* (etsBC .% (etsBbu**C; +% ,rint*BW(ets- [s%\nW8 bu**C; 6% i* B*(etsBbu**8 H##SIL18 stdinC ZZ @H<<C V 7% ,rint*BWread error%\nWC; 4% abortBC; 2% X &0% ,rint*BW*(ets- [s%\nW8 bu**C; &&% i* B(etsDsBbu**8 H##SIL1C ZZ @H<<C V &2% ,rint*BWdia(nosed unde*ined be:avior%\nWC; &>% abortBC; &.% X &+% ,rint*BW(etsDs- [s%\nW8 bu**C; &6% return 0; &7% X $:e (etsDsBC *unction returns a ,ointer to t:e c:aracter array i* success*ul% A @H<< ,ointer is returned i* t:e *unction ar(uments !ere invalid8 an end5o*5*ile is encountered and no c:aracters :ave been read into t:e array8 or i* a read error occurs durin( t:e o,eration% $:e (etsDsBC *unction only succeeds i* it reads a com,lete line Bt:at is8 it reads a ne!line c:aracterC% I* a com,lete line cannot be read8 t:e *unction returns @H<< and sets t:e bu**er to t:e null strin(% $:e *unction also clears t:e in,ut stream to t:e neEt ne!line c:aracter% $:e *(etsBC and (etsDsBC *unctions can still lead to bu**er over*lo!s i* t:e s,eci*ied number o* c:aracters to in,ut eEceeds t:e len(t: o* t:e destination bu**er% ii

1. .0 memc&-4s23 and memmo+e4s23


Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 Substitutin( t:e memc,yDsBC and memmoveDsBC *unctions *or t:e memc,yBC and memmoveBC *unctions can :el, (uard a(ainst so*t!are vulnerabilities%

Pa(e &0 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

De+elo&ment Conte,t Co,yin( c:aracters *rom one memory location to anot:er% Tec"nolog- Conte,t C''8 C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. $:e memc,yBC and memmoveBC *unctions are a source o* bu**er over*lo! vulnerabilities% Descri&tion Substitutin( t:e memc,yDsBC and memmoveDsBC *unctions *or t:e memc,yBC and memmoveBC *unctions can :el, (uard a(ainst so*t!are vulnerabilities% $:e memc,yDsBC and memmoveDsBC *unctions de*ined in ISO0I1C WD$" 2.7>& are similar to t:e corres,ondin( memc,yBC and memmoveBC *unctions but ,rovide some additional sa*e(uards% $:ese *unctions :ave an additional ar(ument t:at s,eci*ies t:e maEimum si7e o* t:e destination8 and t:ey also include a return value t:at indicates !:et:er t:e o,eration !as success*ul% A return value o* 7ero indicates t:at t:e o,eration succeeded% A non57ero return value indicates t:at t:e o,eration *ailed because it !as dia(nosed to :ave an unde*ined be:avior due to an invalid in,ut ar(ument% $:e memc,yDsBC and memmoveDsBC *unctions !ill be dia(nosed to :ave an unde*ined be:avior i* eit:er t:e source or destination ,ointer is null8 i* t:e s,eci*ied number o* c:aracters to co,y or move is (reater t:an t:e maEimum si7e o* t:e destination bu**er8 or t:e number o* c:aracters to co,y or move or t:e maEimum si7e o* t:e destination bu**er is (reater t:an "SIL1DMAI %& Additionally8 t:e memc,yDsBC *unction !ill be dia(nosed to :ave an unde*ined be:avior i* t:e memory re(ions o* t:e obPects overla,% I* t:e o,eration is dia(nosed to :ave an unde*ined be:avior8 7eros !ill be stored in t:e *irst c:aracters o* t:e destination i* t:e destination ,ointer is not eRual to null and t:e si7e o* t:e destination bu**er is less t:an or eRual to "SIL1DMAI % $:e memc,yDsBC *unction :as better ,er*ormance t:an t:e memmoveDsBC but :as additional ris?s% $:ere is no security related reason to ,re*er memc,yDsBC to memmoveDsBC% $:e memc,yDsBC and memmoveDsBC *unctions are used to co,y c:aracters *rom one memory location to anot:er% $:e !memc,yDsBC and !memmoveDsBC *unctions are used to co,y !ide c:aracters%iii

Pa(e && o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

1. .6 Runtime 'rotection
Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 $:ere are a number o* runtime solutions t:at can detect stac? corru,tion and bu**er overruns or (uard a(ainst attac?s% $:ese solutions ty,ically terminate t:e ,ro(ram !:en an anomaly is detected8 ,reventin( t:e eEecution o* arbitrary code% De+elo&ment Conte,t Pro(ram runtime c:ec?s and ,rotection tec:niRues t:at can be used to detect stac? corru,tion and bu**er overruns or (uard a(ainst attac?s Tec"nolog- Conte,t C8 H@II8 WI@>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Pro(rammin( errors can result in bu**er over*lo! vulnerabilities% Descri&tion $:ere are a number o* runtime solutions t:at can detect stac? corru,tion and bu**er overruns or (uard a(ainst attac?s% $:ese solutions ty,ically terminate t:e ,ro(ram !:en an anomaly is detected8 ,reventin( t:e eEecution o* arbitrary code% $:ey are not e**ective at sto,,in( denial5o*5service BDoSC attac?s unless t:e ,ro(ram also includes restart ,rocessin( t:at is initiated !:en t:e ,ro(ram terminates8 !:ic: !ould limit t:e e**ectiveness o* t:e attac?% "untime ,rotection strate(ies s:ould not be used as a substitute *or eliminatin( t:e source o* t:e vulnerability8 as t:ese solutions are o*ten ine**ective% $:ere are o*ten many !ays to eE,loit a vulnerability8 and many runtime ,rotection sc:emes only eliminate a subset o* t:ese% "untime ,rotection strate(ies may be em,loyed as ,art o* a de*ense5in5de,t: strate(y to miti(ate undetected vulnerabilities but s:ould not be solely relied on as a so*t!are assurance strate(y% Several runtime solutions are described neEt%

Pa(e &2 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

1. .7 Com&iler8Generated Runtime C"ec.s


Microso*t =isual C'' ,rovides native runtime c:ec?s to catc: common runtime errors suc: as stac? ,ointer corru,tion and overruns o* local arrays% $:e 0GS o,tion enables canaries and ,er*orms some stac? reor(ani7ation to ,revent common eE,loits% =isual C'' also ,rovides a runtimeDc:ec?s ,ra(ma t:at disables or restores t:e 0"$C settin(s%& Stac. 'ointer Corru&tion. Stac? ,ointer veri*ication detects stac? ,ointer corru,tion% Stac? ,ointer corru,tion can be caused by a callin( convention mismatc:% #or eEam,le8 usin( a *unction ,ointer8 you call a *unction in a D<< t:at is eE,orted as DDstdcall8 but you declare t:e ,ointer to t:e *unction as cdecl% 9+erruns o% :ocal Arra-s. $:e 0"$Cs o,tion enables stac? *rame run5time error c:ec?in( *or !rites outside t:e bounds o* local variables suc: as arrays% $:e 0"$Cs o,tion does not detect overruns !:en accessin( memory t:at results *rom com,iler ,addin( !it:in a structure% Paddin( could occur by usin( ali(n8 0L,8 or ,ac?8 or i* you order structure elements in a !ay t:at reRuires t:e com,iler to add ,addin(%

1. .6 $on8(,ecutable Stac.s
@on5eEecutable stac?s are a runtime solution to bu**er over*lo!s t:at are desi(ned to ,revent eEecutable code *rom runnin( in t:e stac? se(ment% Many o,eratin( systems can be con*i(ured to use non5 eEecutable stac?s% @on5eEecutable stac?s are o*ten re,resented as a ,anacea in securin( a(ainst bu**er over*lo! vulnerabilities% Ko!ever8 non5eEecutable stac?s do not ,revent bu**er over*lo!s *rom occurrin( in t:e stac?8 :ea,8 or data se(ments% $:ey do not ,revent an attac?er *rom usin( a bu**er over*lo! to modi*y a return address8 variable8 data ,ointer8 or *unction ,ointer% @on5eEecutable stac?s do not ,revent arc inPection or inPection o* eEecution code in t:e :ea, or data se(ments% @ot allo!in( an attac?er to run eEecutable code on t:e stac? can ,revent t:e eE,loitation o* some vulnerabilities8 but it is o*ten only a minor inconvenience to an attac?er% De,endin( on :o! t:ey are im,lemented8 non5eEecutable stac?s can a**ect ,er*ormance% @on5 eEecutable stac?s can also brea? ,ro(rams t:at eEecute code in t:e stac? se(ment8 includin( <inuE si(nal delivery and Gnu Com,iler Collection BGCCC tram,olines%

1. .! Stac.ga&
Many eE,loits *or stac?5based bu**er over*lo!s rely on t:e *act t:at t:e bu**er bein( over*lo!ed is al!ays at t:e same ,lace in memory% I* t:e attac?er can over!rite t:e *unction return address8 !:ic: is at *iEed value ,ointers into t:e over*lo! bu**er8 eEecution o* t:e attac?er5su,,lied code starts% A strai(:t*or!ard solution to t:is ,roblem is to introduce a randomly si7ed (a, o* s,ace u,on allocation o* stac? memory /de "aadt 0>3%

Pa(e &> o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

$:is tec:niRue (ives a disadvanta(e to t:e attac?er !:ile !astin( at most & ,a(e o* real memory% $:is miti(ation can be easily added to <inuE systems because it reRuires only a small c:an(e to t:e ?ernel8 as s:o!n in #i(ure &% Figure 1. :inu, .ernel modi%ication to su&&ort stac.ga& &% s(a, Z S$ACJGAP<1@; 2% i* Bstac?(a,Drandom ]Z 0C s(a, 'Z Barc.randomBC Y A<IG@ O$1SC ) Bstac?(a,Drandom 5 &C; 0Y @o! c:ec? i* ar(s ) environ *it into ne! stac? Y0 >% len Z BBar(c ' envc ' 2 ' ,ac?%e,Demul5UeDar(lenC Y si7eo*Bc:ar YC ' si7eo*Blon(C ' d, ' s(a, ' si7eo*Bstruct ,sDstrin(sCC 5 ar(,;

1. .; Runtime <ounds C"ec.ers


I* usin( a ty,e5sa*e lan(ua(e suc: as 9ava or CS is im,ractical8 it may still be ,ossible to use a com,iler t:at ,er*orms array bounds c:ec?in( *or C ,ro(rams% 9ones and Jelley /9ones 273 ,ro,ose an a,,roac: *or bounds c:ec?in( usin( re*erent obPects% $:is a,,roac: is based on t:e ,rinci,le t:at an address com,uted *rom an in5bounds ,ointer must s:are t:e same re*erent obPect as t:e ori(inal ,ointer% Hn*ortunately8 t:ere are a sur,risin(ly lar(e number o* ,ro(rams t:at (enerate and store out5o*5bounds addresses and later retrieve t:ese values in t:eir com,utation !it:out causin( bu**er over*lo!s6ma?in( t:ese ,ro(rams incom,atible !it: t:is bounds5 c:ec?in( a,,roac:% $:is a,,roac: to runtime bounds c:ec?in( also :ad si(ni*icant ,er*ormance costs8 ,articularly in ,ointer5intensive ,ro(rams8 !:ere ,er*ormance may slo! do!n by u, to >0 times /Co!an 003% "u!ase and <am :ave im,roved t:e 9ones and Jelley a,,roac: in t:eir C "an(e 1rror Detector BC"1DC /"u!ase 0.3% C"1D en*orces a relaEed standard o* correctness by allo!in( ,ro(ram mani,ulations o* out5o*5bounds addresses t:at do not result in bu**er over*lo!s% $:is relaEed standard o* correctness ,rovides :i(:er com,atibility !it: eEistin( so*t!are% C"1D can be con*i(ured to c:ec? all bounds o* all data or o* strin( data only% #ull bounds c:ec?in(8 li?e t:e 9ones and Jelley a,,roac:8 im,oses si(ni*icant ,er*ormance over:ead on most ,ro(rams% <imitin( t:e bounds c:ec?in( to strin(s im,roves t:e ,er*ormance *or most ,ro(rams% Over:ead ran(es *rom &[ to &>0[ de,endin( on t:e use o* strin(s in t:e a,,lication% ounds c:ec?in( is e**ective in ,reventin( most over*lo! conditions but is not ,er*ect% $:e C"1D solution8 *or eEam,le8 is unable to detect conditions !:ere an out5o*5bounds ,ointer is cast to an inte(er8 used in an arit:metic o,eration8 and cast bac? to a ,ointer% $:e a,,roac: does ,revent over*lo!s in t:e stac?8 :ea,8 and data se(ments% C"1D !as e**ective in detectin( 20 di**erent bu**er over*lo! attac?s

Pa(e &. o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

develo,ed by Wilander and Jam?ar *or evaluatin( dynamic bu**er over*lo! detectors /Wilander 0>38 even !:en o,timi7ed to c:ec? only *or over*lo!s in strin(s% C"1D :as been mer(ed into t:e latest 9ones and Jelly c:ec?er *or GCC >%>%&8 !:ic: is currently maintained by Kerman ten ru((e%

1. .= Canaries
Canaries are anot:er mec:anism used to eliminate stac? smas:in( attac?s% Instead o* ,er*ormin( (enerali7ed bounds c:ec?in(8 canaries are used to ,rotect t:e return address on t:e stac? *rom seRuential !rites t:rou(: memory B*or eEam,le8 resultin( *rom a strc,yBCC% Canaries consist o* a :ard5to5insert or :ard5to5s,oo* value !ritten to an address belo! t:e section o* t:e stac? bein( ,rotected% A seRuential !rite !ould t:ere*ore need to over!rite t:is value on t:e !ay to t:e ,rotected re(ion% $:e canary is initiali7ed immediately a*ter t:e return address is saved and c:ec?ed immediately be*ore t:e return address is accessed% A :ard5to5insert or terminator canary consists o* *our di**erent strin( terminators BC"8 <#8 @ull8 and 5&C% $:is (uards a(ainst bu**er over*lo!s caused by strin( o,erations but not memory co,y o,erations% A :ard5to5s,oo* or random canary is basically a >25bit secret random number t:at c:an(es eac: time t:e ,ro(ram is eEecuted% $:is a,,roac: !or?s !ell as lon( as t:e canary remains a secret% Canaries are im,lemented in Stac?Guard /Co!an 243% =arious Stac?Guard versions :ave been used !it: GCC *or ImmuniE OS 6%28 7%08 and 7'% "ed Kat 7%> !ill mer(e Stac?Guard > into t:e GCC >%E mainline com,iler% Canaries :ave also been used in ProPolice and Microso*tNs =isual C'' %@et% Canaries are use*ul only a(ainst eE,loits t:at over*lo! a bu**er on t:e stac? and attem,t to over!rite t:e stac? ,ointer or ot:er ,rotected re(ion% Canaries do not ,rotect a(ainst eE,loits t:at modi*y variables8 data ,ointers8 or *unction ,ointers% Canaries do not ,revent bu**er over*lo!s *rom occurrin( in any location8 includin( t:e stac? se(ment% In *act8 neit:er t:e terminator nor random canary o**ers com,lete ,rotection a(ainst eE,loits t:at over!rite t:e return address% 1E,loits t:at !rite *our bytes directly to t:e location o* t:e return address on t:e stac? can de*eat terminator and random canaries / ulba 003% $o solve t:ese direct access eE,loits8 Stac?Guard added "andom IO" canaries /Wa(le 0>3 t:at IO" t:e return address !it: t:e canary% A(ain8 t:is !or?s !ell as lon( as t:e canary remains a secret%

1. .10 Stac. Smas"ing 'rotector 2'ro'olice3


A ,o,ular miti(ation a,,roac: derived *rom Stac?Guard is t:e GCC Stac? Smas:in( Protector BSSP8 also ?no!n as ProPoliceC /1to: 0.3% SSP is a GCC eEtension *or ,rotectin( a,,lications !ritten in C *rom t:e most common *orms o* stac? bu**er over*lo! eE,loits and is im,lemented as an intermediate lan(ua(e translator o* GCC% SSP ,rovides bu**er over*lo! detection and t:e variable reorderin( to avoid t:e corru,tion o* ,ointers% S,eci*ically8 SSP

Pa(e &+ o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

reorders local variables to ,lace bu**ers a*ter ,ointers to avoid t:e corru,tion o* ,ointers t:at could be used to *urt:er corru,t arbitrary memory locations co,ies ,ointers in *unction ar(uments to an area ,recedin( local variable bu**ers to ,revent t:e corru,tion o* ,ointers t:at could be used to *urt:er corru,t arbitrary memory locations omits instrumentation code *rom *unctions t:at contain c:aracter arrays to decrease t:e ,er*ormance over:ead

$:e SSP *eature is enabled usin( (cc o,tions% $:e 5*stac?5,rotector and 5*no5stac?5,rotector o,tions res,ectively enable and disable stac? smas:in( ,rotection% $:e 5*stac?5,rotector5all and 5*no5stac?5 ,rotector5all o,tions enable and disable t:e ,rotection o* every *unction8 not Pust t:e *unctions !it: c:aracter arrays% SSP !or?s by introducin( a (uard variable to ,revent c:an(es to t:e ar(uments8 return address8 and ,revious *rame ,ointer% Given t:e source code o* a *unction8 a ,re,rocessin( ste, inserts code *ra(ments into a,,ro,riate locations as *ollo!s

Declaration o* local variables volatile int (uard; 1ntry ,oint (uard Z (uardDvalue; 1Eit ,oint i* B(uard ]Z (uardDvalueC V 0Y out,ut error lo( Y0 0Y :alt eEecution Y0 X

A random number is used as t:e (uard value at t:e initiali7ation time o* t:e a,,lication8 ,reventin( discovery by a non5,rivile(ed user% SSP also ,rovides a sa*er stac? structure8 as s:o!n in #i(ure 2% Figure . SS' sa%e %rame structure

Pa(e &6 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

$:is structure establis:es t:e *ollo!in( constraints

<ocation BAC :as no array or ,ointer variables% <ocation B C :as arrays or structures t:at contain arrays% <ocation BCC :as no arrays%

Placin( t:e (uard a*ter t:e section containin( t:e arrays B C ,revents a bu**er over*lo! *rom over!ritin( t:e ar(uments8 return address8 ,revious *rame ,ointer8 or local variables%

1. .11 :ibsa%e and :ibVeri%<ibsa*e is a dynamic library available *rom Avaya <abs "esearc: *or limitin( t:e im,act o* bu**er over*lo!s on t:e stac?% $:e library interce,ts and bounds c:ec?s ar(uments to C library *unctions t:at are susce,tible to bu**er over*lo! / aratloo 003% $:e library ma?es sure t:at *rame ,ointers and return addresses cannot be over!ritten by an interce,ted *unction% $:e libveri*y library8 also described by aratloo et al% / aratloo 0038 im,lements a return address veri*ication sc:eme similar to t:at used in Stac?Guard but does not reRuire recom,ilation o* source code8 !:ic: allo!s it to be used !it: eEistin( binaries% Summar"untime solutions suc: as bounds c:ec?ers8 canaries8 and sa*e libraries also :ave a runtime ,er*ormance cost and sometimes com,ete !it: eac: ot:er% #or eEam,le8 it may not ma?e sense to use a canary in conPunction !it: sa*e libraries because eac: ,er*orms more or less t:e same *unction in a di**erent !ay%iv

1. .1 Sa%eStr
Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3

Pa(e &7 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

$:e C Strin( <ibrary BSa*eStrC *rom Messier and =ie(a ,rovides a ric: strin(5:andlin( library *or C t:at :as secure semantics yet is intero,erable !it: le(acy library code in a strai(:t*or!ard manner% De+elo&ment Conte,t Strin( mani,ulation Tec"nolog- Conte,t C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Standard C strin( mani,ulation *unctions are ,rone to ,ro(rammer mista?es t:at can result in bu**er over*lo! vulnerabilities% Descri&tion $:e C Strin( <ibrary BSa*eStrC *rom Messier and =ie(a ,rovides a ric: strin(5:andlin( library *or C t:at :as secure semantics yet is intero,erable !it: le(acy library code in a strai(:t*or!ard manner /Messier 0>3% $:e Sa*eStr library uses a dynamic a,,roac: *or C t:at automatically resi7es strin(s as reRuired% Sa*eStr accom,lis:es t:is by reallocatin( memory and movin( t:e contents o* t:e strin( !:enever an o,eration reRuires t:at a strin( (ro! in si7e% $:e Sa*eStr library is built around t:e sa*estrDt ty,e% $:e sa*estrDt ty,e is com,atible !it: c:ar Y and allo!s sa*estrDt structures to be cast as c:ar Y and be:ave as C5style strin(s% $:ese strin(s cannot be *reed by a call to *reeBC and cannot be mani,ulated as a Sa*eStr a(ain once modi*ied% $:e sa*estrDt ty,e ?ee,s accountin( in*ormation Be%(%8 t:e actual and allocated len(t:C in memory directly ,recedin( t:e memory re*erenced by t:e ,ointer% $:e Sa*eStr library su,,orts immutable strin(s% Strin(s can be s,eci*ied as immutable durin( initiali7ation or by callin( void sa*estrDma?ereadonlyBsa*estrDtC; Immutable strin(s cannot be modi*ied usin( t:e Sa*eStr API% Ko!ever8 t:e memory can still be over!ritten% $:e library only ,revents !rites initiated t:rou(: Sa*eStr *unctions% Pa(e &4 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

$:e Sa*eStr API can :el, trac? trusted and untrusted data in t:e style o* PerlNs taint mode% A develo,er can use t:is mec:anism to mar? strin(s ori(inatin( *rom untrusted sources as suc:% Strin(s t:at :ave been c:ec?ed *or ,otentially malicious in,ut could subseRuently be mar?ed as trusted% W:en modi*yin( a strin(8 t:e trusted ,ro,erty o* t:at strin( is set to GuntrustedG i* any o* t:e o,erands are untrusted% W:en creatin( a ne! strin( *rom o,erations on ot:er strin(s8 t:e ne! strin( is mar?ed as trusted only i* all t:e strin(s t:at in*luence its value are trusted% $:e trust ,ro,erty !ill not ,ro,erly ,ro,a(ate i* t:e Sa*eStr API is circumvented% $:e Sa*eStr API does not currently ,rovide any routines t:at c:ec? t:e trusted *la(% Ko!ever8 you can eE,licitly c:ec? t:e *la( yoursel* as s:o!n in #i(ure &% Figure 1. Trusted and untrusted data in Sa%eStr &% int sa*erDsystemBsa*estrDt cmdC V 2% i* B]sa*estrDistrustedBcmdCC V >% ,rint*BWHntrusted data in sa*erDsystem]\nWC; .% abortBC; +% X 6% return systemBBc:ar YCcmdC; 7% X 1rror :andlin( in Sa*eStr is ,er*ormed usin( II<8 a library t:at ,rovides bot: eEce,tions and asset mana(ement *or C and C''% $:e caller is res,onsible *or :andlin( eEce,tions t:ro!n by Sa*eStr and II<% I* no eEce,tion :andler is s,eci*ied8 t:e de*ault action is to out,ut a messa(e to stderr and call abortBC% $:e de,endency on II< can sometimes be an issue because bot: libraries need to be ado,ted to su,,ort t:is solution% Sa*eStr is released under an o,en source SD5style license%v

1. .10 strc&-4s23 and strcat4s23


Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 $:e strc,yDsBC and strcatDsBC *unctions are de*ined in ISO0I1C $" 2.7>& as a close re,lacement *or strc,yBC and strcatBC% $:ese *unctions :ave an additional ar(ument t:at s,eci*ies t:e maEimum si7e o* t:e destination and also include a return value t:at indicates !:et:er t:e o,eration !as success*ul% De+elo&ment Conte,t Co,yin( and concatenatin( c:aracter strin(s Tec"nolog- Conte,t C8 H@II8 Win>2 Attac.s

Pa(e &2 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. $:e strc,yBC and strcatBC *unctions are a source o* bu**er over*lo! vulnerabilities% Descri&tion $:e strc,yDsBC and strcatDsBC *unctions are de*ined in ISO0I1C WD$" 2.7>& as a close re,lacement *or strc,yBC and strcatBC% $:ese *unctions :ave an additional ar(ument t:at s,eci*ies t:e maEimum si7e o* t:e destination and also include a return value t:at indicates !:et:er t:e o,eration !as success*ul% $:e strc,yDsBC *unction is similar to strc,yBC i* a constraint violation does not occur% In t:is case8 t:e strc,yDsBC *unction co,ies c:aracters *rom t:e source strin( to t:e destination c:aracter array u, to and includin( t:e terminatin( null c:aracter and t:en returns 7ero to indicate success% $:e strc,yDsBC *unction only succeeds !:en t:e source strin( can be *ully co,ied to t:e destination !it:out over*lo!in( t:e destination bu**er% I* eit:er t:e source or destination ,ointers are null or i* t:e maEimum len(t: o* t:e destination bu**er is eRual to 7ero8 (reater t:an "SIL1DMAI8& or less t:an or eRual to t:e len(t: o* t:e source strin(8 t:en a constraint violation occurs and t:e o,eration returns a non57ero value% Additionally8 t:e strc,yDsBC *unction !ill result in a constraint violation i* t:e memory re(ions o* t:e obPects overla,% I* a constraint violation occurs8 a 7ero is stored in t:e *irst c:aracter o* t:e destination i* t:e destination ,ointer is not eRual to null and t:e si7e o* t:e destination bu**er is (reater t:an 7ero and less t:an or eRual to "SIL1DMAI% $:e strcatDsBC *unction a,,ends t:e c:aracters o* t:e source strin(8 u, to and includin( t:e null c:aracter8 to t:e end o* t:e destination strin(% $:e initial c:aracter *rom t:e source strin( over!rites t:e null c:aracter at t:e end o* t:e destination strin(% $:e strcatDsBC *unction returns 7ero on success% A constraint violation !ill occur and t:e o,eration !ill return a non57ero value i*

eit:er BaC t:e source or destination ,ointer is null or t:e maEimum len(t: o* t:e destination bu**er is eRual to 7ero or (reater t:an "SIL1DMAI or BbC t:e destination strin( is already *ull or t:ere is not enou(: room to *ully a,,end t:e source strin( t:e memory re(ions o* t:e obPects overla,

I* a constraint violation occurs8 a 7ero is stored in t:e *irst c:aracter o* t:e destination i* t:e destination ,ointer is not eRual to null and t:e si7e o* t:e destination bu**er is (reater t:an 7ero and less t:an or eRual to "SIL1DMAI% $:e strc,yDsBC and strcatDsBC *unctions can still result in a bu**er over*lo! i* t:e maEimum len(t: o* t:e destination bu**er is incorrectly s,eci*ied%vi Pa(e 20 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

1. .16 strc&-23 and strcat23


Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 $:e strc,yBC and strcatBC *unctions :ave been villaini7ed as a maPor source o* bu**er over*lo!s8 and t:ere are many miti(ation strate(ies t:at ,rovide more secure variants o* t:ese *unctions% Ko!ever8 not all a,,lications o* strc,yBC are *la!ed% De+elo&ment Conte,t Co,yin( and concatenatin( c:aracter strin(s Tec"nolog- Conte,t C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. $:e strc,yBC and strcatBC *unctions are a source o* bu**er over*lo! vulnerabilities% Descri&tion $:e strc,yBC and strcatBC *unctions :ave been villaini7ed as a maPor source o* bu**er over*lo!s8 and t:ere are many miti(ation strate(ies Bsuc: as strc,yDsBC and strcatDsBCC t:at ,rovide more secure variants o* t:ese *unctions% Ko!ever8 not all a,,lications o* strc,yBC are *la!ed% #or eEam,le8 assumin( source :as been ,ro,erly validated8 it is o*ten ,ossible to dynamically allocate t:e reRuired s,ace as *ollo!sdest Z Bc:ar YCmallocBstrlenBsourceC ' &C; i* BdestC V strc,yBdest8 sourceC; X else V 0Y Kandle memory allocation error Y0 ^ X $:ere are also ot:er cases !:ere it is clear t:at t:ere is no ,otential *or !ritin( beyond t:e array bounds%

Pa(e 2& o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

As a result8 it may not be cost e**ective to re,lace or ot:er!ise secure every call to strc,yBC% $:is de,ends on t:e overall miti(ation strate(y ado,ted8 as some strate(ies reRuire an overall retoolin( o* strin( mani,ulation lo(ic% vii

1. .17 9&en<SD>s strlc&-23 and strlcat23


Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 Many H@II variants ,rovides t:e strlc,yBC and strlcatBC *unctions to co,y and concatenate strin(s in a less error5,rone manner% De+elo&ment Conte,t Co,yin( and concatenatin( c:aracter strin(s Tec"nolog- Conte,t C8 H@II8 #ree SD8 O,en SD8 @et SD8 MacOS I8 Solaris Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. $:e strc,yBC and strcatBC *unctions are a source o* bu**er over*lo! vulnerabilities% Descri&tion Many H@II variants ,rovide t:e strlc,yBC and strlcatBC *unctions to co,y and concatenate strin(s in a less error5,rone manner% $:ese *unctionsN ,rototy,es are as *ollo!ssi7eDt strlc,yBc:ar Ydst8 const c:ar Ysrc8 si7eDt si7eC; si7eDt strlcatBc:ar Ydst8 const c:ar Ysrc8 si7eDt si7eC; $:e strlc,yBC *unction co,ies t:e null5terminated strin( *rom src to dst Bu, to si7e c:aractersC% $:e strlcatBC *unction a,,ends t:e null5terminated strin( src to t:e end o* dst Bbut no more t:an si7e c:aracters !ill be in t:e destinationC%

Pa(e 22 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

$o :el, ,revent !ritin( outside t:e bounds o* t:e array8 t:e strlc,yBC and strlcatBC *unctions acce,t t:e *ull si7e o* t:e destination strin( as a si7e ,arameter% #or statically allocated bu**ers8 t:is value is easily com,uted at com,ile time usin( t:e si7eo*BC o,erator% ot: *unctions (uarantee t:at t:e destination strin( is null terminated *or all non57ero5len(t: bu**ers to ,revent null5termination errors% $:e strlc,yBC and strlcatBC *unctions return t:e total len(t: o* t:e strin( created% #or strlc,yBC t:at is sim,ly t:e len(t: o* t:e source; *or strlcatBC it is t:e len(t: o* t:e destination Bbe*ore concatenationC ,lus t:e len(t: o* t:e source% $o c:ec? *or truncation8 t:e ,ro(rammer need only veri*y t:at t:e return value is less t:an t:e si7e ,arameter% I* t:e resultin( strin( is truncated8 t:e ,ro(rammer no! ?no!s t:e number o* bytes needed to store t:e entire strin( and may reallocate and reco,y% $:is :el,s ,revent errors resultin( *rom an unintentional loss o* data% @eit:er strlc,yBC nor strlcatBC 7ero5*ills its destination strin(s Bot:er t:an t:e com,ulsory null byte to terminate t:e strin(C% $:is results in ,er*ormance close to t:at o* strc,yBC and muc: better t:an strnc,yBC /ISO0I1C 223% $able & s:o!s t:e ela,sed time reRuired to co,y t:e strin( Gt:is is Pust a testG &000 times into a &02. byte bu**er /Miller 223% Table 1. 'er%ormance in seconds CPH #unction $ime Bsec%C m?64 strc,yBC 0%&>7 m?64 strnc,yBC 0%.6. m?64 strlc,yBC 0%&.0 al,:a strc,yBC 0%0&4 al,:a strnc,yBC 0%&00 al,:a strlc,yBC 0%020 Hn*ortunately8 strlc,yBC and strlcatBC are not universally available in t:e standard libraries o* H@II systems% ot: *unctions are de*ined in strin(%: *or many H@II variants8 includin( O,en SD and Solaris8 but not *or G@H0<inuE% ecause t:ese are relatively small *unctions8 :o!ever8 you can easily include t:em in your o!n ,ro(ramAs source !:enever t:e underlyin( system doesnAt ,rovide t:em% viii

1. .16 strnc&-4s23 and strncat4s23


Pa(e 2> o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 $:e strnc,yBC and strncatBC *unctions are a source o* bu**er over*lo! vulnerabilities% $:e strnc,yDsBC and strncatDsBC *unctions are de*ined in ISO0I1C $" 2.7>& as dro,5in re,lacements *or strnc,yBC and strncatBC% De+elo&ment Conte,t Co,yin( and concatenatin( c:aracter strin(s

Tec"nolog- Conte,t C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. $:e strnc,yBC and strncatBC *unctions are a source o* bu**er over*lo! vulnerabilities% Descri&tion $:e strnc,yDsBC and strncatDsBC *unctions are de*ined in ISO0I1C WD$" 2.7>& as dro,5in re,lacements *or strnc,yBC and strncatBC% $:e strnc,yDsBC *unction co,ies not more t:an a s,eci*ied number o* successive c:aracters Bc:aracters t:at *ollo! a null c:aracter are not co,iedC *rom a source strin( to a destination c:aracter array% I* no null c:aracter !as co,ied8 t:e last c:aracter o* t:e destination c:aracter array is set to a null c:aracter% $:e strnc,yDsBC *unction returns 7ero to indicate success% I* a constraint violation occurs8 strnc,yDsBC returns a non57ero value and sets t:e destination strin( to t:e null strin( i* t:e destination ,ointer is not eRual to null and t:e si7e o* t:e destination bu**er is (reater t:an 7ero and less t:an or eRual to "SIL1DMAI%& A constraint violation occurs i*

eit:er BaC t:e source or destination ,ointer is null or BbC t:e maEimum si7e o* t:e destination strin( is 7ero or (reater t:an "SIL1DMAI

Pa(e 2. o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

t:e s,eci*ied number o* c:aracters to be co,ied eEceeds "SIL1DMAI t:e memory re(ions o* t:e obPects overla,

A strnc,yDsBC o,eration can actually succeed !:en t:e number o* c:aracters s,eci*ied to be co,ied eEceeds t:e maEimum len(t: o* t:e destination strin( as lon( as t:e actual source strin( is s:orter t:an t:e maEimum len(t: o* t:e destination strin(% I* t:e number o* c:aracters to co,y is (reater t:an or eRual to t:e maEimum si7e o* t:e destination strin( and t:e source strin( is lon(er t:an t:e destination bu**er8 t:e o,eration !ill *ail% Figure 1. Sam&le use o% strnc&-4s23 %unction &% c:ar src&/&003 Z W:elloW; 2% c:ar src2/73 Z VW(W8WoW8WoW8WdW8WbW8WyW8WeWX; >% c:ar dst&/638 dst2/+38 dst>/+3; .% int r&8 r28 r>; +% r& Z strnc,yDsBdst&8 68 src&8 &00C; 6% r2 Z strnc,yDsBdst28 +8 src28 7C; 7% r> Z strnc,yDsBdst>8 +8 src28 .C; Hsers o* t:ese *unctions are less li?ely to introduce a security *la! because t:e si7e o* t:e destination bu**er and t:e maEimum number o* c:aracters to a,,end must be s,eci*ied% $:e strncatDsBC *unction also ensures null termination o* t:e destination strin(% #or eEam,le8 t:e *irst call to strnc,yDsBC on line + o* t:e sam,le ,ro(ram s:o!n in #i(ure & assi(ns t:e value 7ero to r& and t:e seRuence :ello\0 to dst&% $:e second call on line 6 assi(ns a non57ero value to r2 and t:e seRuence \0 to dst2% $:e t:ird call on line 7 assi(ns t:e value 7ero to r> and t:e seRuence (ood\0 to dst>% I* strnc,yBC :ad been used instead o* strnc,yDsBC8 a bu**er over*lo! !ould :ave occurred durin( t:e eEecution o* line 6% $:e strncatDsBC *unction a,,ends not more t:an a s,eci*ied number o* successive c:aracters Bc:aracters t:at *ollo! a null c:aracter are not co,iedC *rom a source strin( to a destination c:aracter array% $:e initial c:aracter *rom t:e source strin( over!rites t:e null c:aracter at t:e end o* t:e destination array% I* no null c:aracter !as co,ied *rom t:e source strin(8 a null c:aracter is !ritten at t:e end o* t:e a,,ended strin(% $:e strncatDsBC *unction *ails and returns a non57ero value Bindicatin( an unde*ined be:aviorC i* any o* t:e *ollo!in( occurs

eit:er BaC t:e source or destination ,ointer is null or BbC t:e maEimum len(t: o* t:e destination bu**er is eRual to 7ero or (reater t:an "SIL1DMAI or t:e memory re(ions o* t:e obPects overla, t:e destination strin( is already *ull t:ere is not enou(: room to *ully a,,end t:e source strin(

Pa(e 2+ o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

I* a constraint violation occurs8 t:e destination strin( !ill be set to null i* t:e destination ,ointer is not eRual to null and t:e si7e o* t:e destination bu**er is (reater t:an 7ero and less t:an or eRual to "SIL1DMAI% $:e strnc,yDsBC and strncatDsBC *unctions are still ca,able o* over*lo!in( a bu**er i* t:e maEimum len(t: o* t:e destination bu**er and number o* c:aracters to co,y are incorrectly s,eci*ied% iE

1. .1! strnc&-23 and strncat23


Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 $:e standard C library includes *unctions t:at are desi(ned to ,revent bu**er over*lo!s8 ,articularly strnc,yBC and strncatBC% $:ese universally available *unctions discard data lar(er t:an t:e s,eci*ied len(t:8 re(ardless o* !:et:er it *its into t:e bu**er% $:ese *unctions are de,recated *or ne! Windo!s code because t:ey are *reRuently used incorrectly% De+elo&ment Conte,t Co,yin( and concatenatin( c:aracter strin(s Tec"nolog- Conte,t C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Im,ro,er use o* t:e strnc,yBC and strncatBC *unctions can result in bu**er over*lo! vulnerabilities% Descri&tion $:e standard C library includes *unctions t:at are desi(ned to ,revent bu**er over*lo!s8 ,articularly strnc,yBC and strncatBC% $:ese universally available *unctions discard data lar(er t:an t:e s,eci*ied len(t:8 re(ardless o* !:et:er it *its into t:e bu**er% $:ese *unctions are de,recated *or ne! Windo!s code because t:ey are *reRuently used incorrectly% $:e strnc,yBC library *unction ,er*orms a similar *unction to strc,yBC but allo!s a maEimum si7e to be s,eci*ied-

Pa(e 26 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

strnc,yBdest8 source8 destDsi7e 5 &C; dest/destDsi7e 5 &3 Z N\0N; $:e strcatBC *unction concatenates a strin( to t:e end o* a bu**er% <i?e strc,yBC8 strcatBC :as a more secure version8 strncatBC% #unctions li?e strnc,yBC and strncatBC restrict t:e number o* bytes !ritten and are (enerally more secure8 but t:ey are not *ool,roo*% $:e *ollo!in( is an actual eEam,le o* code t:at can result *rom a sim,listic trans*ormation o* eEistin( codestrnc,yBrecord8 user8 MAIDS$"I@GD<1@ 5 &C; strncatBrecord8 c,!8 MAIDS$"I@GD<1@ 5 &C; $:e ,roblem is t:at t:e last ar(ument to strncatBC s:ould not be t:e total bu**er len(t:8 it s:ould be t:e s,ace remainin( a*ter t:e call to strnc,yBC% ot: *unctions reRuire t:at you s,eci*y t:e remainin( s,ace and not t:e total si7e o* t:e bu**er% ecause t:e remainin( s,ace c:an(es every time data is added or removed8 ,ro(rammers must trac? or constantly recom,ute t:e remainin( s,ace% $:ese ,rocesses are error ,rone and can lead to vulnerabilities8 but t:e *ollo!in( call correctly calculates t:e remainin( s,ace !:en concatenatin( a strin( usin( strncatBCstrncatBdest8 source8 destDsi7e5strlenBdestC5&C; Anot:er ,roblem !it: strnc,yBC and strncatBC is t:at neit:er *unction ,rovides a status code or re,orts !:en t:e resultin( strin( is truncated% ot: *unctions return a ,ointer to t:e destination bu**er8 reRuirin( si(ni*icant e**ort by t:e ,ro(rammer to determine !:et:er t:e resultin( strin( !as truncated% $:e strnc,yBC *unction doesnAt null terminate t:e destination strin( i* t:e source strin( is at least as lon( as t:e destination% As a result8 t:e destination strin( must be null terminated a*ter callin( strnc,yBC% In certain circumstances8 a *ailure to null5terminate could lead to a bu**er over*lo! vulnerability% $:ereAs also a ,er*ormance ,roblem !it: strnc,yBC in t:at it *ills t:e entire destination bu**er !it: null bytes a*ter t:e source data :as been eE:austed% Alt:ou(: t:ere is no (ood reason *or t:is be:avior8 ,ro(rams no! de,end on it and it is di**icult to c:an(e% E

1. .1; Strsa%e."
Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 Microso*t ,rovides a set o* sa*er strin( :andlin( *unctions *or t:e C ,ro(rammin( lan(ua(e called Strsa*e%:% $:ese *unctions are intended to re,lace t:eir built5in C0C'' counter,arts8 as !ell as any le(acy Microso*t5s,eci*ic strin( :andin( *unctions% De+elo&ment Conte,t

Pa(e 27 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

Strin( mani,ulation Tec"nolog- Conte,t C0C''8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Standard C strin( mani,ulation *unctions are ,rone to ,ro(rammer mista?es t:at can result in bu**er over*lo! vulnerabilities% Descri&tion Microso*t ,rovides a set o* sa*er strin( :andlin( *unctions *or t:e C ,ro(rammin( lan(ua(e called Strsa*e%: /MSD@ 0+3% $:ere is also ntstrsa*e%: *or ?ernel mode code% $:ese *unctions are intended to re,lace t:eir built5in C0C'' counter,arts8 as !ell as any le(acy Microso*t5s,eci*ic strin( :andin( *unctions% $:ese *unctions su,,ort bot: A@SI and Hnicode c:aracters8 al!ays return a status code8 and reRuire t:at t:e ,ro(rammer al!ays s,eci*ies t:e si7e o* t:e destination bu**er% Se,arate *unctions are ,rovided t:at allo! t:e ,ro(rammer to s,eci*y t:e si7e o* t:e destination bu**er usin( eit:er c:aracter or byte counts% $:e Microso*t Strsa*e library *unctions (uarantee t:at all strin(s are null terminated Beven i* t:ey are truncatedC and t:at a !rite does not occur ,ast t:e end o* t:e destination bu**er% $:is is all true and t:ese *unctions are sa*e as lon( as t:e ,ro(rammer in,uts t:e actual startin( address o* t:e destination bu**er and correct len(t:% $:us care still must be ta?en !:en usin( t:ese *unctions% #i(ure & s:o!s an eEam,le ,ro(ram t:at ,er*orms a secure strin( co,y on line 4 and a secure strin( concatenation on line &&% Figure 1. )icroso%t Strsa%e e,am&le &% Sinclude TStrsa*e%:U 2% int DtmainBint ar(c8 D$CKA"Y ar(v/3C >% V .% c:ar MyStrin(/&243; +% K"1SH<$ "es; 6% "esZStrin(CbCo,yBMyStrin(8 si7eo*BMyStrin(C8 WPro(ram &% @ame is WC; 7% i* B"es ]Z SDOJC V 4% ,rint*BWStrin(CbCo,y #ailed- [s\nW8 MyStrin(C; Pa(e 24 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

2% eEitB5&C; &0% X &&% "esZStrin(CbCatBMyStrin(8si7eo*BMyStrin(C8ar(v/03C; &2% i* B"es ]Z SDOJC V &>% ,rint*BWStrin(CbCat #ailed- [s\nW8 MyStrin(C; &.% eEitB5&C; &+% X &6% ,rint*BW[s\nW8 MyStrin(C; &7% return 0; &4% X It is also im,ortant to remember t:at t:e Strsa*e *unctions8 suc: as Strin(Cc:Co,yBC and Strin(Cc:CatBC8 do not :ave t:e same semantics as t:e Microso*t C"$ *unctions strnc,yDsBC and strncatDsBC% W:en strncatDsBC detects an error it sets t:e destination strin( to a null strin(8 !:ile Strin(Cc:CatBC *ills t:e destination !it: as muc: data as ,ossible and t:en null terminates t:e strin(% Ei =str Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 =str is a strin( library o,timi7ed to !or? !it: readvBC0!ritevBC *or in,ut0out,ut% #or eEam,le8 you can readvBC data to t:e end o* t:e strin( and !ritevBC data *rom t:e be(innin( o* t:e strin( !it:out allocatin( or movin( memory% $:is also allo!s t:e library to !or? !it: data containin( multi,le 7ero bytes% De+elo&ment Conte,t Strin( in,ut and out,ut Tec"nolog- Conte,t C8 H@II Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. C5style strin( in,ut and out,ut *unctions are ,rone to ,ro(rammer mista?es t:at can result in bu**er over*lo! vulnerabilities% Descri&tion

Pa(e 22 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

=str is a strin( library o,timi7ed to !or? !it: readvBC0!ritevBC *or in,ut0out,ut /Antill 0+3% #or eEam,le8 you can readvBC data to t:e end o* t:e strin( and !ritevBC data *rom t:e be(innin( o* t:e strin( !it:out allocatin( or movin( memory% $:is also allo!s t:e library to !or? !it: data containin( multi,le 7ero bytes% #i(ure & s:o!s a sim,le eEam,le o* a ,ro(ram t:at uses =str to ,rint out GKello World%G $:e library is initiali7ed on line 4 o* t:is eEam,le% $:e call to t:e vstrDdu,DcstrDbu*BC *unction on line 2 creates a vstr *rom a C5style strin( literal% $:e strin( is t:en out,ut to t:e user usin( t:e vstrDscD!riteD*d BC *unction on line &2% $:is call to t:e vstrDscD!riteD*d BC *unction !rites t:e contents o* t:e s& vstr to S$DOH$% <ines &+ and &6 o* t:e eEam,le are used to clean u, allocated resources% Hnli?e most strin( libraries8 =str does not :ave an internal re,resentation o* t:e strin( t:at allo!s direct access *rom a c:aracter ,ointer% Instead8 t:e internal re,resentation is o* multi,le nodes8 eac: containin( a ,ortion o* t:e strin( data% $:is data re,resentation model means t:at memory usa(e increases linearly as a strin( (ets lar(er% Addin(8 substitutin(8 or movin( data any!:ere in t:e strin( can be o,timi7ed to reRuire OB&C co,yin( instead o* OBnC% ecause o* t:e dynamic memory mana(ement8 use o* t:e =str library s:ould eliminate t:e ,ossibility o* bu**er over*lo! in strin( :andlin(8 alt:ou(: t:e security im,lications o* usin( t:e library :ave not been t:orou(:ly evaluated% Figure 1. ?ello /orld using Vstr &% Sde*ine =S$"DCOMPI<1DI@C<HD1 & 2% Sinclude Tvstr%:U >% Sinclude Terrno%:U .% Sinclude Terr%:U +% Sinclude Tunistd%:U 6% int mainBvoidC V 7% =strDbase Ys& Z @H<<; 4% i* B]vstrDinitBCC errB1II$D#AI<H"18 WinitWC; 2% i* B]Bs& Z vstrDdu,DcstrDbu*B@H<<8 WKello World\nWCCC &0% errB1II$D#AI<H"18 WCreate strin(WC; &&% !:ile Bs&5UlenC &2% i* B]vstrDscD!riteD*dBs&8 &8 s&5Ulen8 S$DOH$D#I<1@O8 @H<<CC V &>% i* BBerrno ]Z 1AGAI@C )) Berrno ]Z 1I@$"CC errB1II$D#AI<H"18 W!riteWC; &.% X &+% vstrD*reeDbaseBs&C; &6% vstrDeEitBC; &7% eEit B1II$DSHCC1SSC; &4% X Eii

D-namic )emor- )anagement

Pa(e >0 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

.1 Guard 'ages
Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 Automatic allocation o* additional inaccessible memory durin( memory allocation o,erations is a tec:niRue *or miti(atin( a(ainst eE,loitation o* :ea, bu**er over*lo!s% $:ese (uard ,a(es are unma,,ed ,a(es ,laced bet!een all memory allocations o* one ,a(e or lar(er% $:e (uard ,a(e causes a se(mentation *ault u,on any access%
De+elo&ment Conte,t

Dynamic memory mana(ement Tec"nolog- Conte,t C''8 C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Standard C dynamic memory mana(ement *unctions suc: as malloc() 8 calloc()8 reallocBC8 and free() /ISO0I1C 223 are ,rone to ,ro(rammer mista?es t:at can lead to vulnerabilities resultin( *rom bu**er over*lo! in t:e :ea,8 !ritin( to already *reed memory8 and *reein( t:e same memory multi,le times Be%(%8 double5*ree vulnerabilitiesC% Descri,tion Automatic allocation o* additional inaccessible memory durin( memory allocation o,erations is a tec:niRue *or miti(atin( a(ainst eE,loitation o* :ea, bu**er over*lo!s% $:ese (uard ,a(es are unma,,ed ,a(es ,laced bet!een all allocations o* memory t:at are t:e si7e o* one ,a(e or lar(er% $:e (uard ,a(e causes a se(mentation *ault u,on any access% As a result8 any attem,t by an attac?er to over!rite adPacent memory in t:e course o* eE,loitin( a bu**er over*lo! causes t:e vulnerable ,ro(ram to terminate rat:er t:an continue eEecution o* t:e attac?er5su,,lied code% Guard ,a(es are im,lemented by a number o* systems and tools8 includin( O,en SD8 1lectric #ence8 and A,,lication =eri*ier Beac: o* !:ic: is discussed *urt:er in t:is content areaC% Guard ,a(es :ave a :i(: de(ree o* over:ead because t:ey *ra(ment t:e ?ernelNs memory ma, and can increase t:e amount o* virtual s,ace considerably% $:eir e**ectiveness de,ends on t:e si7e and ,attern o* allocations; t:ey are o*ten more e**ective as a debu((in( *acility t:an an o,erational security measure% Eiii

Pa(e >& o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

?ea& @ntegrit- Detection

Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 $:is article describes a system to ,rotect t:e (libc :ea, by ma?in( modi*ications to t:e c:un? structure and mana(ement *unctions% De+elo&ment Conte,t Dynamic memory mana(ement Tec"nolog- Conte,t C8 (libc8 GCC8 dlmalloc Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Standard C dynamic memory mana(ement *unctions suc: as mallocBC 8 callocBC 8 reallocBC 8 and *reeBC /ISO0I1C 223 are ,rone to ,ro(rammer mista?es t:at can lead to vulnerabilities resultin( *rom bu**er over*lo! in t:e :ea,8 !ritin( to already *reed memory8 and *reein( t:e same memory multi,le times Be%(%8 double5*ree vulnerabilitiesC% Descri&tion "obertson and collea(ues devised a system to ,rotect t:e (libc :ea, by ma?in( modi*ications to t:e c:un? structure and mana(ement *unctions /"obertson 0>3% Figure 1. )odi%ied memor- c"un. structure &% struct mallocDc:un? V 2% I@$1"@A<DSIL1D$ ma(ic; >% I@$1"@A<DSIL1D$ DD,ad0; .% I@$1"@A<DSIL1D$ ,revDsi7e; +% I@$1"@A<DSIL1D$ si7e; 6% struct mallocDc:un? Yb?; 7% struct mallocDc:un? Y*d; 4% X; $:is :ea, inte(rity sc:eme ,re,ends a canary and ,addin( *ield to t:e c:un? structure as s:o!n in #i(ure &% $:e canary contains a c:ec?sum o* t:e c:un? :eader seeded !it: a random value% $:e (lobal Pa(e >2 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

c:ec?sum seed value is stored in t:e DD:ea,Dma(ic static variable% $:is variable is initiali7ed durin( ,rocess startu, !it: a random value8 !:ic: is t:en ,rotected a(ainst *urt:er !rites by m,rotectBC%& $:e :ea, ,rotection system also au(ments t:e :ea, mana(ement *unctions !it: code to mana(e and c:ec? eac: c:un?Ns canary% $:e canary in a ne!ly allocated c:un? is initiali7ed to a c:ec?sum t:at includes its memory location and si7e *ields and is seeded !it: t:e (lobal value o* DD:ea,Dma(ic% W:en a c:un? is returned by a call to *reeBC8 t:e c:un?Ns canary is c:ec?ed a(ainst t:e c:ec?sum calculated !:en t:e c:un? !as allocated% I* t:e c:ec?sums do not matc:8 an eEce,tion is raised and t:e ,rocess is aborted%Eiv

.0

$ull 'ointers

Daniel Pla?os:8 So*t!are 1n(ineerin( Institute /vita3 One obvious tec:niRue to reduce vulnerabilities in C and C'' ,ro(rams is to set t:e ,ointer to null a*ter t:e call to *reeBC :as com,leted% De+elo&ment Conte,t Dynamic memory mana(ement Tec"nolog- Conte,t C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Standard C dynamic memory mana(ement *unctions suc: as mallocBC 8 callocBC 8 reallocBC8 and *reeBC /ISO0I1C 223 are ,rone to ,ro(rammer mista?es t:at can lead to vulnerabilities resultin( *rom bu**er over*lo! in t:e :ea,8 !ritin( to already *reed memory8 and *reein( t:e same memory multi,le times Be%(%8 double5*ree vulnerabilitiesC% Descri&tion One obvious tec:niRue to reduce vulnerabilities in C and C'' ,ro(rams is to set t:e ,ointer to null a*ter t:e call to *reeBC :as com,leted% Dan(lin( ,ointers B,ointers to already *reed memoryC can result in !ritin( to *reed memory and double5*ree vulnerabilities% Any attem,t to dere*erence t:e ,ointer !ill

Pa(e >> o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

result in a *ault8 !:ic: increases t:e li?eli:ood t:at t:e error !ill be detected durin( im,lementation and test% Also8 i* t:e ,ointer is set to null8 t:e memory can be *reed multi,le times !it:out conseRuence% W:ile settin( t:e ,ointer to null s:ould si(ni*icantly reduce vulnerabilities resultin( *rom !ritin( to *reed memory and double5*ree vulnerabilities8 it cannot ,revent t:em !:en multi,le ,ointers all re*erence t:e same data structure% Hn*ortunately8 memory mana(ement in C and C' must be ,er*ormed !it: (reat care% Ev .6 '".malloc

"obert C% Seacord8 So*t!are 1n(ineerin( Institute /vita3 P:?malloc is an alternative dynamic memory mana(ement *unction t:at !as by !ritten by Poul5 Kennin( Jam, *or #ree SD in &22+5&226 and subseRuently ada,ted by a number o* o,eratin( systems8 includin( @et SD8 O,en SD8 and several <inuE distributions% De+elo&ment Conte,t Dynamic memory mana(ement Tec"nolog- Conte,t C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Standard C dynamic memory mana(ement *unctions suc: as mallocBC8 callocBC8 and *reeBC /ISO0I1C 223 are ,rone to ,ro(rammer mista?es t:at can lead to vulnerabilities resultin( *rom bu**er over*lo! in t:e :ea,8 !ritin( to already *reed memory8 and *reein( t:e same memory multi,le times Be%(%8 double5*ree vulnerabilitiesC% Descri&tion P:?malloc !as by !ritten by Poul5Kennin( Jam, *or #ree SD in &22+5&226 and subseRuently ada,ted by a number o* o,eratin( systems8 includin( @et SD8 O,en SD8 and several <inuE distributions% P:?malloc !as !ritten to o,erate e**iciently in a virtual memory system8 !:ic: resulted in stron(er c:ec?s% $:e stron(er c:ec?s led to t:e discovery o* memory mana(ement errors in some a,,lications and t:e idea o* usin( ,:?malloc to eE,ose and ,rotect a(ainst malloc5API mista?es and misuse /Jam, 243% $:is !as ,ossible because o* ,:?mallocNs in:erent mistrust o* t:e ,ro(rammer% P:?malloc can Pa(e >. o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

determine !:et:er a ,ointer ,assed to *reeBC or reallocBC is valid !it:out dere*erencin( it% P:?malloc cannot detect i* a !ron( Bbut validC ,ointer is ,assed8 but can detect all ,ointers t:at !ere not returned by mallocBC or reallocBC% ecause ,:?malloc can determine !:et:er a ,ointer is allocated or *ree8 it detects all double5*ree errors% #or un,rivile(ed ,rocesses8 t:ese errors are treated as !arnin(s8 meanin( t:at t:e ,rocess can survive !it:out any dan(er to t:e malloc data structures% Ko!ever8 enablin( t:e FAG or FabortG o,tion causes t:ese !arnin(s to be treated as errors% An error is terminal and results in a call to abortBC% Some con*i(urable o,tions *or ,:?malloc t:at :ave security im,lications are s:o!n in $able &% Table 1. '".malloc o&tions #la( Descri,tion A I 9 L FAbort%G mallocBC !ill core dum, t:e ,rocess rat:er t:an tolerate *ailure% $:e core *ile !ill re,resent t:e time o* *ailure rat:er t:an !:en t:e @H<< ,ointer !as accessed% Instead o* returnin( an error *or any allocation *unction8 dis,lay a dia(nostic messa(e on stderr and call abortBC% F9un?%G #ill some Pun? into t:e area allocated% Currently Pun? is bytes o* 0Ed0% FLero%G #ill some Pun? into t:e area allocated Bsee 9C8 eEce,t *or t:e eEact len(t: t:e user as?ed *or8 !:ic: is 7eroed%

A*ter t:e C=S double5*ree vulnerability 8 t:e FAG o,tion !as made automatic and mandatory *or sensitive ,rocesses B!:ic: !ere some!:at arbitrarily de*ined as setuid8 set(id8 root8 or !:eel ,rocessesCi* BmallocDabort __ issetu(idBC __ (etuidBC ZZ 0 __ (et(idBC ZZ 0C abortBC; A more com,lete descri,tion o* t:e C=S Server vulnerability and t:e security im,lications o* ,:?malloc can be *ound in /Smas:in( 0+3% Due to t:e success o* ,ointer c:ec?s8 t:e 9Bun?C and LBeroC o,tions !ere added to *ind even more memory mana(ement de*ects% $:e 9Bun?C o,tion *ills t:e allocated area !it: t:e value 0Ed0 because !:en *our o* t:ese bytes are turned into a ,ointer B0Ed0d0d0d0C8 it re*erences t:e ?ernelNs ,rotected memory so t:at t:e ,rocess !ill core dum, !it: a se(*ault% $:e LBeroC o,tion also *ills t:e memory !it: Pun? eEce,t *or t:e eEact len(t: t:e user as?ed *or8 !:ic: is 7eroed% #ree SDNs version o* ,:?malloc can also ,rovide a trace o* all malloc0*ree0realloc reRuests usin( t:e ?traceBC *acility !it: t:e FHG o,tion% P:?malloc :as been used to discover memory mana(ement de*ects in *sc?8 y,serv8 cvs8 mountd8 inetd8 and ot:er ,ro(rams% P:?malloc determines !:ic: o,tions are set by scannin( *or *la(s in t:e *ollo!in( locationsPa(e >+ o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

t:e symbolic lin? 0etc0malloc%con* t:e environment variable MA<<OCDOP$IO@S t:e (lobal variable mallocDo,tions

#la(s are sin(le letters; u,,er case means on8 lo!er case means o**%Evi

.7

RandomiAation

"obert C% Seacord8 So*t!are 1n(ineerin( Institute /vita3 "andomi7ation !or?s on t:e ,rinci,le t:at it is :arder to :it a movin( tar(et% Addresses o* memory allocated by mallocBC are *airly ,redictable% "andomi7in( t:e addresses o* bloc?s o* memory returned by t:e memory mana(er can ma?e it more di**icult to eE,loit a :ea,5based vulnerability% De+elo&ment Conte,t Dynamic memory mana(ement Tec"nolog- Conte,t C''8 C8 H@II8 Win>2 Attac.s Attac?er eEecutes arbitrary code on mac:ine !it: ,ermissions o* com,romised ,rocess or c:an(es t:e be:avior o* t:e ,ro(ram% Ris. Standard C dynamic memory mana(ement *unctions suc: as mallocBC8 callocBC8 and *reeBC /ISO0I1C 223 are ,rone to ,ro(rammer mista?es t:at can lead to vulnerabilities resultin( *rom bu**er over*lo! in t:e :ea,8 !ritin( to already *reed memory8 and *reein( t:e same memory multi,le times Be%(%8 double5*ree vulnerabilitiesC% Descri&tion "andomi7ation !or?s on t:e ,rinci,le t:at it is :arder to :it a movin( tar(et% Addresses o* memory allocated by mallocBC are *airly ,redictable% "andomi7in( t:e addresses o* bloc?s o* memory returned by t:e memory mana(er can ma?e it more di**icult to eE,loit a :ea,5based vulnerability% "andomi7in( memory addresses can occur in multi,le locations% #or bot: t:e Windo!s and H@II o,eratin( systems8 t:e memory mana(er reRuests memory ,a(es *rom t:e o,eratin( system8 !:ic: are Pa(e >6 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

t:en bro?en u, into small c:un?s and mana(ed as reRuired by t:e a,,lication ,rocess% It is ,ossible to randomi7e bot: t:e ,a(es returned by t:e o,eratin( system and t:e addresses o* c:un?s returned by t:e memory mana(er% $:e O,en SD ?ernel8 *or eEam,le8 uses mma,BC to allocate or ma, additional memory ,a(es% $:e mma,BC *unction !ill return a random address eac: time an allocation is ,er*ormed8 as lon( as t:e MAPD#II1D *la( is not s,eci*ied% $:e mallocBC *unction can also be con*i(ured to return random c:un?s% $:e result is t:at eac: time a ,ro(ram is run8 it eE:ibits di**erent address s,ace be:avior8 t:ereby ma?in( it :arder *or an attac?er to (uess t:e location o* memory structures t:at must be over!ritten to eE,loit a vulnerability% ecause randomi7ation can ma?e debu((in( di**icult8 it can usually be enabled or disabled at runtime% Also8 randomi7ation adds an un,redictable8 but o*ten si(ni*icant8 ,er*ormance over:ead% Evii

Pa(e >7 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

C++ inherits a host of opportunities for type violations from C and adds a few of its own. ` Parne Stroustru,8 WA rationale *or semantically en:anced library lan(ua(esW 00% Pre,rocessor BP"1C 0&% Declarations BDC<C 02% 1E,ressions B1IPC 0>% Inte(ers BI@$C 0.% #loatin( Point Arit:metic B#<PC 0+% Arrays BA""C 06% Dan(lin( Pointers BDA@C Pa(e >4 o* ..

DRAFT C++ Coding Standards Version 0.1 Secure Coding and Design Standards March 18, 2014

07% 1rrors and 1Ece,tions B1""C 04% "esource Mana(ement B"1SC 02% ObPect Orientation BO 9C &0% asic Strin( Class B SCC &&% @ull5$erminated yte Strin(s BS$"C &2% =ectors B=1CC &>% S$< BS$<C &.% In,ut Out,ut B#IOC &+% Miscellaneous BMSCC AA% C'' "e*erences

Pa(e >2 o* ..

References

2 " S#$ %C &&' S#$ %C. ISO/IEC 9899 Second edition 1999-12-01 Programming languages C. nternationa( #rgani)ation *or Standardi)ation, 1&&&." S#$ %C &8'+oint Technica( Co,,ittee S#$ %C +TC - nternationa( #rgani)ation *or Standardi)ationand nternationa( %(ectrotechnica( Co,,ission. Programming Languages C++. .ene/a, S0it)er(and1 S#$ %C, 1&&8."Viega 02'Viega, +ohn 3 Messier, Matt. Secure Programming Coo !oo "or C and C++# $eci%es "or Cr&%togra%'&( )ut'entication( *et+or ing( In%ut ,alidation - .ore. Se4asto5o(, CA1 #6Rei((7, 2002 8 S9:1 0;<&=;002&4;2>.'earson
(ducationB @nc. Co&-rig"t $:is material is eEcer,ted *rom Secure Coding in C and C++8 by "obert C% Seacord8 co,yri(:t a 2006 by Pearson 1ducation8 Inc%8 ,ublis:ed as a C1"$b boo? in t:e S1I Series in So*t!are 1n(ineerin(% All ri(:ts reserved% It is re,rinted !it: ,ermission and may not be *urt:er re,roduced or distributed !it:out t:e ,rior !ritten consent o* Pearson 1ducation8 Inc%

ii

References

2 " S#$ %C &&' S#$ %C. ISO/IEC 9899 Second edition 1999-12-01 Programming languages C. nternationa( #rgani)ation *or Standardi)ation, 1&&&." S#$ %C 04' S#$ %C. ISO/IEC /01$ 22341 S%eci"ication "or Secure C Li!rar& 5unctions. nternationa( #rgani)ation *or Standardi)ation, 2004.'earson
(ducationB @nc. Co&-rig"t $:is material is eEcer,ted *rom Secure Coding in C and C++8 by "obert C% Seacord8 co,yri(:t a 2006 by Pearson 1ducation8 Inc%8 ,ublis:ed as a C1"$b boo? in t:e S1I Series in So*t!are 1n(ineerin(% All ri(:ts reserved% It is re,rinted !it: ,ermission and may not be *urt:er re,roduced or distributed !it:out t:e ,rior !ritten consent o* Pearson 1ducation8 Inc%

iii

References

4 " S#$ %C &&' S#$ %C. ISO/IEC 9899 Second edition 1999-12-01 Programming languages C. nternationa( #rgani)ation *or Standardi)ation, 1&&&." S#$ %C 04' S#$ %C. ISO/IEC /01$ 22341 S%eci"ication "or Secure C Li!rar& 5unctions. nternationa( #rgani)ation *or Standardi)ation, 2004.'earson
(ducationB @nc. Co&-rig"t $:is material is eEcer,ted *rom Secure Coding in C and C++8 by "obert C% Seacord8 co,yri(:t a 2006 by Pearson 1ducation8 Inc%8 ,ublis:ed as a C1"$b boo? in t:e S1I Series in So*t!are 1n(ineerin(% All ri(:ts reserved% It is re,rinted !it: ,ermission and may not be *urt:er re,roduced or distributed !it:out t:e ,rior !ritten consent o* Pearson 1ducation8 Inc%

iv

References

7 C<aratloo 00D<aratlooB A.E Sing"B $.E & TsaiB T. FTrans&arent Run8 Time De%ense Against Stac. Smas"ing Attac.sBG 718 6 . Proceedings of 2000 USENIX Annual Technical Conference. San DiegoB CAB Hune 1;8 0B 000. <er.ele-B CA* 5S($@I AssociationB 000.C<ulba 00D<ulba & Jil0r. B !assing Stac"#uard and Stac"Shiel 2'rac.B Vol8 ume 0,a @ssue 0,0; 07.01. 000 0,07C0,10D3. "tt&*##///.&"rac..org#&"rac.#76# &7680,07 2 0003.CCo/an =;DCo/anB C.E 'uB C.* )aierB D.E ?intonB ?.E Kal&oleB H.E <a..eB '.E <eattieB S.E GrierB A.E KagleB '.E & L"angB M. FStac.guard* Automatic ada&ti+e detection and &re+ention o% bu%%er8o+er%lo/ attac.sBG 608!!. Proceedings of the Se$enth USENIX Securit S %!osiu%. San AntonioB TIB Hanuar- 68 =B 1==;. <er.ele-B CA* 5S($@I AssociationB 1==;.CCo/an 00DCo/anB Cris&inE KagleB 'err-E 'uB CaltonE <eattieB Ste+eE & Kal&oleB Honat"an. F<u%%er 9+er%lo/s* Attac.s and De%enses %or t"e Vulnerabilit- o% t"e DecadeBG 11=81 =. Proceedings of the &ARPA Infor%ation Sur$i$abilit Conference and E'!osition (&ISCEX)00*. ?ilton ?ead @slandB SCB Hanuar- 78 !B 000. :os AlamitosB CA* @((( Com&uting Societ-B 000.Cde Raadt 00DT"eo de RaadtB Ad+ances in 9&en<SDB &resented at CanSecKestB Vancou+erB Canada. A&ril 000 "tt&*##///.o&enbsd.org#&a&ers#cs/00#mg&00001."tmlC(to" 06D(to"B ?iroa.i & NodaB J. Protecting fro% stac"+s%ashing attac"s. "tt&*## ///.researc".ibm.com#trl#&ro1ects#securit-#ss&#main."tml 2 0063. CHones =!DHonesB Ric"ard K. ). & Jelle-B 'aul ?. H. F<ac./ards8 com&atible bounds c"ec.ing %or arra-s and &ointers in C &rogramsBG 108 6. Proceedings of the Third International ,or"sho! on Auto%atic &ebugging (AA&EBU#)-.*. :in.o&ingB S/edenB )a- 68 !B 1==!. :in.o&ingB S/eden* :in.o&ings 5ni+ersitetB 1==!.CRu/ase 06DRu/aseB 9latun1i & :amB ). S. FA 'ractical D-namic <u%%er 9+er%lo/ DetectorBG 17=816=. Proceedings of the //th Annual Net0or" and &istributed S ste% Securit S %!osiu%. San DiegoB CAB Februar786 006. RestonB VA* @nternet Societ-B 006. "tt&*##sui%.stan%ord.edu#&a&ers#tun1i06.&d%.CSeacord 07DRobert C. Seacord. Secure Coding in C and C11. <ostonB )A* Addison8Kesle-B 007.CKagle 00DKagleB 'err- & Co/anB Cris&in. FStac.Guard* Sim&le Stac. Smas" 'rotection %or GCCBG 608 76. Proceedings of

the #CC &e$elo!ers Su%%it. 9tta/aB 9ntarioB CanadaB )a- 78 !B 000.CKilander 00DKilanderB H. & Jam.arB ). FA Com&arison o% 'ublicl- A+ailable Tools %or D-namic <u%%er 9+er%lo/ 're+entionBG 16=816 . Proceedings of the /0th Net0or" and &istributed S ste% Securit S %!osiu%. San DiegoB Cali%orniaB Februar- 68!B 000. RestonB VA* @nternet Societ-B 000. "tt&*##///.ida.liu.se#O1o"/i# researc"4&ublications#&a&er4ndss 00041o"n4/ilander.&d%.'earson
(ducationB @nc. Co&-rig"t
$:is material is eEcer,ted *rom Secure Coding in C and C++8 by "obert C% Seacord8 co,yri(:t a 2006 by Pearson 1ducation8 Inc%8 ,ublis:ed as a C1"$b boo? in t:e S1I Series
v

References

/ISO0I1C 223ISO0I1C% ISO/IEC ! Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation *or Standardi7ation8 &222%/Messier 0>3Messier8 Matt ) =ie(a8 9o:n% Safe C String (ibrary v".%.)% :tt,-00!!!%7or?%or(0sa*estr B200+C%
vi

$e"erences

/ISO0I1C 223ISO0I1C% ISO/IEC ! Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation *or Standardi7ation8 &222%/ISO0I1C 0.3ISO0I1C% ISO/IEC *+,- $./)" Specification for Secure C (ibrary 0unctions% International Or(ani7ation *or Standardi7ation8 200.%
vii

$e"erences
Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation

/ISO0I1C 223ISO0I1C% ISO/IEC ! *or Standardi7ation8 &222%


viii

References

/ISO0I1C 223ISO0I1C% ISO/IEC ! Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation *or Standardi7ation8 &222%/Miller 223Miller8 $% C% ) de "aadt8 $% Wstrlc,y and strlcat6Consistent8 Sa*e Strin( Co,y and Concatenation8W &7+5&74% &roceedings of the 0-EE1I2 ,rac34 " 5SE1I2 6nnual ,echnical Conference. Monterey8 CA8 9une 65&&8 &222% er?eley8 CA- HS1@II Association8 &222% :tt,-00!!!%useniE%or(0,ublications0library0,roceedin(s0useniE220 *ullD,a,ers0millert0millert%,d*%
ix

References

/ISO0I1C 223ISO0I1C% ISO/IEC ! Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation *or Standardi7ation8 &222%/ISO0I1C 0.3ISO0I1C% ISO/IEC *+,- $./)" Specification for Secure C (ibrary 0unctions% International Or(ani7ation *or Standardi7ation8 200.%
x

References
Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation

/ISO0I1C 223ISO0I1C% ISO/IEC ! *or Standardi7ation8 &222%


xi

References

/ISO0I1C 223ISO0I1C% ISO/IEC ! Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation *or Standardi7ation8 &222%/MSD@ 0+3Microso*t Cor,% 5sing the Strsafe.h 0unctions B200+C%
xii

References

/ISO0I1C 223ISO0I1C% ISO/IEC ! Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation *or Standardi7ation8 &222%/Antill 0+3Antill8 9ames% 7str documentation ## overview% :tt,-00!!!%and%or(0vstr B200+C%
xiii

References
Second edition " #"$#%" &rogramming (anguages ' C% International Or(ani7ation

/ISO0I1C 223ISO0I1C% ISO/IEC ! *or Standardi7ation8 &222%


xiv

References

/ISO0I1C 223ISO0I1C% ISO/IEC ! Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation *or Standardi7ation8 &222%/"obertson 0>3"obertson8 William; Jrue(el8 C:risto,:er; Mut78 Darren; ) =aleur8 #redri?% G"un5time Detection o* Kea,5based Over*lo!s8G +&560% &roceedings of the "/th (arge Installation Systems 6dministration Conference% San Die(o8 CA8 October 26`>&8 200>% er?eley8 CA- HS1@II Association8 200>%
xv

References
Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation

/ISO0I1C 223ISO0I1C% ISO/IEC ! *or Standardi7ation8 &222%


xvi

References

/ISO0I1C 223ISO0I1C% ISO/IEC ! Second edition " #"$#%" &rogramming languages ' C% International Or(ani7ation *or Standardi7ation8 &222%/Smas:in( 0+38S+ 9eap Smashing% :tt,-00t:c%or(0root0docs0eE,loitD!ritin(0 SD5:ea,5 smas:in(%tEt B200+C%/Jam, 243Jam,8 Poul5Kennin(% FMallocB>C revisited8G &2>5&24% 5SE1I2 " ! 6nnual ,echnical Conference: Invited ,al3s and 0reenix ,rac3% @e! Orleans8 <A8 9une &+5&28 &224% er?eley8 CA- HS1@II Association8 &224%
xvii

References
Second edition " #"$#%" &rogramming (anguages ' C% International Or(ani7ation

/ISO0I1C 223ISO0I1C% ISO/IEC ! *or Standardi7ation8 &222%

You might also like