Michael Howard Principal Security Program Mgr. Microsoft Corp. DPR203 Who Is This Guy? [email protected] Microsoft employee for 17 years Always in security Worked on the SDL since.
Download ReportTranscript Michael Howard Principal Security Program Mgr. Microsoft Corp. DPR203 Who Is This Guy? [email protected] Microsoft employee for 17 years Always in security Worked on the SDL since.
Michael Howard Principal Security Program Mgr. Microsoft Corp. DPR203 Who Is This Guy? [email protected] Microsoft employee for 17 years Always in security Worked on the SDL since inception Agenda The SDL Recommendations vs. Requirements SDL Recommendations and Requirements My Only Objective Give you actionable ideas that will improve the security of your software. Links to tools and other resources are in the speaker notes. IMPORTANT This session does not cover every SDL item This session covers very little privacy and nothing to do with security response and servicing Nor does it cover any internal Microsoft-specific issues The SDL “Reduce the Number of Vulnerabilities in your code.” “Reduce the Severity of the Vulnerabilities you miss.” Does SDL Apply to Your Product? Yes, if… It handles valuable data (e.g., PII, sensitive business/medical data) Has a large customer base Has functional risk Eg: one socket from the ’net Part of an acquisition Recommendations vs. Requirements Requirement is something you must do prior to shipping Recommendation is something you should consider Many requirements start life as recommendations Identify Primary Security & Privacy Contact REQUIREMENT Someone (or some people) must handle the security and privacy for the team ACTION Pick a security person to be the “Security Champ” “Grow” this person if needed Security Training REQUIREMENT Fits into the “rhythm of the product” At least 80% trained ACTION Adopt ongoing training for your team If you have *NEVER* attended *ANY* security training, do so ASAP Track Security Bugs REQUIREMENT Configure your bug database to track security bugs ACTION Create the following in your database: Security Criticality None, Critical, Important, Moderate, Low, Defense in Depth Security Cause None, Buffer overflow/underflow, Arithmetic, SQL injection, Race Condition, XSS, Crypto, etc… Security Effect None, STRIDE Use Strong-Named Assemblies and but not APTCA REQUIREMENT Strong-named assemblies prevent DLL Hell and provide tamper detection Adds a defense: immediate callers must be granted FullTrust AllowPartiallyTrustedCallersAttributes allows partially trusted callers (i.e., code from the ’net) ACTION Run FxCop on your strong-named assemblies Code review CA2116 & CA2117 Consider using SecurityTransparent Use Secure Crypto Design (1 of 3) REQUIREMENT Covers: algorithms, agility, use of standard libs Agility: Do not hard-code algorithms in your code SHA1Managed sha = new SHA1Managed(); ACTION Use a class factory HashAlgorithm alg = HashAlgorithm.Create(“MyAppHash”); Use Secure Crypto Design (2 of 3) ACTION Use Microsoft standard crypto libraries System.Security.Cryptography for managed CryptoAPI, CNG for native Use DPAPI for secrets Use approved random number generators CryptGenRandom rand_s RNGCryptoServiceProvider Use Secure Crypto Design (3 of 3) ACTION Use appropriate algorithms Use: AES (128-bit or better), RSA (2048 or better), SHA-256 (+) Use nothing else! Download SDLCryptoCheck, run on your code and triage results Firewall Requirements REQUIREMENT Firewall setting changes must be logged in the system security log Do not disable the firewall Do not create an inbound rule to allow the traffic through the firewall Cannot allow exception by user without admin privileges Document your networking requirements ACTION See above :-) Threat Models REQUIREMENT Build a threat model for your product Threats to a Windows Azure solution are different threats to a native Windows solution Helps you understand secure design issues Service updates do not need threat modeling ACTION Learn how to do threat modeling, then download the SDL Threat Modeling tool and use it Support UAC REQUIREMENT Most applications should run correctly as normal users and not require unnecessary privileges ACTION Make sure you test your application as a non-admin on Windows Vista or Windows 7 Use Aaron Margosis’ LUABuglight to help ascertain why your application fails as non-admin Or use LuaPriv with Application Verifier Read Writing Secure for Windows Vista Granular Feature Control RECOMMENDATION To reduce attack surface, expose only the most common functionality ACTION Support granular enable/disable features and parsers IIS7 is the poster child Grant Minimal Privileges RECOMMENDATION Applications should run with only enough privilege to perform the tasks required, and no more ACTION (See UAC) and don’t run your services as SYSTEM unless you absolutely must Drop privileges on service startup Use Minimum Code Generation Suite REQUIREMENT We constantly add defenses to the compiler and linker You get defenses for free by simply using the latest compilers ACTION At a minimum, you should use VS 2005 SP1 But highly recommend you use VS 2008 SP1 And VS 2010 when it comes out, especially for C++ Stronger -GS Use /GS REQUIREMENT Applies to 32-bit native C/C++ code only Even if the code is called by Managed code Detects some forms of stack-based buffer overrun at runtime ACTION Compile all native 32-bit C/C++ code with /GS It’s on by default in VC++ 2008, so don’t use /GSConsider using #pragma strict_gs_check(on) Use Safe Exception Handling REQUIREMENT Detects compromised exception handlers C++ and Windows SEH Would have prevented CodeRed ACTION Link with /SAFESEH Use MIDL /ROBUST for RPC/DCOM REQUIREMENT RPC is subject to potentially dangerous input Lots of services use RPC In Windows NT4 server-side proxy code was very trusting We added /ROBUST to MIDL to add more data validation ACTION Always run MIDL with /ROBUST (it’s the default now) Requires Windows 2000 and later Use ASLR REQUIREMENT Applies to all code Randomizes the image in memory, making it harder for attackers to get their exploits working correctly ACTION Link your code with /DYNAMICBASE Use DEP REQUIREMENT Applies to all code Marks memory as “no execute” which can stop some forms of buffer overrun ASLR is required for DEP to be effective ACTION Link your code with /NXCOMPAT Confirm DEP and ASLR with Process Explorer Detect Heap Corruption REQUIREMENT C & C++ only Windows Vista and later heap manager detect heap corruption, but Windows will not shut your application down by default ACTION Add the following to your main() or WinMain() function (void)HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0); No Writeable PE Segments REQUIREMENT Somewhat esoteric IPC method PE segments are not ACL-able ACTION Don’t use PE segments These are all bad: /section:<name>, RWS #pragma comment(linker, ―/section:<name>, rws‖) #pragma section(<name>, read, write, shared) Do Not Use Banned APIs REQUIREMENT Some C runtime functions are prone to error So don’t use them, use safer versions ACTION Compile with banned.h or strsafe.h Triage C4996 warnings Replace insecure functions with safer C runtime functions or strsafe functions strcpy [strcpy_s or String CchCopy] Add the following to auto-migrate functions to safe functions #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES (1) Encode Long-lived Pointers RECOMMENDATION Long-lived pointers, for example globally scoped, are targets for attack They need protecting ACTION Find all long-lived pointers and protect them with EncodePointer, etc. // g_pFoo is a global point that points to foo void g_pFoo = EncodePointer(&foo); ... // Decode the pointer when you need to use it void *pFoo = DecodePointer(g_pFoo); Use FxCop on Managed Code REQUIREMENT FxCop can help find common security vulnerabilities in C# and VB.NET code Web code or standalone code ACTION Download FxCop (or use Code Analysis in VS) Run it at least once a day Triage all Security rules Aim to have zero suppressions and zero warnings Use /analyze for Unmanaged Code REQUIREMENT The PREfast engine can find many common and easy-to-fix security vulnerabilities at compile time ACTION Compile with /analyze at least once a day Don’t use it on your main builds, it doubles compile times Triage: 6029 6053 6057 6059 6063 6067 6200 6201 6202 6203 6204 6248 6259 6260 6268 6276 /analyze is very low noise Help /analyze – Use SAL RECOMMENDATION Adding SAL can help /analyze find more security bugs SAL adds valuable interface contract data, e.g., _In_z_bytecount_(n) Buffer will be NULL-terminated ‘In’ buffer, code will read the buffer Buffer byte count is ‘n’ Use /W4 RECOMMENDATION C and C++ only There is a subset of high-noise warnings that are now potentially real security vulnerabilities ACTION Compile C and C++ code with /W4 or the less noisy: MSC_WARNING_LEVEL=/W3 /WX /we4242 /we4245 /we4254 /we4289 /we4295 /we4296 /we4701 Hand triage the results Native Code XML Parsers REQUIREMENT Parsing XML safely is hard There have been many industry-wide security vulnerabilities parsing malicious XML payloads XML is everywhere! C++ just makes matters worse! ACTION Use XmlLite Use MSXML 6 SP1 Use MSXML3 SP9 only if there is a strong business justification XSS Prevention REQUIREMENT XSS is the #1 security vulnerability today Yes, it’s bigger than BOs! ACTION Check all incoming data Constrain with TryParse, or RegEx Encode with HTML Encoding Use AntiXSS Use ValidateRequest‖(defense in depth) Use CAT.NET XSS Prevention (Safe Tags) IMPORTANT Only safe if you strip or disallow attributes <b> <em> <blockquote> <i> <br> <li> <div> <ol> <p> <strong> <u> <ul> bool IsSafeTag(string tag) { bool safe = false; string safeTagsRE = @"^<\/?[b|blockquote|br|div|em|i|li|ol|p|strong|u|ul]+>$"; if (Regex.Match(tag, safeTagsRE,RegexOptions.IgnoreCase).Success) safe = true; return safe; } Use ViewStateUserkey REQUIREMENT Helps mitigate Cross-Site Request Forgery (CSRF) vulnerabilities Defense in depth ACTION Add this to your Web applications protected void Page_Init(object sender, EventArgs e) { this.ViewStateUserKey = Session.SessionID; } Do Not Use JavaScript eval() or Equivalents RECOMMENDATION Evaluates and executes arbitrary string data What if the data is untrusted? ACTION Triage the following in your JavaScript code eval setTimeout setInterval When using JSON, use fromJSON Safe Redirect RECOMMENDATION Redirecting to an arbitrary Web location specified in an HTTP request is dangerous Opens users of your site to phishing attacks ACTION Only redirect to a known set of safe URLs Response.Redirect(Request.QueryString(uri)) Response.Redirect("/error.aspx") SQL Execute Only Permission REQUIREMENT Helps mitigate SQL Injection vulns ACTION Run your app as Network Service (DOMAIN\$machinename) Join that account to a domain group (DOMAIN\webapps) Grant that group execute permission to stored procs, etc. Use SQL Parameterized Queries REQUIREMENT SQL injections are hard to pull off with parameterized queries …and easy to pull off with string concatenation ACTION string query= "select * from status where id = " + id; SqlDataAdapter cmd = new SqlDataAdapter("exec sp_getshipstatus(@id)", conn); SqlParameter parm = cmd.SelectCommand.Parameters.Add("@id",id); Use SQL Stored Procedures REQUIREMENT A good way to hide back-end application logic in the event your server is breached It also allows you to easily support execute-only database objects It’s defense in depth ACTION Use sprocs for all your back-end queries Don’t add EXEC (etc) to your sprocs Do Not Depend on NTLM RECOMMENDATION NTLM provides only client authentication All current versions of Windows support Kerberos ACTION Grep for the word “NTLM” in your code Use the Negotiate SSP rather than NTLM SSP No “Swallow All” Exceptions RECOMMENDATION Exceptions that handle all possible exceptions can mask serious bugs They also can make it easier to defeat ASLR ACTION Handle only the exceptions you can REALLY handle All bad: SEH: __except(EXCEPTION_EXECUTE_HANDLER) C++: catch(…) RPC: RpcExcept(1) Managed Code: catch (Exception) Safe Error Messages RECOMMENDATION You want to make it easy for users and admins to know why something failed But, you don’t want to tell attackers too much ACTION Review all error message text, make sure they are: Clear to users Do not disclose too much information Especially for errors transmitted across the network Fuzz Testing REQUIREMENT Many applications fail when presented with incorrectly or malformed data A DoS may really be a code execution vulnerability ACTION Fuzz test Applications that read untrusted data with a minimum of 100,000 malformed inputs File parsers are a great candidate ActiveX controls marked safe for scripting or safe for initialization Networking endpoints Test with Application Verifier REQUIREMENT Applies to native code only A runtime tool that can detect many runtime security vulnerabilities Requires good code coverage to be effective ACTION Run your application under application verifier using the following rules: Heaps, handles, memory Device Driver Issues REQUIREMENT Kernel-mode crashes lead to BSOD ACTION Run Driver Verifier with at least the following: Security Checks Miscellaneous Checks Resources www.microsoft.com/teched www.microsoft.com/learning Sessions On-Demand & Community Microsoft Certification & Training Resources http://microsoft.com/technet http://microsoft.com/msdn Resources for IT Professionals Resources for Developers www.microsoft.com/learning Microsoft Certification and Training Resources Track Resources Visit the DPR TLC for a chance to win a copy of Visual Studio Team Suite. Daily drawing occurs every day in the TLC at 4:15pm. Stop by for a raffle ticket http://www.microsoft.com/visualstudio http://www.microsoft.com/visualstudio/enus/products/teamsystem/default.mspx Please visit us in the TLC blue area Complete an evaluation on CommNet and enter to win! © 2009 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.