bryan sullivan senior security program manager...
TRANSCRIPT
Agenda
Introduction to the SDLSecure coding practices for ASP.NET and the OWASP Top 10SDL tools demonstrationsSDL-Agile (if we have time and interest…)
Cybercrime evolution
LANs First PC virusMotivation: damage
1986–1995
Internet Era “Big Worms”Motivation: damage
1995–2003
OS, DB attacksSpyware, SpamMotivation: Financial
2004+
Targeted attacksSocial engineeringFinancial + Political
2006+
Attacks are focusing on applications
Calculated from the Microsoft Security Intelligence Report V6
0%
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
% of vulnerability disclosures:Operating system vs browser and application
vulnerabilities
OS vulns Browser vulns Application vulns
Most vulnerabilities are in smaller organizations’ applications
11%89%
Vendors' accountability for vulnerabilities
Top 5 ISVsOthers
Sources: IBM X‐Force 2008 Security Report
The Microsoft SDL
Administer and track security training
IncidentResponse (MSRC)
Sign up with SECDefine business ownerDefine security lead
Define product-specific security measures Meet SDL requirements
Guide product teams to meet SDL requirements
Security engineeringFeedback for SDL improvements
Establish release criteria and sign-off as part of FSR
Meetrelease criteria
Ongoing Process Improvements
Education Process Accountability
Training Requirements Design Implementation Verification Release ResponseTraining Requirements Design Implementation Verification Release Response
Windows: 45% reduction of vulnerabilities
Source: Windows Vista One Year Vulnerability Report, Microsoft Security Blog 23 Jan 2008
11966
400
242
157
Windows XP Windows Vista OS I OS II OS III
Total vulnerabilities disclosed one year after release
Before SDL After SDL
45% reduction in vulnerabilities
Microsoft SDL and SQL Server
Sources: Analysis by Jeff Jones (Microsoft technet security blog)
34
3
187
SQL Server 2000 SQL Server 2005 Competing commercial DB
Before SDL After SDL
91% reduction in Vulnerabilities
Total Vulnerabilities Disclosed 36 Months After Release
Microsoft SDL and Internet Explorer (IE)
Source: Browser Vulnerability Analysis, Microsoft Security Blog 27-NOV-2007
18 14
8
3
Internet Explorer 6 Internet Explorer 7
Medium High
Before SDL After SDL
35% reduction in vulnerabilities63% reduction in high severity vulnerabilities
Vulnerabilities Fixed One Year After Release
Secure Software Development Requires Process Improvement
Simply “looking for bugs” doesn’t make software secure
Must reduce the chance vulnerabilities enter into design and code
Requires executive commitment
Requires ongoing process improvement
Requires education & training
Requires tools and automation
Requires incentives and consequences
OWASP Top 10
InjectionCross-Site ScriptingBroken Authentication and Session ManagementInsecure Direct Object ReferencesCross-Site Request ForgerySecurity MisconfigurationInsecure Cryptographic StorageFailure to Restrict URL AccessInsufficient Transport Layer ProtectionUnvalidated Redirects and Forwards
Looks innocent enough…
String sql = "SELECT * FROM [Users] WHERE username = '" + Request["username"] + "' AND password = '" + Request["password"] + "'";
bryansul
Elv1sL1ves4ever#
SELECT * FROM [Users] WHERE username = 'bryansul' AND password = 'Elv1sL1ves4ever#'
…but roguery abounds
String sql = "SELECT * FROM [Users] WHERE username = '" + Request["username"] + "' AND password = '" + Request["password"] + "'";
admin
' OR '1' = '1
SELECT * FROM [Users] WHERE username = 'admin' AND password = '' OR '1='1'
SQL Injection in the News
7-Eleven
Dave & Busters
BJ’s Wholesale Club
OfficeMax
Boston Market
Barnes & Noble
Sports AuthorityForever 21
DSW
Use Stored Procedures
Bad code:
SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE CustomerId = '" + customerId + "'");
Good code:
SqlCommand command = new SqlCommand("GetCustomer");command.CommandType = CommandType.StoredProcedure;command.Parameters.Add(new SqlParameter("@customerId",customerId);
Use Parameterized Queries
Bad code:
SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE CustomerId = '" + customerId + "'");
Good code:
SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE CustomerId = @customerId");
command.Parameters.Add(new SqlParameter("@customerId",customerId);
Use LINQ
But don’t use ExecuteQuery
Bad code:ExecuteQuery<Customer>("SELECT * FROM Customers");
Good code:from c in this.Customers select c;
Avoid EXEC @sql
Moving the string concatenation to the stored proc code still leaves you vulnerable…
EXEC ('SELECT * FROM Customers WHERE CustomerId = ''' + @CustomerId + ''')
The only approved use of EXEC is to call other stored procedures
Remove Database Privileges
Allow only EXECUTE privileges on the necessary stored procedures
All other privileges on all objects must be removed
This is defense in depth
XSS is the new buffer overflowBuffer overflows are a path to own the machine…
…but owning a machine is only a means to an end.
Steal private dataLog victims’ keystrokesCreate botnets for DDoS attacksLaunch self-propagating webwormsCreate darknets to trade pirated software or pornography
You can do all of these with XSS, and it’s a lot easier
Input ValidationEnsure the data is what the application expects
FormatLength
Regular expressions can work great hereSystem.Text.RegularExpressions.RegexSystem.Web.UI.WebControls.RegularExpressionValidator
Be careful with your regexes!
ValidateRequestPage directive
<%@ Page ValidateRequest="true" %>
Web.config setting<configuration><system.web><pages validateRequest="true" />
</system.web></configuration>
More of a defense-in-depth measureDon’t rely solely on ValidateRequest
EnableViewStateMac
Page directive<%@ Page EnableViewStateMac="true" %>
Web.config setting<configuration><system.web><pages enabledViewStateMac="true" />
</system.web></configuration>
ViewStateUserKeyBuilt-in canary defense for ASPX pages
protected void Page_Init(object sender, EventArgs e){this.ViewStateUserKey = Session.SessionID;
}
Use AntiForgeryToken for ASP.NET MVC
The Same Origin PolicyTwo frames/windows can only communicate with each other if they have the same origin
Origin is defined as having the same:DomainPortProtocol
Also applies to XMLHttpRequest
SOP Example
If my page is http://www.mysite.com/foo/bar.aspx
Page Allowed? Why?
http://blogs.mysite.com/page.aspx No Different domain
https://www.mysite.com/page.aspx No Different protocol
http://www.mysite.com:81/page.aspx No Different port
http://mysite.com/page.aspx No Different domain
http://www.mysite.com/bar/page.aspx Yes Everything ok
Take a guess…
Take a guess…
Take a guess…
Take a guess…
Take a guess…
Document.Domain
Two cooperating pages can lower their domain so they can talk to each other
Do not lower document.domain unless all data and functionality on the site is public
No authenticated accessNo PII
Cross-Domain Access PoliciesUsed by Flash, Silverlight
crossdomain.xmlclientaccesspolicy.xml
<cross-domain-policy><allow-access-from domain="www.good.com"/><allow-access-from domain="*.net"/><allow-access-from domain="*"/>
</cross-domain-policy>
Crypto Algorithm Requirements
AlgorithmType
Banned Allowed Recommended
Symmetric block DES, DESX, RC2, SKIPJACK
3DES (2 or 3 key)
AES (>= 128 bit)
Symmetric stream
SEAL, CYLINK_MEK, RC4 (<128 bit or unreviewed)
RC4 (reviewed and >= 128 bit)
None – block cipher is preferred
Asymmetric RSA (<2048 bit),Diffie-Hellman (<2048 bit)
RSA (>= 2048 bit), Diffie-Hellman (>= 2048 bit)
RSA (>= 2048 bit), Diffie-Hellman (>= 2048 bit), ECC (>= 256 bit)
Hash (includes HMAC usage)
SHA-0 (SHA), SHA-1, MD2, MD4, MD5
SHA-2 SHA-2
HMAC key lengths
<112 bit >= 112 bit >= 128 bit
.NET Crypto LibrariesSystem.Security.Cryptography
AESAESCryptoServiceProvider (XP SP2 & later)AESManaged
RSARSACryptoServiceProvider
ECCECDiffieHelmanCng
SHA-2SHA256CryptoServiceProvider (Windows 2003)SHA384CryptoServiceProvider (Windows 2003)SHA512CryptoServiceProvider (Windows 2003)SHA256Cng (Vista)SHA384Cng (Vista)SHA512Cng (Vista)
Crypto systems get broken
Why assume that current algorithms really are unbreakable, unlike every other time in
the history of cryptography?
eh vxuh wr gulqn brxu rydowlqhbe sure to drink your ovaltine
Solution
Plan for this from the beginning
Assume the crypto algorithms you use will be defeated in your application’s lifetime
Code your apps in a cryptographically agile manner
.NET top-level abstract classes
SymmetricAlgorithmAsymmetricAlgorithmHashAlgorithm
KeyedHashAlgorithm○ HMAC
RandomNumberGenerator
.NET Crypto ArchitectureHashAlgorithm
+ComputeHash()
SHA512
SHA512Cng SHA1ManagedSHA512Managed
#HashCore()+Create()
SHA1
.NET examples
More agile:
HashAlgorithm hashObj = HashAlgorithm.Create("MD5");
byte[] result = hashObj.ComputeHash(data);
Steps toward crypto agility
Step 1: Avoid hardcoded algorithmsStep 2: Reconfigure the algorithm provider
Altering machine.config
<configuration><mscorlib> <cryptographySettings>
<nameEntry name="MD5" class="MyPreferredHash" />
<cryptoClasses><cryptoClassMyPreferredHash="SHA512Cng, …" />
</cryptoClasses>
Remapping algorithm names is dangerous
MD5 SHA-1This is a good thing, right?What could possibly go wrong?
Steps toward crypto agility
Step 1: Avoid hardcoded algorithmsStep 2: Avoid hardcoded implementationsStep 3: Reconfigure the algorithm providerStep 3 (alternate): Avoid default algorithm names
HashAlgorithm.Create("ApplicationFooPreferredHash");
Enable Custom Errors<configuration><system.web><customErrors mode=“RemoteOnly”/>
Why give attackers more information to attack you with?
Disable Tracing<configuration><system.web><trace enabled="false"/>
Ensure no Page directives override the application-level tracing
Bad: <%@ Page Trace="true" %>Good: <%@ Page Trace="false" %> or no Trace directive specified
Disable cookieless session state
<configuration><system.web>
<sessionState cookieless=”UseCookies”>
What kind of attacks could sessionless URLs enable?
http://myserver/MyApp/(123ABC)/default.aspx
Disable cookieless authentication
<configuration><system.web>
<authentication mode=”Forms”><forms cookieless=”UseCookies”>
Same problem as before
Require SSL for auth cookies<configuration><system.web>
<authentication mode=”Forms”><forms requireSSL=”true”>
Disable “sliding” expiration<configuration><system.web>
<authentication mode=”Forms”><forms slidingExpiration=“false”>
Expert Advice?“…the developer should be able to define a very strong validation pattern, usually based on regular expressions, for validating [user] input.”
OWASP SQL Injection Prevention Cheat Sheet
“Regular expressions are a good way to validate text fields such as names, addresses, phone numbers, and other user information.”
MSDN Patterns & Practices
“Regex is a perfect tool for input validation.”Bryan Sullivan, Ajax Security
71
The Root of the Problem
Example 1: ^\d+$Evaluate this pattern against test input: 123456X
123456 [no match, backtrack]12345 [no match, backtrack]1234 [no match, backtrack]123 [no match, backtrack]12 [no match, backtrack]1 [no match]
Fails in 13 steps (including backtracks)• Operates in O(n) time
72
Exponential Execution
Example 2: ^(\d+)+$Evaluate this pattern against test input: 123456X
123456 [no match, backtrack]12345123456 [no match, backtrack]123 45123456 [no match, backtrack]…
Fails in 223 steps• Operates in O(2n) time
73
More Irony…
“Just as we perform whitelist input validation on the server for security purposes, developers must perform client-side validation to ensure security of their offline applications.”
Ajax Security
75
Detecting Vulnerable Regexes
Look for:Grouping expressions containing repetition that is itself repeatedGroups containing alternation where the alternate subexpressions overlap each other
This is harder than it sounds, and it doesn’t sound easy
76
Regex Testing Strategies
Test each regex clause with a large, valid sample
[email protected]@aaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com
Add one invalid character to the end of the sample
[email protected][email protected]!
Why does this work?
77
XML Entities
Like macros for XML
<!DOCTYPE employees [<!ENTITY companyname "Contoso Inc.">]><employees>
<employee>Bryan S,companyname;</employee><employee>Steve L,&companyname;</employee>
</employees>
79
Nesting Entities
You can nest entities too:
<!DOCTYPE employees [<!ENTITY companyname "Contoso Inc."><!ENTITY divisionname "&companyname; SaaS">]>
80
Exponential Entity Expansion Attack
AKA “The billion laughs attack”
<!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol"><!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2">…<!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8">]><lolz>&lol9;</lolz>
81
Infinite Recursion Entity Expansion?
<!DOCTYPE lolz [<!ENTITY lol1 "&lol2;"><!ENTITY lol2 "&lol1;">]><lolz>&lol1;</lolz>
Fortunately (or unfortunately?) not legal
83
Variation: Quadratic blowup Attack
<!DOCTYPE kaboom [<!ENTITY a "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa…">]><kaboom>&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;…</kaboom>
84
External Entity Attacks
You call pull entity data from external sources too:
<!ENTITY stockprice SYSTEM "http://www.contoso.com/stockticker.ashx">
Attack ideas:Infinite delayVery large file downloadsInfinite data pipeIntranet resource redirection
85
XML Entity Attack Defenses
Reduce as much attack surface as possible:
Best solution: Disable inline DTD processing completely
ProhibitDtd propertyIf you can’t do that, then disable external entity resolution
Set resolver to null, or implement a custom resolver If you can’t do that, then throttle external entity resolution
Will need a custom resolver
86
The Agile Manifesto
Individuals and interactions
Working software
Customer collaboration
Responding to change
Processes and tools
Comprehensive documentation
Contract negotiation
Following a plan
SDL “Classic”
Fits spiral or waterfall……but Agile doesn’t have phases…and it may not even have a release!
Idea: Move SDL to product backlog
Very Agile……but not secure
“Security is not a freakin’ task card.”- Adrian Lane, Securosis
Idea: Drop some requirements
But every requirement is, well, required
Need to keep all requirementsNeed to reorganize into Agile-friendly form
Three classes of requirements
Every Sprint
Training
Threat modeling
etc...
One-Time Only
Set up tracking
Upgrade compilers
etc...
Bucket
Fuzz parsers
Create response
plan
etc…
Requirements as backlog items
One-time requirements get added to the Product Backlog (with deadlines)So do bucket requirementsEvery-sprint requirements go to the Sprint Backlog directly
Product Backlog• Set up tracking system• Upgrade to VS2010• Fuzz image parser• Fuzz network parser• …
Sprint Backlog• Threat model new stored
procedures• Run static analysis• …
Sprint exit criteria
All every-sprint requirements completeNo bucket items over six months oldNo expired one-time requirementsNo open security bugs over the bugbar
Categorization specifics
SDL v5.0 process guidance documentMSF-A+SDL process template
Both available on www.microsoft.com/sdl
Bug bar• EoP: Remote Anonymous• Info Disc: HBI/PIICritical
• EoP: Local Anonymous• DoS: Asymmetric PersistentImportant
• Info Disc: LBI• DoS: TemporaryModerate
• Info Disc: Random memoryLow
Agile Security Challenges
Iterative natureProjects may never endJust-in-time planning/YAGNI mentalityGeneral avoidance of project artifactsEmphasis on project/iteration backlogsGeneral avoidance of automated tools
Security Incident Response
Because 2:00 AM Christmas morning is a poor time to hold a Scrum meeting…
Agile Security Challenges
Iterative natureProjects may never endJust-in-time planning/YAGNI mentalityGeneral avoidance of project artifactsEmphasis on project/iteration backlogsGeneral avoidance of automated tools
Security bug tracking
Must track bug causeBuffer overflowXSSEtc
And effectSTRIDE
Important for bugbar criteria
Threat modeling“The cornerstone of the SDL”
Data Flow Diagrams (DFDs)STRIDE/elementMitigationsAssumptionsExternal dependencies
Agile Security Challenges
Iterative natureProjects may never endJust-in-time planning/YAGNI mentalityGeneral avoidance of project artifactsEmphasis on project/iteration backlogsGeneral avoidance of automated tools
Writing secure code
90% Writing SecureFeatures
Overflow defenseInput validationOutput encoding
10% Writing SecurityFeatures
CryptographyFirewallsACLs
Secure code does not featurize
Not a User Story
Doesn’t go in the Product
Backlog
Can’t get prioritized in or
out
Can’t decide to not do security
this sprint
Taskifying the SDL
Some are straightforward...Enable compiler switchesRun static analysis tools
…some are tougher (not actionable)Avoid banned APIsAccess databases safely
Two strategies
Verify these things by hand (alone or in pairs)Verify these things with tools
www.sondheim.com www.dow.com
Static analysis requirements
FxCopCAT.NETPREFast (/analyze)And/or your alternative tool(s) of choice
These are “every-sprint” requirementsBetter still: Continuous Integration
Dynamic analysis requirementsFuzzers (homegrown)
File parsersRPC interfacesActiveX controlsCOM objects
AppVerifierPassive HTTP traffic analysisAnd/or your alternative tool(s) of choice
These are “bucket” requirementsOr CI…
Secure coding librariesAntiXss/Web Protection LibraryStrSafeSafeInt
Use always, check every sprint
<opinion>
This is the future of the SDL</opinion>
Strengths: Adapting SDL to Agile
Bucket activities easily move in & out of sprintsTeams self-select best security activitiesSDL versioning is simpler and more currentEach iteration is a gate
Strengths: Adapting SDL to Agile
Bucket activities easily move in & out of sprintsTeams self-select best security activitiesSDL versioning is simpler and more currentEach iteration is a gate
“Welcome changing requirements, even late in development. Agile processes harness change
for the customer’s competitive advantage.”
Strengths: Adapting SDL to Agile
Bucket activities easily move in & out of sprintsTeams self-select best security activitiesSDL versioning is simpler and more currentEach iteration is a gate
“At regular intervals, the team reflects on how to become more effective, then tunes and adjusts
its behavior accordingly.”
Strengths: Adapting SDL to Agile
Bucket activities easily move in & out of sprintsTeams self-select best security activitiesSDL versioning is simpler and more currentEach iteration is a gate
SDL-Agile “versioning”
SDL-Classic
Updated yearlyGrandfather clause
SDL-Agile
Updated at any timeAutomatic updating
Strengths: Adapting SDL to Agile
Bucket activities easily move in & out of sprintsTeams self-select best security activitiesSDL versioning is simpler and more currentEach iteration is a gate
Each iteration is a gate
“Security and privacy are most effective when ‘built-in’ throughout the entire development
lifecycle”
“Security is most effective when it is ‘baked-in’ from the start”
This fits Agile perfectly
The Agile Manifesto
Individuals and interactions
Working software
Customer collaboration
Responding to change
Processes and tools
Comprehensive documentation
Contract negotiation
Following a plan
The SDL-Agile Manifesto
Continuous, incremental effort
Automated tasks
Planned incident response
Heroic pushes
Manual processes
Ad-hoc response
More Resources
SDL 5.0 process guidanceMSF-A+SDL process template
http://www.microsoft.com/sdlhttp://blogs.msdn.com/sdl
My alias: bryansul