secure coding practices

37
Secure Coding Practices Developer Office Hours Scott Hurrey Developer Relations Engineer Blackboard Partnerships s [email protected] om

Upload: shurrey

Post on 23-Jan-2015

2.323 views

Category:

Education


6 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Secure coding practices

Secure Coding Practices

Developer Office Hours

Scott HurreyDeveloper Relations EngineerBlackboard [email protected] x2620

Page 2: Secure coding practices

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.

Page 3: Secure coding practices

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

Page 4: Secure coding practices

Developer Office Hours 4Reference: http://www.ruggedsoftware.org/

Page 5: Secure coding practices

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

Page 6: Secure coding practices

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

Page 7: Secure coding practices

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

Page 8: Secure coding practices

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

Page 9: Secure coding practices

Developer Office Hours 9

Secure Starter Building BlockWhere Did It Install To?

Page 10: Secure coding practices

Developer Office Hours 10

Secure Starter Building BlockAvailable Tutorials

Page 11: Secure coding practices

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

Page 12: Secure coding practices

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

Page 13: Secure coding practices

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

Page 14: Secure coding practices

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>

Page 15: Secure coding practices

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>

Page 16: Secure coding practices

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

Page 17: Secure coding practices

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

Page 18: Secure coding practices

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

Page 19: Secure coding practices

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

Page 20: Secure coding practices

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

Page 21: Secure coding practices

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

Page 22: Secure coding practices

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

Page 23: Secure coding practices

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

Page 24: Secure coding practices

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

Page 25: Secure coding practices

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.

Page 26: Secure coding practices

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

Page 27: Secure coding practices

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

Page 28: Secure coding practices

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

Page 29: Secure coding practices

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

Page 30: Secure coding practices

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

Page 31: Secure coding practices

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)}

Page 32: Secure coding practices

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>

Page 33: Secure coding practices

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)}"/>

Page 34: Secure coding practices

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

Page 35: Secure coding practices

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

Page 36: Secure coding practices

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

Page 37: Secure coding practices

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]