Secure coding practices

4,759 views

Published on

Blackboard Developers Office Hours - Secure Coding Practices - March 13, 2013

Published in: Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,759
On SlideShare
0
From Embeds
0
Number of Embeds
222
Actions
Shares
0
Downloads
125
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Secure coding practices

  1. 1. Developer Office Hours Secure Coding PracticesScott HurreyDeveloper Relations EngineerBlackboard Partnershipsscott.hurrey@blackboard.com202.463.4860 x2620
  2. 2. Statements regarding our product developmentinitiatives, including new products and future productupgrades, updates or enhancements represent ourcurrent intentions, but may be modified, delayed orabandoned without prior notice and there is noassurance that such offering, upgrades, updates orfunctionality will become available unless and untilthey have been made generally available to ourcustomers. Developer Office Hours 2
  3. 3. Agenda• What is Ruggedness?• Delivering a Rugged Building Block• Secure Design Principles• Secure Coding Guidelines with the Private Security APIs• Verification Techniques Developer Office Hours 3
  4. 4. Reference: http://www.ruggedsoftware.org/ Developer Office Hours 4
  5. 5. The Rugged Software ManifestoHighlighting a few concepts from the manifesto• Recognize that your Building Block becomes part mission-critical platform• Recognize that your code will be used (or manipulated) in ways you cannot anticipate• It may be attacked by talented and persistent adversaries• So….refuse to be the source of a vulnerability or weakness Developer Office Hours 5
  6. 6. Secure Starter Building BlockFeatures & Methodology Highlights Common Security Pitfalls Shows Flaws Creating VulnerabilitiesGood Code Good Code / Bad Code Examples Bad Code How to Use the Security Framework Developer Office Hours 6
  7. 7. Secure Starter Building BlockHow To Access DANGER! This is experimental code containing purposefully designed-in vulnerabilities for teaching and learning purposesGoogle Code site - bb-secure-starterShortcut: http://goo.gl/3YqDq(points to…trust me…)http://code.google.com/p/bb-secure-starter/Download the B2 .war fileInstall ONLY on an isolated, non-production instance Developer Office Hours 7
  8. 8. Secure Starter Building BlockRelease 1.0.0 – Three TutorialsNote: These are NOT vulnerabilities in Blackboard Learn Core, BUT aninsecure Building Block would expose your Blackboard Learninstance to such issuesThree Common Security Pitfalls:• Handling User Input• Verifying Authenticity of Requests• Restricting Access to Pages Developer Office Hours 8
  9. 9. Secure Starter Building BlockWhere Did It Install To? Developer Office Hours 9
  10. 10. Secure Starter Building BlockAvailable Tutorials Developer Office Hours 10
  11. 11. Definitions Risk = Vulnerability x Threat x AssetTerm DefinitionSecure Coding Practices Input Validation, Escaping, Access Control, etc.Vulnerability Software weakness that allows an attack to be successfulThreat Source and means of a particular type of attackAsset Information or system of valueRisk Potential for loss, damage, or destruction of an asset as a result of a threat exploiting a vulnerability.Ways to Reduce Risk (severity of a potential issue):• Reduce the Vulnerability through a Secure Coding Practice• Reduce the Threat, perhaps through a Security Design Principle• Reduce the Asset, perhaps through evaluating what information is collected/modified/displayed Developer Office Hours 11
  12. 12. LegendSecure Design Principles 1. Defense in Depth 6. Cryptology 2. Secure Defaults 7. Fail Secure 3. Least Privilege 8. Robustness &Re-use 4. Compartmentalization 9. Expected Ability &Presence 5. Security by Obscurity is a 10. Error Handling Myth Developer Office Hours 12
  13. 13. LegendSecure Coding Practices 1. Input Validation 5. File Handling 2. Escaping 6. Authenticity Validation 3. Safe HTML (Sanitation) 7. Error Handling & Exceptions 4. Arbitrary Redirects 8. Access Control Developer Office Hours 13
  14. 14. Reflecting User InputBad Code<bbNG:step title="Results" instructions=""> <c:if test="${exists == 1}"> <h3>User ${username} located</h3> <bbNG:dataElement label="Given Name" labelFor="givenName"> ${givenName} </bbNG:dataElement> <bbNG:dataElement label="Email" labelFor="email"> ${email} </bbNG:dataElement> </c:if></bbNG:step> Developer Office Hours 14
  15. 15. Reflecting User InputGood Code<bbNG:step title="Results" instructions=""> <c:if test="${exists == 1}"> <h3>User ${bbNG:HtmlEscape(username)} located</h3> <bbNG:dataElement label="Given Name" labelFor="givenName"> ${givenName} </bbNG:dataElement> <bbNG:dataElement label="Email" labelFor="email"> ${email} </bbNG:dataElement> </c:if></bbNG:step> Developer Office Hours 15
  16. 16. Restricting Access to PagesBad CodeAction ClassNo call to check entitlementspublic ActionForward saveMissingAuthorizationCheck(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { // immediately perform privileged actions….}JSPNo call to restrict access to the page (entitlement attribute)<bbNG:genericPage ctxId="ctx"> Developer Office Hours 16
  17. 17. Restricting Access to PagesGood CodeAction ClassCall to check entitlements in action classpublic ActionForward saveMissingAuthorizationCheck(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { SecurityUtil.checkEntitlement (StarterUtil.SYSTEM_ADMIN_ENTITLEMENT); // now perform privileged actions….}JSPCall to restrict access to the page (entitlement attribute)<bbNG:genericPage ctxId="ctx" entitlement="system.admin.VIEW"> Developer Office Hours 17
  18. 18. Verifying Request AuthenticityBad CodeAction ClassExtended LegacySecureDispatchActionpublic class AuthenticityInsecureAction extends LegacySecureDispatchAction { // No explicit call to // checkXSRFSecurity(actionForm, request);JSPNonce not required to be passed in (isSecure, nonceId)<bbNG:form id="exampleCourseUserForm" action="${submitUrl}“ method="POST"> Developer Office Hours 18
  19. 19. Verifying Request AuthenticityGood Code – Pre-9.1 SP10Action ClassKeep LegacySecureDispatchActionpublic class AuthenticitySecureAction extends LegacySecureDispatchAction { // Make explicit call to checkXSRFSecurity(actionForm, request);JSPRequire nonce to be passed in (isSecure=true, nonceId=packagename to ActionForm)<bbNG:form id="exampleCourseUserForm" action="${submitUrl}“ method="POST" isSecure="true" nonceId="blackboard.plugin.starter.struts.AuthenticityForm" > Developer Office Hours 19
  20. 20. Verifying Request AuthenticityGood Code – Post-9.1 SP10Action ClassSwitch to SecureDispatchAction, checks nonce by defaultpublic class AuthenticitySecureAction extends SecureDispatchAction{ // No longer need to explicitly call nonce check //checkXSRFSecurity(actionForm, request);JSPLeave as-is, nonce not required to be passed in (isSecure, nonceId)<bbNG:form id="exampleCourseUserForm" action="${submitUrl}“ method="POST"> Developer Office Hours 20
  21. 21. Design and Code SecurelyLet’s look at a small subset of SecureDesign Principles and Secure CodingPractices Security Design Principles Secure Coding Practices 1. Defense in Depth 1. Input Validation 2. Compartmentalization 2. Escaping 3. Security != Obscurity 3. HTML Sanitization 4. Fail Secure 5. Least Privilege Developer Office Hours 21
  22. 22. Defense-In-Depth Example: TSA“Each one of these layersalone is capable of stopping aterrorist attack. Incombination their securityvalue is multiplied, creating amuch stronger, formidablesystem. A terrorist who has toovercome multiple securitylayers in order to carry out anattack is more likely to be pre-empted, deterred, or to failduring the attempt.” 11 http://www.tsa.gov/what_we_do/layers/index.shtm Developer Office Hours 22
  23. 23. Defense-In-Depth Example: Blackboard Learn  Layering security defenses in an application can reduce the chance of a successful attack• Existing and upcoming countermeasures for Blackboard Learn• Prevents single point of failure• Increases robustness and future use Developer Office Hours 23
  24. 24. Defense-In-Depth Your Building Block  Follow All Secure Design Principles  Follow All Secure Coding Guidelines• Failure to follow these suggestions can increase the risk of system and data compromise• Your Building Block can affect various layers of System Architecture beyond Blackboard Learn and circumvent existing Security Controls Developer Office Hours 24
  25. 25. Secure Default Settings  Deploy B2 with minimum permissions necessary• If a permission is not required, do not include it in your Building Block• For example, do not include blanket filesystem access permissions unless absolutely necessary. Developer Office Hours 25
  26. 26. Fail Securely  Transaction initialization, shutdown and aborts should always keep the application in a secure stateExample: Access Control Check If CheckAccessDenied() Display Error Message () DenyAccess() Else Perform Privileged Action () Endif Developer Office Hours 26
  27. 27. Handling User InputWhen to use Input Validation, Escaping and Safe HTMLRequired Action Input Validation Escaping Safe HTMLRendered as text Yes Yes NoInput to be added Yes Yes, but be careful Noto JavaSciptInput to be added Yes Yes Noas a parameter to aURLRendered as HTML No No Yes Developer Office Hours 27
  28. 28. Input ValidationDO:• Validate Input – Applicable to ALL parameters, URLs and HTTP Header content – Perform at a “trust boundary” – e.g. at every tier – Remember DB is the last line of defense – Use a recommended Validation Strategy• Reject Violations Developer Office Hours 28
  29. 29. Input ValidationValidation StrategiesValidation Strategy(Best to Worst) Definition Often Used ForExact match Finite list of known values, such Enumerated types or as enumerated types or structured data structured dataAccept known good No known list of finite values, UUIDS, pk ids, but specific patterns strings or numbersSanitize with whitelist Remove/encode/replace Freeform text areas characters not on approved list (similar to Safe HTML)Reject/encode known Blacklist rejection/HTML Freeform text areasbad escaping of known malicious chars. “Arms race”No validation No validation N/A Developer Office Hours 29
  30. 30. Output Encoding and EscapingDO:• Escape ALL untrusted data in proper context – Applicable to ALL input, such as URL Parameters, form fields, headers or cookies – Often missed when output to HTML tags and attributes, taglibs, CSS, JavaScript data values and URIsContext Trusted Users Untrusted UsersNon-VTBE, like Query Escape EscapeStringsVTBE Unrestricted HTML Safe HTML Developer Office Hours 30
  31. 31. Output Encoding and EscapingDO NOT:• Restrict escaping to roles unless related to VTBE – NO! EscapeUntrusted(), escapeThenFilter()DO:• Escape server-side using approved methodsContext Java JSPHTML XSSUtil.escape(evil) ${bbNG:HtmlEscape(evil)}JavaScript JsResource.encode(evil) ${bbFn:jsEncode(evil)}URL EncodeUtility.urlEncode(evil) ${bbFn:urlEncode(evil)} UrlUtil.addParameterToUrl(url,key,evil, true) Developer Office Hours 31
  32. 32. Output Encoding and EscapingExampleMissing escaping, remember XSSUtil.filter is not relevantAction Classrequest.setAttribute(“username”, request.getParameter(“username”));JSP<h3>User ${username} located</h3>Action Classrequest.setAttribute(“username”, XSSUtil.escape(request.getParameter(“username”))); JSP<h3>User ${bbNG:HtmlEscape(username)} located</h3> Developer Office Hours 32
  33. 33. Output Encoding and Escaping More Examples// Escape for HTML Tags<b>${bbNG:HtmlEscape(evil)}</b>// Escape for HTML Attributes<input type="text" name="foo" value="${bbNG:HtmlEscape(evil)}">// Escape for JavaScript<script type=text/javascript>function foo(){ return confirm("${bbFn:jsEncode(evil)}")}</script>// Escape for URLsurl = UrlUtil.addParameterToUrl( url, “bar", evil, true );url = "/webapps/foo?bar="+EncodeUtility.urlEncode(evil);<c:set var=“fooURL" value="/webapps/foo/bar.jsp?foo=${bbFn:urlEncode(evil)}"/> Developer Office Hours 33
  34. 34. Safe HTMLDO:• Use when rendering input to be executed as HTML – e.g. VTBE-related fieldsDO NOT:• Use directly from untrusted input• Use as a replacement for appropriate input validation or output escaping Developer Office Hours 34
  35. 35. Safe HTMLBlacklisting• List of URL prefixes for which the global XSS filtering should NOT be performed.• Add entries here to work around issues that arise in Building Blocks or other areas that are sensitive to the changing of request parameter values.• Configuration file located at /usr/local/blackboard/content/vi/bb_bb60/plug ins/bb-xss-filter/webapp/WEB- INF/classes/blackboard/xss/request/bb-xss- global-filter-exceptions.txt Developer Office Hours 35
  36. 36. Safe HTMLWhitelisting• This filter controls allowable HTML tags in the Content Editor (VTBE).• You can modify the default policy through the UI• Policy can be downloaded from System Admin->Safe HTML Filters->Safe HTML Filter for Content Editor, edited and the uploaded via the same screen• This only affects untrusted users, like students Developer Office Hours 36
  37. 37. Questions, Comments, Concerns• Feel free to ask.• Email me at scott.hurrey@blackboard.com• Report Learn vulnerabilities to LearnSecurity@blackboard.com• Report vulnerabilities in Partner Building Blocks to BbPartnerTeam@blackboard.com Developer Office Hours 37

×