secure coding practices
DESCRIPTION
Blackboard Developers Office Hours - Secure Coding Practices - March 13, 2013TRANSCRIPT
Secure Coding Practices
Developer Office Hours
Scott HurreyDeveloper Relations EngineerBlackboard [email protected] x2620
Developer Office Hours 2
Statements regarding our product development initiatives, including new products and future product upgrades, updates or enhancements represent our current intentions, but may be modified, delayed or abandoned without prior notice and there is no assurance that such offering, upgrades, updates or functionality will become available unless and until they have been made generally available to our customers.
Developer Office Hours 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 4Reference: http://www.ruggedsoftware.org/
Developer Office Hours 5
The Rugged Software Manifesto
Highlighting 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 6
Secure Starter Building BlockFeatures & Methodology
Highlights Common Security Pitfalls
Shows Flaws Creating Vulnerabilities
Good Code / Bad Code Examples
How to Use the Security Framework
Good Code
Bad Code
Developer Office Hours 7
Secure Starter Building BlockHow To Access
Google 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 file Install ONLY on an isolated, non-production instance
DANGER! This is experimental code containing purposefully
designed-in vulnerabilities for teaching and learning purposes
Developer Office Hours 8
Secure Starter Building BlockRelease 1.0.0 – Three Tutorials
Three Common Security Pitfalls:• Handling User Input• Verifying Authenticity of Requests• Restricting Access to Pages
Note: These are NOT vulnerabilities in Blackboard Learn Core, BUT
an insecure Building Block would expose your Blackboard Learn
instance to such issues
Developer Office Hours 9
Secure Starter Building BlockWhere Did It Install To?
Developer Office Hours 10
Secure Starter Building BlockAvailable Tutorials
Developer Office Hours 11
DefinitionsRisk = Vulnerability x
Threat x Asset Term Definition
Secure Coding Practices
Input Validation, Escaping, Access Control, etc.
Vulnerability Software weakness that allows an attack to be successful
Threat Source and means of a particular type of attack
Asset Information or system of value
Risk 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 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 Myth 10. Error Handling
Developer Office Hours 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 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 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 16
Restricting Access to PagesBad Code
Action Class No call to check entitlements public ActionForward saveMissingAuthorizationCheck(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
// immediately perform privileged actions…. } JSP No call to restrict access to the page (entitlement attribute) <bbNG:genericPage ctxId="ctx">
Developer Office Hours 17
Restricting Access to PagesGood Code
Action Class Call to check entitlements in action class public ActionForward saveMissingAuthorizationCheck(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
SecurityUtil.checkEntitlement(StarterUtil.SYSTEM_ADMIN_ENTITLEMENT);
// now perform privileged actions….
} JSP Call to restrict access to the page (entitlement attribute) <bbNG:genericPage ctxId="ctx" entitlement="system.admin.VIEW">
Developer Office Hours 18
Verifying Request AuthenticityBad Code
Action Class Extended LegacySecureDispatchAction public class AuthenticityInsecureAction extends
LegacySecureDispatchAction {
// No explicit call to // checkXSRFSecurity(actionForm, request); JSP Nonce not required to be passed in (isSecure, nonceId) <bbNG:form id="exampleCourseUserForm" action="${submitUrl}“
method="POST">
Developer Office Hours 19
Verifying Request AuthenticityGood Code – Pre-9.1 SP10
Action Class Keep LegacySecureDispatchAction public class AuthenticitySecureAction extends LegacySecureDispatchAction {
// Make explicit call to checkXSRFSecurity(actionForm, request); JSP Require nonce to be passed in (isSecure=true, nonceId=package name to ActionForm) <bbNG:form id="exampleCourseUserForm" action="${submitUrl}“
method="POST" isSecure="true" nonceId="blackboard.plugin.starter.struts.AuthenticityForm" >
Developer Office Hours 20
Verifying Request AuthenticityGood Code – Post-9.1 SP10
Action Class Switch to SecureDispatchAction, checks nonce by default public class AuthenticitySecureAction extends SecureDispatchAction {
// No longer need to explicitly call nonce check //checkXSRFSecurity(actionForm, request);
JSP Leave as-is, nonce not required to be passed in (isSecure,
nonceId) <bbNG:form id="exampleCourseUserForm" action="${submitUrl}“
method="POST">
Developer Office Hours 21
Design and Code Securely
Let’s look at a small subset of Secure Design Principles and Secure Coding Practices
Security Design Principles1.
2.
3.
4.
5.
Defense in Depth
Compartmentalization
Security != Obscurity
Fail Secure
Least Privilege
Secure Coding Practices
1.
2.
3.
Input Validation
Escaping
HTML Sanitization
Developer Office Hours 22
Defense-In-DepthExample: 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.” 1
1 http://www.tsa.gov/what_we_do/layers/index.shtm
Developer Office Hours 23
Defense-In-DepthExample: 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 24
Defense-In-DepthYour 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 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 26
Fail Securely
Transaction initialization, shutdown and aborts should always keep the application in a secure state
Example: Access Control Check
If CheckAccessDenied() Display Error Message () DenyAccess()
ElsePerform Privileged Action ()
Endif
Developer Office Hours 27
Handling User InputWhen to use Input Validation, Escaping and Safe HTML
Required Action Input Validation Escaping Safe HTML
Rendered as text Yes Yes No
Input to be added to JavaScipt
Yes Yes, but be careful No
Input to be added as a parameter to a URL
Yes Yes No
Rendered as HTML No No Yes
Developer Office Hours 28
Input Validation
DO: • 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 29
Input ValidationValidation Strategies
Validation Strategy (Best to Worst) Definition Often Used For
Exact match Finite list of known values, such as enumerated types or structured data
Enumerated types or structured data
Accept known good No known list of finite values, but specific patterns
UUIDS, pk ids, strings or numbers
Sanitize with whitelist
Remove/encode/replace characters not on approved list(similar to Safe HTML)
Freeform text areas
Reject/encode known bad
Blacklist rejection/HTML escaping of known malicious chars. “Arms race”
Freeform text areas
No validation No validation N/A
Developer Office Hours 30
Output Encoding and Escaping
DO: • 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 URIs
Context Trusted Users Untrusted Users
Non-VTBE, like Query Strings
Escape Escape
VTBE Unrestricted HTML Safe HTML
Developer Office Hours 31
Output Encoding and EscapingDO NOT: • Restrict escaping to roles unless related to
VTBE– NO! EscapeUntrusted(), escapeThenFilter()
DO:• Escape server-side using approved methods
Context Java JSP
HTML XSSUtil.escape(evil) ${bbNG:HtmlEscape(evil)}
JavaScript JsResource.encode(evil) ${bbFn:jsEncode(evil)}
URL EncodeUtility.urlEncode(evil) UrlUtil.addParameterToUrl(url,key,evil,true)
${bbFn:urlEncode(evil)}
Developer Office Hours 32
Output Encoding and EscapingExample
Missing escaping, remember XSSUtil.filter is not relevant
Action Class request.setAttribute(“username”,
request.getParameter(“username”));
JSP<h3>User ${username} located</h3>Action Class request.setAttribute(“username”,
XSSUtil.escape(request.getParameter(“username”))); JSP<h3>User ${bbNG:HtmlEscape(username)} located</h3>
Developer Office Hours 33
Output Encoding and EscapingMore 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 34
Safe HTML
DO:• Use when rendering input to be
executed as HTML– e.g. VTBE-related fields
DO NOT:• Use directly from untrusted input• Use as a replacement for appropriate
input validation or output escaping
Developer Office Hours 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/plugins/bb-xss-filter/webapp/WEB-INF/classes/blackboard/xss/request/bb-xss-global-filter-exceptions.txt
Developer Office Hours 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 37
Questions, Comments, Concerns
• Feel free to ask.• Email me at [email protected]• Report Learn vulnerabilities to
[email protected]• Report vulnerabilities in Partner Building
Blocks to [email protected]