Upload
blaise-horton
View
221
Download
3
Tags:
Embed Size (px)
Citation preview
Software SecuritySoftware Security
Building Building Security in Security in SoftwareSoftware
SECURITY INNOVATION ©20032
The ProblemThe Problem
• The problem in a nutshell is diversityThe problem in a nutshell is diversity• The Internet is great because it’s diverse The Internet is great because it’s diverse
and openand open– Anyone can do what they wantAnyone can do what they want– Anyone can code the next “killer app”Anyone can code the next “killer app”
• Which means:Which means:– Nobody learns from anyone’s mistakesNobody learns from anyone’s mistakes
SECURITY INNOVATION ©20033
The ProblemThe Problem
• To achieve a high and broad level of To achieve a high and broad level of security we must security we must reduce diversity of reduce diversity of implementationimplementation– But if we reduce it too far we lose all our But if we reduce it too far we lose all our
“biological diversity” and are vulnerable to “biological diversity” and are vulnerable to broad-sweeping virusesbroad-sweeping viruses
SECURITY INNOVATION ©20034
HistoryHistory
• Computing grew up in a trusting worldComputing grew up in a trusting world– In 1988, most Internet hosts trustedIn 1988, most Internet hosts trusted
• The Internet today is radically differentThe Internet today is radically different– Must assume there are bad guys out thereMust assume there are bad guys out there– Woe to software that gives no thought to Woe to software that gives no thought to
securitysecurity
SECURITY INNOVATION ©20035
The Internet Worm of The Internet Worm of 19881988
• The first widely-known Internet virusThe first widely-known Internet virus– Exploited a buffer overrun in Exploited a buffer overrun in fingerdfingerd– Viruses well-known before ’88Viruses well-known before ’88
• Just not network-basedJust not network-based
• Written by Cornell gradWritten by Cornell grad– Goal was demonstration of vulnerabilityGoal was demonstration of vulnerability– But the code had a tragic bugBut the code had a tragic bug
• Infection rate was exponential instead of linearInfection rate was exponential instead of linear• Brought down thousands of machines on the Brought down thousands of machines on the
InternetInternet
SECURITY INNOVATION ©20036
Top Ten Security HolesTop Ten Security Holes
In June 2000, GSA Federal Chief Information Officers Council listed the "The Ten Most In June 2000, GSA Federal Chief Information Officers Council listed the "The Ten Most Critical Internet Security Threats"Critical Internet Security Threats"
1.1. BIND weaknesses: nxt, qinv and in.named allow immediate root compromise. BIND weaknesses: nxt, qinv and in.named allow immediate root compromise. 2.2. Vulnerable CGI programs and application extensions (e.g., ColdFusion) installed Vulnerable CGI programs and application extensions (e.g., ColdFusion) installed
on web servers. on web servers. 3.3. Remote Procedure Call (RPC) weaknesses in rpc.ttdbserverd (ToolTalk), rpc.cmsd Remote Procedure Call (RPC) weaknesses in rpc.ttdbserverd (ToolTalk), rpc.cmsd
(Calendar Manager), and rpc.statd that allow immediate root compromise (Calendar Manager), and rpc.statd that allow immediate root compromise 4.4. Remote Data Services (RDS) security hole in the Microsoft's web server named Remote Data Services (RDS) security hole in the Microsoft's web server named
IIS. IIS. 5.5. Sendmail buffer overflow weaknesses, pipe attacks and MIMEbo, that allow Sendmail buffer overflow weaknesses, pipe attacks and MIMEbo, that allow
immediate root compromise. immediate root compromise. 6.6. Buffer overflows in sadmind (remote administration access to Solaris systems) Buffer overflows in sadmind (remote administration access to Solaris systems)
and mountd (controls and arbitrates access to NFS mounts on UNIX hosts) permit and mountd (controls and arbitrates access to NFS mounts on UNIX hosts) permit root compromise. root compromise.
7.7. Global file sharing and inappropriate information sharing via NFS and Windows Global file sharing and inappropriate information sharing via NFS and Windows NT ports 135->139 (445 in Windows2000) or UNIX NFS exports on port 2049. NT ports 135->139 (445 in Windows2000) or UNIX NFS exports on port 2049. Also Appletalk over IP with Macintosh file sharing enabled. Also Appletalk over IP with Macintosh file sharing enabled.
8.8. User IDs, especially root/administrator with no passwords or weak passwords. User IDs, especially root/administrator with no passwords or weak passwords. 9.9. IMAP and POP buffer overflow vulnerabilities or incorrect configuration. IMAP and POP buffer overflow vulnerabilities or incorrect configuration. 10.10. Default SNMP community strings set to ‘public’ and ‘private.’ Default SNMP community strings set to ‘public’ and ‘private.’
SECURITY INNOVATION ©20037
Robust ProgramsRobust Programs
– Crash proof, and hang-proof no matter what the Crash proof, and hang-proof no matter what the inputs are. inputs are.
– Crash is unexpected termination. Crash is unexpected termination. – A hang is unexpected non-termination. Two classes A hang is unexpected non-termination. Two classes
of being hung are: infinite looping, and waiting for an of being hung are: infinite looping, and waiting for an event that will not occur. Infinite looping consumes event that will not occur. Infinite looping consumes heavily the CPU time. Waiting for a non-occurring heavily the CPU time. Waiting for a non-occurring event consumes almost no resources. event consumes almost no resources.
– Note that infinite recursion will lead to a crash via Note that infinite recursion will lead to a crash via resource exhaustion. resource exhaustion.
SECURITY INNOVATION ©20038
Correct ProgramsCorrect Programs
• Specifications, expressed in a language Specifications, expressed in a language as formal as the programming as formal as the programming languageslanguages
• Implementation “satisfies” the Implementation “satisfies” the specification.specification.
• ““Satisfies” is verified not by testing, but Satisfies” is verified not by testing, but by design and proof.by design and proof.
• Practical: pre- and post-conditionsPractical: pre- and post-conditions
SECURITY INNOVATION ©20039
Secure ProgramsSecure Programs
• Correct and RobustCorrect and Robust• Importance of the programImportance of the program
– Costs of failureCosts of failure
SECURITY INNOVATION ©200310
Design Principles for Design Principles for Secure ProgramsSecure Programs
• Laws of Large Programs Laws of Large Programs • Correctness and Robustness Correctness and Robustness • Economy of Mechanism Economy of Mechanism • Fail-open or -closed? Fail-open or -closed? • Security compartments Security compartments • Trusting untrustworthy channels Trusting untrustworthy channels • Proper defaults Proper defaults • Error Handling and Reporting Error Handling and Reporting • Assertions and Exit Points Assertions and Exit Points
SECURITY INNOVATION ©200311
Automated Tools for Secure Automated Tools for Secure ProgramsPrograms
• Run-time solutionsRun-time solutions– #include <assert.h> #include <assert.h> – StackGuard[USENIX 1997], gcc bounds-checking, StackGuard[USENIX 1997], gcc bounds-checking,
libsafe[USENIX 2000]libsafe[USENIX 2000]– Performance penaltyPerformance penalty– Turns buffer overflow into a DoS attackTurns buffer overflow into a DoS attack
• Compile-time solutions - static analysisCompile-time solutions - static analysis– No run-time performance penaltyNo run-time performance penalty– Checks properties of all possible executionsChecks properties of all possible executions– www.splint.orgwww.splint.org
SECURITY INNOVATION ©200312
<assert.h><assert.h>
• The The <assert.h><assert.h> header defines the header defines the assert()assert() macro: macro:
void assert(int void assert(int expressionexpression); );
• The The assert()assert() macro inserts diagnostics into programs. When it macro inserts diagnostics into programs. When it is executed, if is executed, if expressionexpression is false (that is, equals to 0), is false (that is, equals to 0), assert()assert() writes information about the particular call that failed writes information about the particular call that failed (including the text of the argument, the name of the source file (including the text of the argument, the name of the source file and the source file line number - the latter are respectively the and the source file line number - the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__) on values of the preprocessing macros __FILE__ and __LINE__) on stderrstderr and calls and calls abort()abort(). .
• assert() refers to the macro assert() refers to the macro NDEBUGNDEBUG which is not defined in which is not defined in the header. If the header. If NDEBUGNDEBUG is defined as a macro name before the is defined as a macro name before the inclusion of this header, the inclusion of this header, the assert()assert() macro is defined simply macro is defined simply as: #define assert(ignore)((void) 0) otherwise the macro as: #define assert(ignore)((void) 0) otherwise the macro behaves as described in behaves as described in assert()assert(). .
SECURITY INNOVATION ©200313
Compilers v. VerifiersCompilers v. Verifiers
Effort RequiredEffort RequiredLowLow UnfathomableUnfathomable
Formal VerifiersFormal Verifiers
Bu
gs
Dete
cted
Bu
gs
Dete
cted
nonenone
allall
CompilersCompilers
spLint
spLint
SECURITY INNOVATION ©200314
Building Secure Building Secure SoftwareSoftware
• Common mistakesCommon mistakes– Forget to make the software secureForget to make the software secure– Adding security as an afterthoughtAdding security as an afterthought
• Why these mistakesWhy these mistakes– Security is boringSecurity is boring– Security gets in the waySecurity gets in the way– Security is difficult to measureSecurity is difficult to measure– Security is not the primary skill or interest Security is not the primary skill or interest
of designers and developersof designers and developers
SECURITY INNOVATION ©200315
Security Principles to Security Principles to Live ByLive By
• Establish a security processEstablish a security process• Define the product security goalsDefine the product security goals• Consider security as a product featureConsider security as a product feature• Learn from mistakesLearn from mistakes• Use defense in depthUse defense in depth• Assume external systems are insecureAssume external systems are insecure
SECURITY INNOVATION ©200316
Security Principles to Security Principles to Live ByLive By
• Plan on failurePlan on failure• Fail to a secure modeFail to a secure mode• Employ secure defaultsEmploy secure defaults• Remember that security features != Remember that security features !=
secure featuressecure features• Never depend on security through Never depend on security through
obscurityobscurity
SECURITY INNOVATION ©200317
Security Design by Security Design by Threat ModelingThreat Modeling
• Use a taxonomy of threats, e.g., Use a taxonomy of threats, e.g., STRIDE:STRIDE:– Spoofing identitySpoofing identity– Tampering with dataTampering with data– RepudiationRepudiation– Information disclosureInformation disclosure– Denial of serviceDenial of service– Elevation of privilegeElevation of privilege
• Consider target, chance, criticality, Consider target, chance, criticality, attack techniques, mitigation attack techniques, mitigation techniques, etc.techniques, etc.
SECURITY INNOVATION ©200318
Open Source and Open Source and Closed SourceClosed Source
• Security by obscurity is no panaceaSecurity by obscurity is no panacea– Reverse engineeringReverse engineering
• Disassembler: machine code to assemblyDisassembler: machine code to assembly• Discomplier: machine code to high-level Discomplier: machine code to high-level
languagelanguage• Code obfuscation: make the code difficult to Code obfuscation: make the code difficult to
understand, raise the bar a littleunderstand, raise the bar a little
SECURITY INNOVATION ©200319
Open Source and Closed Open Source and Closed SourceSource
• Open-source software – potentially Open-source software – potentially more securemore secure– The many-eyeballs phenomenonThe many-eyeballs phenomenon
• Given enough eyeballs, all bugs are shallowGiven enough eyeballs, all bugs are shallow– Need incentivesNeed incentives– Many people don’t know and don’t think Many people don’t know and don’t think
much about securitymuch about security• Vulnerability detection in source code is hardVulnerability detection in source code is hard
– E.g., which function has buffer overflow E.g., which function has buffer overflow problemproblem
SECURITY INNOVATION ©200320
Some Basic Obfuscation Some Basic Obfuscation TechniquesTechniques
• Add code that never executes, or that does Add code that never executes, or that does nothingnothing– E.g., make computations far more complex than they E.g., make computations far more complex than they
need beneed be
• Move code aroundMove code around– Spread related information as far apart as possibleSpread related information as far apart as possible
• E.g., Copy and rename the same function, or put E.g., Copy and rename the same function, or put multiple functions into a single functionmultiple functions into a single function
• Encode your data oddlyEncode your data oddly
SECURITY INNOVATION ©200321
The Typical Trajectory The Typical Trajectory TodayToday
• DiscoveryDiscovery– Someone finds a new security holeSomeone finds a new security hole– Writes an exploitWrites an exploit
• PatchPatch– Exploit published, or people notice attacksExploit published, or people notice attacks– Vendor issues a patchVendor issues a patch
• AutomationAutomation– Someone automates the attack, writes a GUISomeone automates the attack, writes a GUI– Hordes of talentless script-kiddies go to workHordes of talentless script-kiddies go to work
• Because many systems don’t have the patchBecause many systems don’t have the patch
SECURITY INNOVATION ©200322
A Problem of DefinitionA Problem of Definition
• What constitutes secure software?What constitutes secure software?• Boils down to: What do you trust?Boils down to: What do you trust?
– Any software Any software mustmust trust something trust something
• Make these trust assumptions explicitMake these trust assumptions explicit– The best we can doThe best we can do– A secure system means that all successful A secure system means that all successful
attacks somehow compromise the trusted attacks somehow compromise the trusted basebase
SECURITY INNOVATION ©200323
Attacking Outside the Attacking Outside the BoxBox
• Recognizing trust assumptions can be hardRecognizing trust assumptions can be hard• Famous example: Smart CardsFamous example: Smart Cards
– Contain very sensitive informationContain very sensitive information– Significant investment in making them secureSignificant investment in making them secure
• Can’t get at private info without authenticationCan’t get at private info without authentication
• The attack?The attack?– Beat the Smart Card with a hammerBeat the Smart Card with a hammer– In significant number of cases, allows data to be readIn significant number of cases, allows data to be read
SECURITY INNOVATION ©200324
A Selection of Currently A Selection of Currently Popular AttacksPopular Attacks
• Buffer overflows Buffer overflows (Separate Module)(Separate Module)
• Race conditions Race conditions (Separate Module)(Separate Module)
• Failing openFailing open• Misplaced trustMisplaced trust
SECURITY INNOVATION ©200325
Stack SmashingStack Smashing
• Buffer overruns can alter the control flow of Buffer overruns can alter the control flow of your program!your program!– char buffer[100]; /* stack allocated array */char buffer[100]; /* stack allocated array */
100 *sizeof(char)
0 1 2 99 return address
SECURITY INNOVATION ©200326
Here’s An Interesting Here’s An Interesting IdeaIdea
• char buf[104] = { ‘ ‘,…,’ ‘, char buf[104] = { ‘ ‘,…,’ ‘, magic 4 charsmagic 4 chars } }
100 *sizeof(char)
0 1 2 99 return address
(**)
100 *sizeof(char)
0 1 2 99 return address
magic 4 chars
SECURITY INNOVATION ©200327
DiscussionDiscussion
• How is this possible? How is this possible? • Unanticipated interaction of two Unanticipated interaction of two
features:features:– Unchecked array operationsUnchecked array operations– Stack-allocated arraysStack-allocated arrays
• Knowledge of frame layout allows prediction of Knowledge of frame layout allows prediction of where array and return address are storedwhere array and return address are stored
– Note the “magic cast” from char’s to an Note the “magic cast” from char’s to an addressaddress
SECURITY INNOVATION ©200328
Buffer Overrun SummaryBuffer Overrun Summary
• Buffer overruns are extremely commonBuffer overruns are extremely common– > 50% of all CERT advisories> 50% of all CERT advisories
• Often very hard to findOften very hard to find– Persist for yearsPersist for years– Refutation of “all bugs are shallow” ideaRefutation of “all bugs are shallow” idea
• But, easy to avoidBut, easy to avoid– Secure coding practicesSecure coding practices– Using a ‘safe’ programming languageUsing a ‘safe’ programming language
SECURITY INNOVATION ©200329
Buffer OverflowBuffer Overflow
• Single largest cause of vulnerabilities in Single largest cause of vulnerabilities in CERT advisoriesCERT advisories
• Buffer overflow threatens Internet Buffer overflow threatens Internet --WSJ(1/30/01)--WSJ(1/30/01)
SECURITY INNOVATION ©200330
Déjà vu…. All Over Again Déjà vu…. All Over Again
• IgnoranceIgnorance• C is difficult to use securelyC is difficult to use securely
– Unsafe functionsUnsafe functions– Confusing APIsConfusing APIs
• Even security aware programmers make Even security aware programmers make mistakes.mistakes.
• Security Knowledge has not been Security Knowledge has not been codified into the development processcodified into the development process
SECURITY INNOVATION ©200331
Race ConditionsRace Conditions
• Basic attackBasic attack– Program assumes some operation is atomicProgram assumes some operation is atomic
• But it is notBut it is not
– Attacker tries to intervene at the magic Attacker tries to intervene at the magic momentmoment• Often attacker will lose the raceOften attacker will lose the race• But he only needs to win onceBut he only needs to win once
• Many examples with file systemsMany examples with file systems– Program checks permissions, then opens the Program checks permissions, then opens the
filefile– Attacker substitutes own file in betweenAttacker substitutes own file in between
SECURITY INNOVATION ©200332
A Fun ExampleA Fun Example
• Early versions of Early versions of Netscape stored Netscape stored cryptographic key in cryptographic key in known place in the binaryknown place in the binary
• AttackAttack– Malicious server on local Malicious server on local
network serves it’s own network serves it’s own version of that page with version of that page with its own keyits own key
– Eavesdrops on traffic Eavesdrops on traffic afterwards and decrypts afterwards and decrypts secretssecrets
serverserver
PCPC
maliciousmalicious
serverserver
SECURITY INNOVATION ©200333
Failing Open: Java RMIFailing Open: Java RMI
• RMI: Remote Method InvocationRMI: Remote Method Invocation– The building block for distributed JavaThe building block for distributed Java
• Before RMI can be usedBefore RMI can be used– Client/server must agree on transfer protocolClient/server must agree on transfer protocol– Default: no encryptionDefault: no encryption– Can negotiate for encrypted channelCan negotiate for encrypted channel
• What happens if client/server don’t What happens if client/server don’t share a secure protocol?share a secure protocol?
SECURITY INNOVATION ©200334
The HoleThe Hole
• SolutionSolution– Client downloads protocol from the serverClient downloads protocol from the server– Makes upgrading clients to new protocols Makes upgrading clients to new protocols
easyeasy– But a huge security hole!But a huge security hole!
• The server is not authenticated at this stageThe server is not authenticated at this stage
• Not the only security flaw found in RMINot the only security flaw found in RMI– But perhaps the worstBut perhaps the worst
SECURITY INNOVATION ©200335
Misplaced TrustMisplaced Trust
What’s wrong with the following C code?What’s wrong with the following C code?
printf(s);printf(s);
SECURITY INNOVATION ©200336
Format String Format String VulnerabilitiesVulnerabilities
Any call that passes user-supplied input directly to aAny call that passes user-supplied input directly to a*printf()*printf()-family function is dangerous. These calls can-family function is dangerous. These calls canAlso be identified by their argument deficiency.Also be identified by their argument deficiency.Consider this code:Consider this code:
printf(“%s“, userdata);printf(“%s“, userdata);
printf(userdata);printf(userdata); Argument deficiency
SECURITY INNOVATION ©200337
Format String Format String VulnerabilitiesVulnerabilities
• Problem: Problem: – Adversary-controlled format stringsAdversary-controlled format strings
s = <data-from-network>s = <data-from-network>
printf(s);printf(s);
– Attacker could set Attacker could set s = “...%n...”s = “...%n...” to write to to write to memorymemory
• Lots of these bugs in the wildLots of these bugs in the wild– New ones weekly on bugtraqNew ones weekly on bugtraq
SECURITY INNOVATION ©200338
Building Secure SystemsBuilding Secure Systems
• Implementing security features is not Implementing security features is not the same as having a secure systemthe same as having a secure system– Security is not being “buzzword compliant”Security is not being “buzzword compliant”
• Security must be designed in, not bolted Security must be designed in, not bolted onon– Requirements or architecture changes are Requirements or architecture changes are
50 to 200 times more expensive to fix50 to 200 times more expensive to fix
• Most humans are not experts in security Most humans are not experts in security – Choose bad passwords or write them downChoose bad passwords or write them down– Security “gets in the way”Security “gets in the way”
SECURITY INNOVATION ©200339
Designing Secure Designing Secure SoftwareSoftware
• Nominate a security czarNominate a security czar• Model security threatsModel security threats• Mitigate security threatsMitigate security threats
SECURITY INNOVATION ©200340
Security CzarSecurity Czar
• Building secure systems requires Building secure systems requires specific knowledge, training and mindsetspecific knowledge, training and mindset
• Security Czar is the focal point of Security Czar is the focal point of security-related issuessecurity-related issues– Stay abreast of security issuesStay abreast of security issues– Provides security education to coworkersProvides security education to coworkers– Review code for security issuesReview code for security issues– Assist in security bug analysisAssist in security bug analysis
SECURITY INNOVATION ©200341
Threat ModelingThreat Modeling
• You cannot build secure systems unless You cannot build secure systems unless you know the threats to which you are you know the threats to which you are susceptiblesusceptible
• Brainstorm about:Brainstorm about:– Which assets need protecting?Which assets need protecting?– What value are the assets?What value are the assets?– What threats are the assets susceptible to?What threats are the assets susceptible to?– Prioritize threatsPrioritize threats– How do you mitigate the threats?How do you mitigate the threats?
SECURITY INNOVATION ©200342
Assets that Software Assets that Software ProtectsProtects
• Configuration DataConfiguration Data• Authentication DataAuthentication Data• Persistent DataPersistent Data• Data ‘on the wire’Data ‘on the wire’• State DataState Data• Temporary DataTemporary Data
SECURITY INNOVATION ©200343
Threats to SoftwareThreats to Software
• Spoofing user IdentitySpoofing user Identity• Tampering with DataTampering with Data• RepudiationRepudiation• Information DisclosureInformation Disclosure• Denial of ServiceDenial of Service• Elevation of Privilege Elevation of Privilege
SECURITY INNOVATION ©200344
Risk ManagementRisk Management
• Chance of attack occurringChance of attack occurring– 1 = high, 10 = low1 = high, 10 = low– How much effort/cost/time is required to How much effort/cost/time is required to
mount the attack?mount the attack?
• What’s the cost/damage if attack What’s the cost/damage if attack occurs?occurs?– 1 = little, 10 = massive1 = little, 10 = massive
• Risk = Damage / ChanceRisk = Damage / Chance• Goal is to reduce riskGoal is to reduce risk• Do high-risk items firstDo high-risk items first
SECURITY INNOVATION ©200345
Threat MitigationThreat Mitigation
• Secure coding techniquesSecure coding techniques• Assume external systems are insecureAssume external systems are insecure• Run with least privilegeRun with least privilege• Don’t store secretsDon’t store secrets• Don’t trust user inputDon’t trust user input• Secure failure and defaultsSecure failure and defaults• Technology is not a panaceaTechnology is not a panacea
SECURITY INNOVATION ©200346
Secure Coding Secure Coding TechniquesTechniques
• Things to avoidThings to avoid– Buffer overruns (#1 problem in the industry)Buffer overruns (#1 problem in the industry)
• Typically an issue for C/C++ onlyTypically an issue for C/C++ only• VB / Java / C# dramatically reduces the chance of VB / Java / C# dramatically reduces the chance of
buffer overruns in your codebuffer overruns in your code
– NULL Access Control ListsNULL Access Control Lists– Predictable random numbersPredictable random numbers– Roll your own cryptographyRoll your own cryptography– Decisions based on file namesDecisions based on file names
SECURITY INNOVATION ©200347
Defense in DepthDefense in Depth
• Assume external systems are insecureAssume external systems are insecure– ““We’re secure; we use a firewall!”We’re secure; we use a firewall!”
• Assume your code is the last piece standingAssume your code is the last piece standing– Plan on failurePlan on failure
• More levels of security means more work for More levels of security means more work for the hacker, therefore less likely to be hackedthe hacker, therefore less likely to be hacked– Remember, threat risk goes down as threat Remember, threat risk goes down as threat
difficulty goes up difficulty goes up
• Never depend on security through obscurityNever depend on security through obscurity
SECURITY INNOVATION ©200348
Run with Least PrivilegeRun with Least Privilege
• Do not require your applications to run with Do not require your applications to run with excessive privilegeexcessive privilege– ““If we don’t run as admin, the features break!”If we don’t run as admin, the features break!”
• Administrator and Local System accounts Administrator and Local System accounts have rights to do anything on the serverhave rights to do anything on the server– If an application running in these accounts is If an application running in these accounts is
hacked, the hacker has full control of the boxhacked, the hacker has full control of the box
• Running applications with minimum Running applications with minimum privilege limits the damage that can be privilege limits the damage that can be caused if (and when) an application gets caused if (and when) an application gets hackedhacked
SECURITY INNOVATION ©200349
Don’t Store SecretsDon’t Store Secrets
• Cryptographic methods are only as Cryptographic methods are only as secure as the method used to store the secure as the method used to store the secret keyssecret keys
• If possible, never store secretsIf possible, never store secrets– Store hashes of secretsStore hashes of secrets
• If you have to store secrets, take If you have to store secrets, take appropriate measures to ensure securityappropriate measures to ensure security– Access Control ListsAccess Control Lists– Use Windows CryptoAPIUse Windows CryptoAPI– Use External Hardware Devices (smart card)Use External Hardware Devices (smart card)
SECURITY INNOVATION ©200350
Don’t Trust User InputDon’t Trust User Input
• Data must be validated as it crosses Data must be validated as it crosses between untrusted and trusted between untrusted and trusted environmentsenvironments– Most vulnerabilities rely on malicious inputMost vulnerabilities rely on malicious input
• Don’t rely on client side validationDon’t rely on client side validation– Hacker tools exist to bypass client validationHacker tools exist to bypass client validation
• All user input is bad until proved otherwiseAll user input is bad until proved otherwise– Use Regular Expressions to validate inputUse Regular Expressions to validate input– Don’t check for invalid data, check for valid Don’t check for invalid data, check for valid
and reject if it’s not validand reject if it’s not valid
SECURITY INNOVATION ©200351
Secure Failure and Secure Failure and DefaultsDefaults
• Secure Failure – Plan on FailureSecure Failure – Plan on Failure– Failure code path should be most secureFailure code path should be most secure– Verify success, not failureVerify success, not failure– Don’t log detailed error into to the clientDon’t log detailed error into to the client
• Secure Defaults – Plan on IgnoranceSecure Defaults – Plan on Ignorance– Don’t rely on the user to turn off features Don’t rely on the user to turn off features
they don’t needthey don’t need– Create solutions in their most secure state, Create solutions in their most secure state,
allow users to turn off security as needed.allow users to turn off security as needed.
SECURITY INNOVATION ©200352
Technology Is Not a Technology Is Not a PanaceaPanacea
• Security is not a destination, it’s a Security is not a destination, it’s a journeyjourney– New breaches are constantly discoveredNew breaches are constantly discovered– New technology invalidates existing New technology invalidates existing
security methodssecurity methods
• Security is about people, process and Security is about people, process and policypolicy– Weak passwords trump strong securityWeak passwords trump strong security– Users will always be the weakest linkUsers will always be the weakest link– Eternal vigilance is the price of securityEternal vigilance is the price of security
SECURITY INNOVATION ©200353
Ten Things You Can DoTen Things You Can Do
• Secure the weakest Secure the weakest linklink
• Defense in depthDefense in depth
• Fail securelyFail securely
• Follow the principle of Follow the principle of least privilegeleast privilege
• CompartmentalizeCompartmentalize
• Keep it Simple, StupidKeep it Simple, Stupid
• Promote PrivacyPromote Privacy
• Avoid secretsAvoid secrets
• Be reluctant to trustBe reluctant to trust
• Use community Use community resourcesresources
SECURITY INNOVATION ©200354
Secure The Weakest LinkSecure The Weakest Link
• There are many points of attackThere are many points of attack• Attackers will go for the easiest attackAttackers will go for the easiest attack
– Today: often buffer overrunsToday: often buffer overruns– Or peopleOr people
• Help desks that give out passwordsHelp desks that give out passwords
• Put your effort into improving the Put your effort into improving the weakest pointsweakest points
SECURITY INNOVATION ©200355
Defense in DepthDefense in Depth
• Don’t assume one line of defense is Don’t assume one line of defense is enoughenough– E.g., don’t trust a firewall to keep out E.g., don’t trust a firewall to keep out
attackersattackers– Encrypt sensitive data as wellEncrypt sensitive data as well– Authenticate client/server transactionsAuthenticate client/server transactions
• Even behind the firewallEven behind the firewall
• Easy to do, andEasy to do, and– Slows down attackersSlows down attackers– Limits the damage they can doLimits the damage they can do
SECURITY INNOVATION ©200356
Fail SecurelyFail Securely
• Check that exceptional cases are as Check that exceptional cases are as secure as the common casesecure as the common case– Don’t be Java RMIDon’t be Java RMI
• Warning!Warning!– Often squarely at odds with convenience, Often squarely at odds with convenience,
unless carefully thought out in advanceunless carefully thought out in advance– Example: remote upgradeExample: remote upgrade
SECURITY INNOVATION ©200357
The Principle of Least The Principle of Least PrivilegePrivilege
• Don’t use more privileges than neededDon’t use more privileges than needed– Limits the damage if compromisedLimits the damage if compromised
• ExampleExample– Unix requires root privilege to bind to port < Unix requires root privilege to bind to port <
10241024• Why? It’s ancient history . . .Why? It’s ancient history . . .
– Once on a port, most apps can give up root Once on a port, most apps can give up root privilegeprivilege• But they often don’tBut they often don’t
SECURITY INNOVATION ©200358
CompartmentalizeCompartmentalize• Break system into unitsBreak system into units
– Compromise of any one unit incurs limited Compromise of any one unit incurs limited damagedamage
– Most important: clients and serversMost important: clients and servers
• Modularity, with a twistModularity, with a twist– Isolated components do not fully trust each Isolated components do not fully trust each
otherother
• Hard to use, except at coarse granularityHard to use, except at coarse granularity– For example, no OS is compartmentalized For example, no OS is compartmentalized
wrt device driverswrt device drivers
SECURITY INNOVATION ©200359
Keep It Simple, StupidKeep It Simple, Stupid
• Simple systems more likely to be secureSimple systems more likely to be secure– And simplicity is a good idea anywayAnd simplicity is a good idea anyway
• Use “chokepoints”Use “chokepoints”– Interfaces through which security-critical actions must Interfaces through which security-critical actions must
passpass– No backdoors, no exceptions!No backdoors, no exceptions!
• Pay attention to usabilityPay attention to usability– Assume users maximally lazyAssume users maximally lazy– Won’t read documentation, change security settings, etc.Won’t read documentation, change security settings, etc.– Must be reasonably secure without interventionMust be reasonably secure without intervention
SECURITY INNOVATION ©200360
Promote PrivacyPromote Privacy
• Privacy is a security concern for most Privacy is a security concern for most usersusers
• Example: credit card informationExample: credit card information– Applications never display credit card once Applications never display credit card once
enteredentered– Don’t know who is looking at the displayDon’t know who is looking at the display
SECURITY INNOVATION ©200361
Avoid Relying on SecretsAvoid Relying on Secrets
• Don’t assume information in binaries is Don’t assume information in binaries is secretsecret– The Netscape exampleThe Netscape example
• Don’t assume server-side information is Don’t assume server-side information is secretsecret– E.g., credit card thefts from web serversE.g., credit card thefts from web servers
• In general, keeping secrets is very difficultIn general, keeping secrets is very difficult– Some secrets will be necessarySome secrets will be necessary– Try to minimize the amount of secret Try to minimize the amount of secret
informationinformation
SECURITY INNOVATION ©200362
Be Reluctant to TrustBe Reluctant to Trust
• Be aware of potential for adversary Be aware of potential for adversary controlcontrol– Of inputsOf inputs– Of other programsOf other programs– Of your environmentOf your environment– Don’t automatically trust any of these!Don’t automatically trust any of these!
• ExampleExample– Set Set LD_LIBRARY_PATH = “/tmp/attack”LD_LIBRARY_PATH = “/tmp/attack”– What happens when your program loads a What happens when your program loads a
dll?dll?
SECURITY INNOVATION ©200363
Use Community Use Community ResourcesResources
• Tempted to write your own crypto Tempted to write your own crypto library?library?– Don’t!Don’t!
• There are good building blocks out thereThere are good building blocks out there– Libraries written by security expertsLibraries written by security experts– Code that has withstood the test of timeCode that has withstood the test of time
• Use these resourcesUse these resources
SECURITY INNOVATION ©200364
Construction Principles Construction Principles for Secure Programsfor Secure Programs
[Not listed in order of importance.][Not listed in order of importance.]
1.1. Do not assume that inputs are valid. E.g., Do not assume that inputs are valid. E.g., a.a. if an argument should be a positive integer in the range of 2 to 7, if an argument should be a positive integer in the range of 2 to 7,
verify that. verify that. b.b. If an argument should be a non-empty string of letters not If an argument should be a non-empty string of letters not
exceeding 13 characters in length, verify that. exceeding 13 characters in length, verify that. c.c. Check interactive input to be sure it contains only "good" Check interactive input to be sure it contains only "good"
characters. Consider how such input will be parsed when characters. Consider how such input will be parsed when substituted. substituted.
d.d. Check arguments passed in environment variables. Check arguments passed in environment variables. 2.2. Check return code of all system call parameters and system Check return code of all system call parameters and system
calls. System calls should verify their arguments, but calls. System calls should verify their arguments, but unfortunately most OS calls do not for fear of becoming unfortunately most OS calls do not for fear of becoming inefficient, so you must. Fortunately, all system calls return inefficient, so you must. Fortunately, all system calls return a success or failure code. Unfortunately, only a few a success or failure code. Unfortunately, only a few programs verify these result codes. programs verify these result codes.
SECURITY INNOVATION ©200365
Construction Principles for Construction Principles for Secure Programs Secure Programs
3.3. Buffer Overflow. Buffer Overflow. a.a. Do bounds checking on every variable before the contents are Do bounds checking on every variable before the contents are
copied to a local buffer. copied to a local buffer. b.b. Avoid routines that fail to check buffer boundaries when Avoid routines that fail to check buffer boundaries when
manipulating strings, particularly: manipulating strings, particularly: sprintf(), fscanf(), sprintf(), fscanf(), scanf(), vsprintf(), realpath(), getopt(), getpass(), scanf(), vsprintf(), realpath(), getopt(), getpass(), streadd(), strecpy(), strtrns(), gets(), strcpy(), and streadd(), strecpy(), strtrns(), gets(), strcpy(), and strcat()strcat()
4.4. Always use full pathnames for any files and directories. The Always use full pathnames for any files and directories. The current directory assumed by your program may not be where current directory assumed by your program may not be where it is at. it is at.
a.a. Explicitly change directories (Explicitly change directories (chdirchdir()) to an appropriate directory ()) to an appropriate directory at program start. at program start.
b.b. If creating a new file, use If creating a new file, use O_EXCLO_EXCL and and O_CREATO_CREAT flags to assure that flags to assure that the file does not already exist. the file does not already exist.
c.c. Do not create files in world-writable directories. Do not create files in world-writable directories. d.d. Use lstat() to make sure a file is not a link, if appropriate. Use lstat() to make sure a file is not a link, if appropriate. e.e. Set limit values to disable creation of a core file if the program fails. Set limit values to disable creation of a core file if the program fails. f.f. If using temporary files, consider using If using temporary files, consider using tmpfile()tmpfile() or or mktemp()mktemp()
system calls to create them (although most system calls to create them (although most mktempmktemp() library calls () library calls have race conditions). have race conditions).
SECURITY INNOVATION ©200366
Construction Principles for Construction Principles for Secure Programs Secure Programs
5.5. Logging Events. Do log relevant information, including date, Logging Events. Do log relevant information, including date, time, uid and effective uid, gid and effective gid, terminal time, uid and effective uid, gid and effective gid, terminal information, pid, command-line arguments, errors, and information, pid, command-line arguments, errors, and originating host. Make sure that the log files themselves originating host. Make sure that the log files themselves remain bounded in size. remain bounded in size.
6.6. Make the program's critical portion as short and simple as Make the program's critical portion as short and simple as possible. possible.
7.7. Be aware of race conditions, deadlock conditions and Be aware of race conditions, deadlock conditions and sequencing conditions. sequencing conditions.
8.8. Do not require clear-text authentication information. Do not require clear-text authentication information.
SECURITY INNOVATION ©200367
Construction Principles for Construction Principles for Secure Programs Secure Programs
9.9. Use session encryption to avoid session hijacking and hide Use session encryption to avoid session hijacking and hide authentication information. authentication information.
10.10. Never use system() and popen() system calls Never use system() and popen() system calls 11.11. Avoid creating setuid or setgid shell scripts Avoid creating setuid or setgid shell scripts 12.12. Do not make assumptions about port numbers, use Do not make assumptions about port numbers, use
getservbyname() instead. Do not assume connections from getservbyname() instead. Do not assume connections from well-known ports are legitimate or trustworthy. Do not well-known ports are legitimate or trustworthy. Do not assume the source IP address is legitimate. Place timeouts assume the source IP address is legitimate. Place timeouts and load level limits on incoming network-oriented read and load level limits on incoming network-oriented read request. Place timeouts on outgoing network-oriented write request. Place timeouts on outgoing network-oriented write requests. requests.
13.13. Robust Compilation and Libraries. Use tools such as lint, and Robust Compilation and Libraries. Use tools such as lint, and splint. Have internal consistency-checking code. Use your splint. Have internal consistency-checking code. Use your compiler wisely. With gcc, use -Wall -ansi -pedantic flags. compiler wisely. With gcc, use -Wall -ansi -pedantic flags. Use safe libraries.Use safe libraries.
SECURITY INNOVATION ©200368
Construction Principles Construction Principles for Secure Programsfor Secure Programs
14.14. Have code reviewed by other people. E.g., commercial Have code reviewed by other people. E.g., commercial products such as 3Com's CoreBuilder and SuperStack II products such as 3Com's CoreBuilder and SuperStack II hubs were revealed to have "secret" backdoor passwords. hubs were revealed to have "secret" backdoor passwords.
15.15. Test thoroughly. Test the software using the same methods Test thoroughly. Test the software using the same methods that crackers do: Try to overflow every buffer in the that crackers do: Try to overflow every buffer in the package, Try to abuse command line options, Try to create package, Try to abuse command line options, Try to create every race condition conceivable. Have others besides the every race condition conceivable. Have others besides the designers and implementers test the code. Be aware of test designers and implementers test the code. Be aware of test coverage; gcc -pg -a causes the program to produce a bb.out coverage; gcc -pg -a causes the program to produce a bb.out file that is helpful in determining how effective your tests are file that is helpful in determining how effective your tests are at covering all branches of the code. at covering all branches of the code.
16.16. Use formal specifications. At a minimum, develop pre- and Use formal specifications. At a minimum, develop pre- and post-conditions in carefully written English.post-conditions in carefully written English.
SECURITY INNOVATION ©200369
Programs that Must be Programs that Must be Secure Secure
• The OS kernel. The OS kernel. • All setuid and setgid programs. All setuid and setgid programs. • All daemons/services that accept All daemons/services that accept
network connections. network connections.
SECURITY INNOVATION ©200370
Practical Advice on WritingPractical Advice on WritingPre- Post-ConditionsPre- Post-Conditions
• Signatures Signatures • Procedures and Functions that Alter Procedures and Functions that Alter
Globals Globals • Robustness Tests Robustness Tests • Some Useful Predicates Some Useful Predicates
SECURITY INNOVATION ©200371
ConclusionConclusion
• Writing secure software is hardWriting secure software is hard– The state of practice is extremely poorThe state of practice is extremely poor– Current ease of buffer-overrun attacks Current ease of buffer-overrun attacks
masks other problemsmasks other problems– It will be a long time before we have a It will be a long time before we have a
“trustworthy computing” base“trustworthy computing” base
• It is not difficult to do a reasonably good It is not difficult to do a reasonably good jobjob– As a developer you can help!As a developer you can help!