620 likes | 839 Views
Secure SharePoint Development. Eli Robillard SharePoint Server MVP Canada, EDT (GMT -5:00) April 16 th /17 th , 2014. #SP24S045. In this hour:. #SP24S045. Security Fundamentals Microsoft’s Secure Development Lifecycle and ISO 27034 Principles, Threats & Countermeasures
E N D
Secure SharePoint Development Eli Robillard SharePoint Server MVP Canada, EDT (GMT -5:00) April 16th /17th, 2014 #SP24S045
In this hour: #SP24S045 Security Fundamentals Microsoft’s Secure Development Lifecycle and ISO 27034 Principles, Threats & Countermeasures Threats specific to SharePoint How to be secure by default: out-of-box threats and security bulletins, service accounts and application context Secure SharePoint practices Code snippets, recommended practices and pitfalls for on-premises solutions The App Model and Remote-hosted Apps Join the conversation! #SP24S045@erobillard
Eli Robillard #SP24S045 Eli Robillard MNP LLP Senior Manager, SharePoint Consulting Eli is a ten-time Microsoft MVP (2x ASP.NET, 8x SharePoint Server) and Senior Manager of MNP’s SharePoint Consulting Practice. As a thought leader and community builder, Eli co-founded the ASPInsiders, launched the Toronto SharePoint User Group in 2005, launched the first free Saturday event in 2007, co-authored Professional SharePoint 2007 Development and served as technical editor of Professional Professional SharePoint 2010 Development (Wrox Press). For over 65 years, MNP LLP has forged strong relationships with businesses across Canada through its consulting, advisory, and accounting practices. E-mail Eli.Robillard@MNP.ca Twitter@erobillard Blogweblogs.asp.net/erobillard
Why bother writing secure code? #SP24S045 Security at development time is rapidly becoming “conventional wisdom” Forrester Research– “…those practicing SDL specifically reported visibly better ROI results than the overall population.” Aberdeen Group – “…realized a very strong 4.0-times return on their annual investments” “…higher than that of both the find and fix and defend and defer approaches.” Ponemon Institute – “…a decrease in revenue that results from both the loss of customer trust and loyalty and the inability to deliver services and products.” Roadmap to Secure Energy Delivery Systems – “…Vendors should employ best product development practices, such as the security development lifecycle (SDL) created by Microsoft in 2002.”
Security Fundamentals ISO 27034 and Microsoft’s Secure Development Lifecycle
Microsoft’s SDL Journey Secure Windows Initiative Prior to 2001 TwC Memo 2002-2003 Secure Windows Initiative Prior to 2001 TwC Memo 2002-2003 SDL Implementation 2005-2007 SDL Launched 2004 SDL and the Ecosystem 2008-2012 Standards-based Secure Development Current We knew we had a problem Training andSecurity Pushes Theory vs. Practice Required for almost all products Publication of SDL and free tools A core part of supply chain discussion International standard on secure development Adaptations SDL for Agile Simplified SDL We neededan approach Integrated into all phases of product lifecycle Automation Heavily reliant on small team of experts Ecosystem collaboration Mitigations Ecosystem Adoption Small team, ad hoc process Needed a consistent, scalable, prescriptive process A framework for continuous improvement
SDL Results Database systems vulnerability trends Data sourced from National Vulnerability Database Improved mitigations http://nvd.nist.gov/ Lower exploitability Lower infection rates
What makes a good standard? #SP24S045
The Simplified SDL implements 27034-1 • Simplified Implementation of SDL Guidance • 17 pages of process guidance and Application Security Controls Response Verification Release Requirements Design Training 17. Execute Incident Response Plan 14. Create an Incident Response Plan 15. Certify Release and Archive 16. Certify Release and Archive 2. Establish Security and Privacy Requirements 3. Create Quality Gates/Bug Bars 4. Perform Security and Privacy Risk Assessments 1. Core Security Training 5. Establish Design Requirements 6. Perform Attack Surface Analysis/Reduction 7. Use Threat Modeling 8. Use Approved Tools 9. Deprecate Unsafe Functions 10. Perform Static Analysis 11. Perform Dynamic Analysis 12. Perform Fuzz Testing 13. Conduct Attack Surface Review Implementation • 27034-1 • 45 pages of process and framework guidance • 16 page case study in Annex A aligning Simplified SDL and ISO/IEC 27034
Organisational (ONF) Components Application (ANF) Components
Spectrum of Maturity Where should you start? Assess the current state of your software security program. Reactive and Ad Hoc Continuously Improving Apply some Simplified SDL practices Systematic application of SDL process Standardize with policy and tools Validate with 27034-1
Key aspects of ONF addressed by SDL Simplified Guidance Context- Specific Guidance • Business Context • SDL Chronicles • Secure Software Trends in Healthcare • Regulatory Context • SDL and PCI DSS/PA-DSS • SDL and HIPAA • BITS Framework Business Context Regulatory Context Technical Context Specifications Roles Processes ASC Library
Putting it all together A conforming 27034 process = + Simplified SDL Guidance Implementation Org Organization Normative Framework (ONF) • Process Guidance • Roles • Technical Context • 17 Practices (ASCs) • Lifecycle Aligned to 27034 • Informed by context, • Regulatory/Business/Tech • Instantiated through • Approved policies • Internal communications • Results in • Centralized ASC store • Compliance workflow + tools Application Security Lifecycle Reference Model Management Process App Application Normative Framework (ANF) • Compliance Tracking Process Requirements • Practices that map to ASMP Application Security Management Process
Security Fundamentals Principles, Threats and Counter-measures #SP24S045
Application Threats and Countermeasures #SP24S045
Principles of Security #SP24S045
Keeping SharePoint Secure Be secure by default
Well-known Threats to SharePoint #SP24S045
Watch for Security Updates #SP24S045 http://technet.microsoft.com/en-us/security/bulletin
Walk Walkthrough ofa Security Bulletin http://technet.microsoft.com/en-us/security/bulletin/ms13-024
Walkthrough: MS 10-070 #SP24S045 1: The advisory was issued for ASP.NET http://technet.microsoft.com/en-us/security/advisory/2416728 2: Scott Guthrie posted a workaround http://weblogs.asp.net/scottgu/archive/2010/09/18/important-asp-net-security-vulnerability.aspx 3: The SP product team notified SharePoint 2010 users http://sharepoint.microsoft.com/blog/Pages/BlogPost.aspx?PageType=4&ListId={72C1C85B-1D2D-4A4A-90DE-CA74A7808184}&pID=941 4: I posted a workaround for SharePoint 2010 and 2007 http://weblogs.asp.net/erobillard/archive/2010/09/21/how-to-protect-sharepoint-servers-from-the-asp-net-vulnerability.aspx 5: Microsoft’s SharePoint guidance was updated to include 2007
Lessons of MS 10-070 #SP24S045 Focus your effort on protecting secrets. Assume the attacker will be able to read files in the SharePoint hive and IIS web root. Encrypt your secrets. When an exploit is published, assume you are affected and protect your information first. Then figure out how you are affected and seek remedies. Good practices pay their own way.
User permissions #SP24S045 • Lock down any unnecessary URLs and pages • Candidates: Application pages in a crawl-only site, userdisp.aspx in a public site • Request blocking with URL Rewrite module • Request routing rules • Lock down unnecessary user permissions • Remove the View Application Pages permission from permission level • Enable the ViewFormPagesLockDownfeature
Service Accounts #SP24S045 Use service accounts to: • Contain attacks • Provide defence-in-depth Fewest Required Accounts: • SQL Service, Setup User, SP Farm Suggested Accounts for Least-Privilege:
Service Account Context #SP24S045 Know the identity used in every context
What to choose for external data? #SP24S045 • Impersonation (PassThrough) • Application Pool ID (RevertToSelf) • Stored Credentials • Hard-coded: Just don’t do it. • Web.config: A pain to encrypt & update. • Secure Store Service: The best choice. • Managed accounts: Great (where applicable).
Habits of Secure SharePoint Developers • Write for SharePoint as a presentation tier. • Keep all non-SharePoint data and code outside SharePoint. • No custom CAS policies. If it’s not Minimal, it’s Full Trust. • Schedule regular peer-to-peer code reviews • Do a formal code security review before release • Use static code analysis tools • SPCop, FxCop, HP Fortify • Run the Initialize-SPResourceSecuritycmdlet
Calls to Action Aim to be “secure by default” If it isn’t a requirement, lock it down. Watch for Security Bulletins SharePoint plus ASP.NET, IIS, Windows Server and other products in use. Think like a service account – understand context What do you really need to get the job done? Adopt secure development habits There are tools and techniques for every stage, knowledge is power.
Keeping SharePoint Secure Tips and Tricks for Writing Secure SharePoint Code
These tips will never be complete… It takes a community to raise a secure SharePoint solution, your feedback is always welcome.
Secure Practices: Dispose of SPWeb and SPSite Bad SPWeb web = site.OpenWeb();// do stuff with web Better SPWeb web = site.OpenWeb();// do stuff with webmyWeb.Dispose(); Best using (SPWeb web = site.OpenWeb()){ // do stuff with web}
Secure Practices: Check Execution Context • Do methods test for execution context before making changes? if (HttpContext.Current == null) { // This isn’t being called in a web application }
Secure Practices: Check user permissions • Are permissions tested before elevating privileges? if (web.DoesUserHavePermissions(SPBasePermissions.ManageLists)) { // Backup list(s) to OneDrive } Reference: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spbasepermissions.aspx
Secure Practices: Validate All Input Data • Do all methods use /// blocks to describe acceptable parameter types, values and ranges? • Do you use the AntiXssLibrary.dll? • Do all methods that emit settings or content provided by users encode output with: AntiXss.HtmlEncode(myString) or AntiXss.URLEncode(myString) ? • Note: AntiXss cannot sanitize all JS injection scenarios. The current version is the last planned for release.
Secure Practices: Validate All Input Data Validate with Type Checking // Is the ItemId parameter an Int32? if(!Int32.TryParse(Request.QueryString["ItemId"],out ItemId)) { // Exit with an invalid parameter error } Validate with Regular Expression // Is the ListId parameter a GUID? RegexStringValidatorval = new RegexStringValidator(@"^\{?[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-[\dA-Fa-f]{4}-[\dA-Fa-f]{4}-[\dA-Fa-f]{12}\}?$"); // If invalid, this will throw a System.ArgumentException val.Validate(Request.QueryString["ListId"]); GuidListId = new Guid(Request.QueryString["ListId"]);
Secure Practices: Application Pages • Does the page inherit from LayoutsPageBase? • Does the page update any SharePoint objects? • If yes, does it process only during IsPostBack? Updating the object model during a GET allows cross-site scripting. • If yes, does the .aspx have a FormDigest control? • Does the page call SPUtility.ValidateFormDigest()before making any updates? • Does the page set AllowUnsafeUpdates? • If yes, make sure the SPSite or SPWeb is not created from HttpContext. Only set AllowUnsafeUpdateswhere you obtain an SPSite or SPWeb reference from an absolute URL. • Reject any code that disables FormDigest – this makes cross-site scripting attacks possible.
Secure Practices: Application Pages Appropriate context to use ValidateFormDigest() vs. AllowUnsafeUpdates if (HttpContext.Current == null) { // parmAbsUrl is an absolute URL in the format "http://server/sites/mySite/" using (SPSite site = new SPSite(parmAbsoluteUrl)) { using (SPWeb web = site.OpenWeb(parmAbsoluteUrl)) {web.AllowUnsafeUpdates = true; // Update SharePoint objects here web.AllowUnsafeUpdates = false; } } } else // HttpContext.Current has a value {SPUtility.ValidateFormDigest(); // Update SharePoint objects here }
Secure Practices: Web Parts • Does the Web Part swallow all exceptions and display the Correlation ID? • It is bad when a page fails because of an errant web part. • How to display Correlation ID: [DllImport("advapi32.dll")] public static extern uintEventActivityIdControl(uintcontrolCode, ref GuidactivityId); public constuint EVENT_ACTIVITY_CTRL_GET_ID = 1; // … // And then use it in code like this: try { // code block goes here } catch { Guid g = Guid.Empty; EventActivityIdControl(EVENT_ACTIVITY_CTRL_GET_ID, ref g); this.Controls.Add(new Label { Text = string.Format("An error occurred with Correlation ID {0}", g) }); }
Secure Practices: Web Part Properties • Do Web Parts validate their properties? • It is most effective to do this in the property settings and not during web part execution (by then the user must re-open the property page). public string NumberArray { // Require format: 1,2,3,4 get{return _numberArray;} set{ string [] arr = value.split(','); foreach (string item in arr) { inti; if(!int.TryParse(item,outi)) throw new WebPartPageUserException("\""+item+"\" is not a valid number"); } _numberArray=value; } }
Secure Practices: Elevated Threads Three scenarios to elevate thread privileges: • Read SharePoint data. • Update SharePoint data. • Make an external call.
Secure Practices: Reading SharePoint Data SPWeb web = SPContext.Current.Web;try{ // Verify this is a postback from a valid Application Page SPUtility.ValidateFormDigest(); // Verify that the user has a valid permission before elevating if (web.DoesUserHavePermissions(SPBasePermissions.ManageWeb)) {SPSecurity.RunWithElevatedPrivileges(delegate() { // Read data using the SharePoint Object Model here }); }}
Secure Practices: Updating SharePoint Data // Update a SharePoint property using (SPSiteelevatedSite = LitwareSecurity.SharePoint.Security.GetElevatedSite(web.Site) { // Update data using SharePoint object model here. } The secret sauce: GetElevatedSite first tries site.SystemAccount.UserToken. If that doesn’t work it falls back to RWEP() to GetSystemToken(). It then returns an elevated SPSite using this token. Get the source: http://www.danlarson.com/elevated-privilege-with-spsite/
Secure Practices: Using thread identity to call outside SharePoint // Call a non-SharePoint resource using (HostingEnvironment.Impersonate()) { // Call an external resource using the credentials of // the Application Pool ID here }
Secure Practices: Elevated Threads Three scenarios to elevate thread privileges: • Read SharePoint data RWEP() is fine to read. • Update SharePoint data GetElevatedSite() creates a safe SPSite to work with. • Make an external call The ASP.NET way to get the job done still works in SharePoint.
Keeping SharePoint Secure The App Model
App Hosting Models SharePoint-hosted Apps • App resources added to SharePoint host • Stored in child site known as App Web • App can have client-side code (HTML4/5, Javascript, • jQuery, Silverlight, Flash, etc.) • App cannot have server-side code Provider-hosted & Auto-hosted Apps • App resources deployed on remote server • Remote site known as Remote Web • App can have client-side code • App can have server-side code (C#, node.js, PHP, • Ruby, Java, etc.)
Granting SharePoint App Permissions Permissions are requested when an App is installed on a SharePoint server. All or nothing
Sample App Manifest <?xml version="1.0" encoding="utf-8" ?><App xmlns=http://schemas.microsoft.com/sharepoint/2012/app/manifestProductID="{4a07f3bd-803d-45f2-a710-b9e944c3396e} " Version="1.0.0.0"SharePointMinVersion="15.0.0.0" Name="MySampleApp"> <Properties> <Title>My Sample App</Title> <StartPage>http://ContosoApps/default.aspx/?SPHostUrl={HostUrl}</StartPage> <SupportedLocales> <SupportedLocaleCultureName="en-US" /> </SupportedLocales> </Properties> <AppPermissionRequests> <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read"/> <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Write"> <Property Name="BaseTemplateId" Value="101"/> </AppPermissionRequest> </AppPermissionRequests> <AppPrincipal> <RemoteWebApplicationClientId="1ee82b34-7c1b-471b-b27e-ff272accd564" /> </AppPrincipal> </App>