COLDFUSION SUMMIT 2016 SECURITY WORKSHOP

Post on 19-Apr-2022

1 views 0 download

Transcript of COLDFUSION SUMMIT 2016 SECURITY WORKSHOP

C O L D F U S I O N S U M M I T 2 0 1 6

S E C U R I T Y W O R K S H O PP R E S E N T E D B Y P E T E F R E I TA G & D A V I D E P L E R

A B O U T P E T E

• 18+ Years ColdFusion Experience

• Job: Foundeo Inc. (Gold Sponsor at CFSummit)

• FuseGuard, HackMyCF & Consulting

• Teach Onsite / Remote CFML Security Classes

• blog: petefreitag.com

• twitter/github: @pfreitag

A B O U T D AV I D

• 16+ years ColdFusion experience

• Job: AboutWeb - Security Architect

• Several Security Certs: GWAPT, CEH

• Learn CF in a Week - Security

• OWASP Zed Attack Proxy (ZAP) Evangelist

• blog: dcepler.net

• twitter/github: @dcepler

T O D AY ’ S A G E N D A

• Get VM Up & Running

• Core Security Principals

• Learn, Hack, Fix:

• Topics include: SQL Injection, File Issues (Path Traversals, Uploads), XSS, Security Headers, CSRF, Remote Code Execution, Authentication / Authorization, Cookies & Sessions

• Security Analyzer in ColdFusion Builder 2016

• Breaks: 10:30 -11, 12:30-1:30 (Lunch), 3-3:30

A B O U T T H E V M

• Ubuntu Linux OS (don’t worry if you have never used linux!)

• ColdFusion 2016

• ColdFusion Builder 2016

• MySQL, Apache

• Username / password: cf / cf

O P E N C F B U I L D E R

• Login (password is: cf)

1. Double Click Files

2. Double Click ColdFusionBuilder2016

3. Double Click CFBuilderit will take a few seconds to open

S TA R T C O L D F U S I O N

• In CFBuilder click on Servers tab

• Click on CF2016

• Click Green Triangle to start

O P E N F I R E F O X

• Double click Firefox Icon

• Bank of Insecurity Site should load.

• Use top nav to browse around the site.

C O R E S E C U R I T Y P R I N C I PA L SP E T E P R E S E N T S

P R I N C I PA L O F L E A S T P R I V I L E G E

• Grant only the minimum permissions to each user to perform required task.

(cc) chriskantos on flickr

D E F E N S E I N D E P T H

• Multiple layers of redundant security.

• If one protection was inadequate another may prevent attack.

• Examples?

(cc) stawarz on flickr

VA L I D AT I O N

• Strong server side validation can provide a tremendous boost to security.

• IsValid, cfparam, int, val etc.

• Regex

• Custom Validation

(cc) sillyeaglebooks on flickr

B L A C K L I S T V S W H I T E L I S T

E X A M P L E : D O N ’ T A L L O W U P L O A D I N G O F C F M , C F C F I L E S

E X A M P L E : O N LY A L L O W U P L O A D I N G O F J P G , P N G F I L E S

S Q L I N J E C T I O ND A V I D P R E S E N T S

S Q L I N J E C T I O N

TweetPic from someone that did not responsibly disclose issue to site owner that has SQL Injection

S Q L I N J E C T I O N E X A M P L E

<cfquery name="news">SELECT id, title, storyFROM newsWHERE id = #url.id#

</cfquery>

news.cfm?id=1;delete+from+news

W H Y I S S Q L I N J E C T I O N B A D ?

• Allows attacker to do any of the following:

• Download all data in database

• Modify or Delete all data in database

• Execute stored procedures or processes in some cases

Try the SQL Injection Lesson

F I X I N G S Q L I N J E C T I O N

• Use parameters (eg cfqueryparam) whenever possible

• Validate and sanitize when you can’t

• ORDER BY column

• SELECT TOP 10

F I X I N G S Q L I N J E C T I O N

<cfquery name="news">SELECT id, title, storyFROM newsWHERE id = #url.id#

</cfquery>

<cfquery name="news">SELECT id, title, storyFROM newsWHERE id = <cfqueryparam value="#url.id#" cfsqltype="integer">

</cfquery>

F I X I N G S Q L I N J E C T I O N

<cfscript>q = QueryExecute("SELECT story FROM news WHERE id = #id#”);

</cfscript>

<cfscript>q = QueryExecute("SELECT story FROM news WHERE id = :id", {id=url.id});

</cfscript>

F I X I N G S Q L I N J E C T I O N

<cfscript>n = ORMExecuteQuery('FROM News WHERE id = ' & url.id);

</cfscript>

<cfscript>n = ORMExecuteQuery('FROM News WHERE id = :id', {id=url.id});

</cfscript>OR<cfscript> n = ormExecuteQuery('FROM News WHERE id = ?', [url.id]);</cfscript>

F I L E A C C E S S I S S U E SP E T E P R E S E N T S

PAT H T R AV E R S A L S

<cfinclude template="files/#url.fileName#">

PAT H T R AV E R S A L S

<cfinclude template="files/#url.fileName#">

page.cfm?fileName=../secret.txt

PAT H T R AV E R S A L S

• Any code that accesses files can be vulnerable:

• cffile, cfdocument, cfinclude, cfmodule, cfspreadsheet

• fileOpen, fileRead, fileWrite, etc.

• cfdirectory, directoryList, etc.

W H Y A R E PAT H T R AV E R S A L S B A D ?

• Attacker can read files that CF has read access to.

• Access passwords, configuration

• Can lead to other vulnerabilities (RCE)

PAT H T R AV E R S A L L E S S O N

F I X I N G PAT H T R AV E R S A L S

• Review all code that access the file system.

• Avoid using taintable variables in paths

• If you do use variables strip / sanitize them

• ESAPI Validator.getValidFileName, etc.

• Define this.compileExtForInclude in Application.cfc (CF11+)

• Separate data into multiple drives (on Windows)

F I L E U P L O A D V U L N E R A B I L I T I E S

• Big Risk: attacker can upload / execute cfm (or any server executed file)

• Other Risks: attacker can upload files used for XSS, phishing, etc.

F I L E U P L O A D S : R U L E # 1

N E V E R T R U S T A M I M E

F I L E U P L O A D S

<cffile action="upload" accept="image/jpg,image/png,image/jpeg" filefield="photo" destination="#ExpandPath("./photos/")#">

File Upload Lesson

F I L E U P L O A D S : S T R I C T AT T R I B U T E

• CF10 Added the strict attribute to cffile action=upload, it defaults to true for CF10 and above.

• When strict="true" CF does a server side file type check based on the mime types in the accept attribute.

• When strict="false" CF only looks at the MIME types sent by the browser as in CF9 and below.

F I L E U P L O A D S : S T R I C T AT T R I B U T E

• Does strict="true" prevent an attacker from uploading a cfm file?

F I L E U P L O A D S : R U L E # 1

NO!

F I L E U P L O A D S : R U L E # 2

A LWAY S C H E C K T H E F I L E E X T E N S I O N

F I L E U P L O A D S : F I L E E X T E N S I O N

• Use a file extension whitelist, instead of a blacklist.

• On CF10+ you can do: accept="*.jpg,*.png"

• But you must also specify strict="false"

F I L E U P L O A D S : F I L E E X T E N S I O N

• In the VM uncomment lines 13-18 of /my-account/register.cfm to add a file extension check.

File Upload Lesson: Can You Still Upload / Execute a CFM?

F I L E U P L O A D S : R U L E # 3

D E S T I N AT I O N PAT H M U S T N O T B E U N D E R W E B R O O T

D E S T I N AT I O N I S I M P O R TA N T

POST /upload.cfm

GET /photos/photo.cfmServer

Hacker

Hacker uses a load tool to make repeated concurrent requests.

The attacker will be able to execute photo.cfm before it is deleted.

F I L E U P L O A D S : A D D I T I O N A L T I P S

• Inspect file content: fileGetMimeType, isImageFile, isPDFFile, etc

• Upload to static content server (s3 for example)

• Upload directly to s3: https://www.petefreitag.com/item/833.cfm

• Make sure directory serving uploaded files cannot serve dynamic content.

• File Extension Whitelist on Web Server (eg IIS Request Filtering)

• secureupload.cfc: https://github.com/foundeo/cfml-security/

C R O S S S I T E S C R I P T I N G ( X S S )D A V I D P R E S E N T S

X S S

• XSS holes give attackers a CMS to create any content.

• Can be used to steal sessions

• Phish for passwords or other info.

X S S : T Y P E S

• Reflected

• Persistant

• DOM

X S S : R E F L E C T E D X S S E X A M P L E

<cfoutput>Hello #url.name#

</cfoutput>

hello.cfm?name=<script>...</script>

X S S L E S S O N

P R E V E N T I N G X S S

• Strip out dangerous characters, for example: < > ' " ( ) ; #

• Escape dangerous characters

• CF10+ EncodeForHTML, etc.

• CF2016+ <cfoutput encodefor="html"></cfoutput>

P R E V E N T I N G X S S

Context Method

HTML encodeForHTML(variable)

HTML Attribute encodeForHTMLAttribute(variable)

JavaScript encodeForJavaScript(variable)

CSS encodeForCSS(variable)

URL encodeForURL(variable)

P R E V E N T I N G X S S I N H T M L

• Preventing XSS while allowing HTML is difficult.

• AntiSamy -> isSafeHTML getSafeHTML

• ScrubHTML

X S S U T I L S

• Encoders

• ESAPI: http://www.petefreitag.com/item/788.cfm

• OWASP Encoder: http://owasp-java-encoder.googlecode.com

• Sanitizers

• AntiSamy: http://www.petefreitag.com/item/760.cfm

• ScrubHTML: https://github.com/foundeo/cfml-security

O W A S P Z A P

• An easy to use web application penetration testing tool

• Completely free and Open Source

• OWASP flagship project

• Included in major security distributions

• Kali, Samurai WTF, etc.

W H Y U S E Z A P ?

• Ideal for beginners, developers

• also used by professional pen testers

• Point and shoot via Quick Start Tab

• Manual penetration testing

• As a debugger

• As part of larger security program

• Automated security regression tests

M A I N Z A P F E AT U R E S

• Intercepting Proxy

• Active and Passive Scanners

• Traditional and AJAX spiders

• Forced browsing

• Fuzzing

• Cross Platform

• built on Java (requires 1.7+)

I N T E R C E P T I N G P R O X Y

Website

U S I N G Z A P - D E M O

S E C U R I T Y H E A D E R SP E T E P R E S E N T S

S E C U R I T Y H E A D E R S

• Modern browsers look for certain HTTP response headers to opt into security features.

• Setting a header in CFML:

• <cfheader name="Header-Name" value="Whatever">

• cfheader(name="Header-Name", value="Whatever");

• You can also configure your web server to send response headers

C O N T E N T- S E C U R I T Y- P O L I C Y ( C S P )

• The Content-Security-Policy Header allows the browser to restrict what additional resources are loaded / executed by the requested document.

C S P H E A D E R S C A N T E L L T H E B R O W S E R T O …

• Only load images, css, fonts, etc from the same origin or a whitelist of origins.

• Only load whitelisted javascript

• Restrict what plugins can be used

• And more…

C S P B R O W S E R S U P P O R T

• Ignored on browsers that do not support it.

• Chrome: 25+ (Level 2 40+ Jan 2015)

• FireFox 23+ (Level 2 31+ / July 2014)

• Safari 7+ (Level 2 10+ / 9.3+ on iOS)

• IE Edge 12+ (Level 2 in development)

C S P L E V E L 1 B R O W S E R S U P P O R T

Source: caniuse.com Global Support was 85% in 2015

C S P L E V E L 2 S U P P O R T

Source: caniuse.com

C S P D I R E C T I V E S

•default-src

•script-src

•style-src

•img-src

•connect-src

•font-src

•object-src

•media-src

•frame-src

•sandbox

•report-uri

•plugin-types (level 2)

•frame-ancestors (level 2)

•form-action (level 2)

E X A M P L E C S P H E A D E R S

• script-src 'self';

• script-src 'self' cdn.example.com;

• script-src 'none';

• script-src 'unsafe-inline';

• default-src 'none'; script-src 'self'

C S P D I S A B L E S I N L I N E S C R I P T S

• It will not execute:

• <script>alert('Hi')</script>

• <div onmouseover="alert('Hi');">Hi</div>

• <a href="javascript:alert('Hi');">Hi</div>

• You must do one of the following:

• Put JS in a file and load via script src on a whitelisted origin.

• You can whitelist the script by putting a hash of the script in your header

• You can put a nonce in your header and then specify nonce attribute in script or style tag.

• You can specify: unsafe-inline but it defeats most value of CSP

S T R I C T T R A N S P O R T S E C U R I T Y ( H S T S )

• The Strict-Transport-Security header Instructs the browser to always request a domain using the HTTPS protocol instead of HTTP.

W H E N T O U S E H S T S

• If you redirect port 80 HTTP to 443 HTTPS you should use HSTS.

• If your site supports HTTPS you should use HSTS

• This will force all traffic to be HTTPS on browsers that support it.

• You still need to setup a 301 redirect from HTTP to HTTPS

W H Y U S E H S T S ?

• Passive Network Attacks - man in the middle, HTTPS stripping attacks

• Active Network Attacks - compromised DNS, evil twin domain

• Mixed Content Vulnerabilities - eg load swf over insecure request

• Performance - remove unnecessary redirect from HTTP to HTTPS

• Because no one types https:// in the address bar.

W H Y U S E H S T S ?

H S T S D I R E C T I V E S

• max-age the number of seconds the policy should be kept for

• includeSubDomains apply the policy to all subdomains

• if omitted applies only to current domain.

• preload tells browser to bake policy into future versions of browser

H S T S : E X A M P L E

Strict-Transport-Security: max-age=31536000; includeSubDomains

H S T S : H O W T O H A N D L E R E Q U E S T S

• Requests over HTTP (non secure)

• Should response with a 301 redirect to secure url.

• Must not respond with Strict-Transport-Security header

• Requests over HTTPS (secure)

• All requests for domain should return Strict-Transport-Security header (so web server is typically best place to put this header)

H S T S : B R O W S E R S U P P O R T

• IE11+

• Firefox 4+

• Chrome 4+

• Safari 7+

• iOS Safari 7.1+

• Android 4.4+

• Android Chrome 51+

O T H E R S E C U R I T Y H E A D E R S

• Public-Key-Pins - tells browser what certificates to trust for domain

• X-Frame-Options - tells browser not to load your site in frames (to prevent click jacking).

• X-Xss-Protection - enable/disable the XSS filter in browsers.

• X-Content-Type-Options - tells browser not to sniff content to figure out mime types.

S E C U R I T Y H E A D E R S L E S S O N

C R O S S S I T E R E Q U E S T F O R G E R YD A V E P R E S E N T S

C R O S S S I T E R E Q U E S T F O R G E R Y

• Causes a user’s web browser to perform an unwanted action on a trusted site for which the user is currently authenticated

• Could result in a transfer of funds, changing a password, or purchasing an item

• Impact vary greatly based on the privileges of the user

• Occurs without knowledge of the target user, until the unauthorized transaction has been committed

R E A L W O R L D C S R F E X A M P L E

• Netflix in 2006

• It was possible to add a movie to a persons queue with following

• Worked because Netflix was only checking for a remember me cookie at the time and not an active session

• Browser sends associated cookies for the URL requested

<img src="http://www.netflix.com/AddToQueue?movieid=70011204" />

F I X I N G C S R F

• Require POST

• CSRF is still possible, but a bit more difficult

• Reject Bad Referers or no Referer

• Referers can be spoofed or turned off

F I X I N G C S R F

• Require the user interaction through re-authentication, one-time password, or CAPTCHA

• Can be annoying, but best solution for sensitive transactions

• Random Token

• Include random token in hidden field

• Store token in session variable

• Compare value submitted and stored in session

C S R F A N D X S S

• Any XSS vulnerability can be used to defeat referer and random token

• Important to ensure XSS vulnerabilities do not exist so CSRF defenses cannot be circumvented

• XSS cannot defeat re-authentication, CAPTCHA, or one-time passwords

C O L D F U S I O N C S R F T O K E N F U N C T I O N S

• CSRFGenerateToken([key], [forceNew])

• Generates a random token and stores it in the session

• CSRFVerifyToken(token, [key])

• Validates the passed in token against the token stored in the session

• Must have session variables enabled

C S R F L E S S O N

F I X I N G C S R F

• In user.cfm

• In set-balance.cfm

<form action=“set-balance.cfm” accept="POST" … > <input type=“hidden” name=“token" type=“#CSRFGenerateToken(“set-balance”)#”> …</form>

<cfif CSRFVerifyToken(form.token, “set-balance”)> <!--- do action here ---></cfif>

R E M O T E C O D E E X E C U T I O NP E T E P R E S E N T S

R E M O T E C O D E E X E C U T I O N

• Beware of functions that allow dynamic evaluation:

• Such as: Evaluate, IIF, PrecisionEvalute

• Beware of code that allows execution vai cfexecute, etc.

• Beware of cfinclude

R E M O T E C O D E E X E C U T I O N : E VA L U AT E

<cfset day_1 = "Wednesday"> <cfset day_2 = "Thursday"> <cfset day_3 = "Friday">

<cfoutput> #Evaluate("day_#url.day#")# </cfoutput>

R E M O T E E X E C U T I O N L E S S O N

F I X I N G E VA L U AT E

• In many cases you can replace with bracket notation, eg:

• variables["day_#url.day#"]

• or even better: variables["day_#int(url.day)#"]

• For a query:

• queryName["colName#i#"][queryName.currentRow]

R E M O T E C O D E E X E C U T I O N : I I F

<cfset greet = iif( len(name), de("Hi #name#"), de("Hi") )>

<cfset greet = ( len(name) ) ? "Hi #name#" : "Hi">

Ternary operator is supported in CF9+

A U T H E N T I C AT I O N & A U T H O R I Z AT I O ND A V E P R E S E N T S

A U T H E N T I C AT I O N & A U T H O R I Z AT I O N

• Authentication is used by a server when the server needs to know exactly who is accessing their information or site

• Authorization is a process by which a server determines if the client has permission to use a resource or access a file

PA S S W O R D S T O R A G E

• NEVER store in plain text

• Should be hashed with a salt with iterations

• Use strong hashing algorithm SHA-512 and avoid MD5 and SHA-1

• Or using an adaptive hash function

• PBKDF2 (password based key derivation function) algorithm

VA L I D U S E R ?

• Depending upon message returned possible for attacker to determine if valid user

• Don’t return separate messages for invalid user, invalid password, or account status (disabled/not active)

• If password hash function does not run when username is not found, possible to determine through timing

A U T H E N T I C AT I O N C O N S I D E R AT I O N S

• Password complexity rules

• Length, special characters

• Remember Me functionality

• Forgot Password functionality

• Brute force attacks

• Lock account for x minutes after given number of attempts

• Audit logs

A U T H O R I Z AT I O N

• Avoid relying on developer to include authorization

• Easy to miss one or 5

• Use onRequest or framework controller, interceptor, etc

A U T H L E S S O N

C O O K I E S & S E S S I O N SP E T E P R E S E N T S

C O O K I E AT T R I B U T E S

HTTPOnly Instructs the browser to prevent access to the cookie from non http apis (eg JavaScript)

Secure Instructs the browser to only send the cookie over secure channels such as HTTPS.

Path Allows you to restrict a cookie to certain URIs (eg /admin/)

Domain Allows subdomains to access cookies

ExpiresDetermines how long the cookie is stored by the

browser, or if omitted becomes a browser session cookie.

S E S S I O N I D E N T I F I E R S

sessionID == (username & password)

H O W A R E S E S S I O N I D E N T I F I E R S PA S S E D ?

• Cookie - best option, requires cookies to be enabled.

• Hidden Form Fields - can be leaked via XSS, difficult to work with

• URL / Query String - easily leaked, users copy/paste, logged in plain text

P R O T E C T I N G S E S S I O N I D S

• Always use HTTPS (Strict-Transport-Security if possible)

• Protect Cookies using HttpOnly and Secure flag (when using https)

• Never pass session ids in the url.

• Use different sessions for HTTP and HTTPS schemes.

T O J 2 E E O R N O T

J2EE CFID/CFTOKEN

Configured in Application.cfc No Yes

SessionRotate No Yes

SessionInvalidateDoes not invalidate J2EE session. Just

clears session struct.Yes

Cookies can be written from CFML. No Yes

T O J 2 E E O R N O T

J2EE CFID/CFTOKEN

Configure Session ID Length Yes No

Interoperable with JSP, Servlets Yes No

Configure Session ID cookie name Yes No

Sets secure flag automatically Yes No

S E S S I O N I N VA L I D AT E ( )

• SessionInvalidate() - CF10+ clears current session and invalidates the id.

• Call when user logs out.

• Call when malicious requests are made.

• Can’t use session scope after calling it.

• Does not invalidates the underlying J2EE session with J2EE sessions

S E S S I O N R O TAT E ( )

• Generates a new session & session id

• Copies session data into the new session

• Invalidates the old session id.

• Call after a successful login to prevent Session Fixation attacks.

E N C R Y P T I O ND A V E P R E S E N T S

E N C R Y P T I O N

• ColdFusion uses Java Cryptography Extension (JCE)

• JCE provides algorithm support to Encrypt, Decrypt, Hash, HMac, GenerateSecretKey, and GeneratePBKDFKey

• Enterprise edition ships with RSA BSAFE Crypto-J JCE to provide FIPS-140 compliant crypto algorithm

K E Y S T O R A G E

• Need to protect the private key used

• Don’t hardcode key into source

• Avoid storing in plain text

• Utilize Hardware Security Module (HSM), Java Keystore, or OS provided mechanism like Microsoft Data Protection API (DPAPI)

• Don’t store key adjacent to encrypted data

S T R O N G A L G O R I T H M

• Don’t use weak algorithms

• Never use CMFX_COMPAT, not cryptographically secure

• DES and Triple-DES

• Might need to install Java JCE Unlimited Strength Jurisdiction Policy Files to use certain encryption key sizes greater than 128

E X A M P L E W I T H A E S

• Step 1: GenerateSecretKey("AES")

• Defaults to 128, you can specify 256 if unlimited juristriction is enabled

• Call Encrypt(data, key, "AES/CBC/PKCS5Padding", "Base64")

• Decrypt(data, key, algorithm, encoding)

O T H E R I N J E C T I O N AT TA C K SP E T E P R E S E N T S

S C O P E I N J E C T I O N

• Due to how CF searches scopes, if a variable is not defined CF checks all scopes for the varaible.

• Suppose session.isAdmin is not defined in current session scope

• Attacker can simply do admin.cfm?session.isAdmin=1

P R E V E N T I N G S C O P E I N J E C T I O N

• In CF2016+ this.searchImplicitScopes=false in Application.cfc

• Define defaults for all important session / application variables in onSessionStart / onApplicationStart

• Use structKeyExists or scope.keyExists() to check for variable

• Avoid isDefined

S C O P E I N J E C T I O N L E S S O N

L D A P I N J E C T I O N

• Ensure that any user supplied variables (such as usernames) are stripped before using with CFLDAP.

• CF11+ Added encodeForLDAP() function.

P D F I N J E C T I O N

• The cfhtmltopdf or cfdocument tags can be vulnerable to injection causing server side execution.

<cfdocument>Hi #url.name#</cfdocument>

<cfhtmltopdf>Hi #url.name#</cfhtmltopdf>

pdf.cfm?name=<img src=http://10.0.0.4/internal/action>

P D F I N J E C T I O N

• The cfhtmltopdf tag uses WebKit to render HTML to PDF

• Can execute some JavaScript, CSS

• Has all potential vulnerabilities of Webkit

C R L F I N J E C T I O N

• Attacker injects CRLF character into variable that is written in to a header to create a new header or start HTTP response.

• CF10+ will strip CRLF out of header values in cfheader,

X PAT H I N J E C T I O N

• If untrusted variables are used to build an XPath query (eg XmlSearch function) attacker can alter query and potentially return a different node.

• Use EncodeForXPath() in CF11+

X M L E N T I T Y I N J E C T I O N

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "http://www.attacker.com/text.txt" >]><foo>&xxe;</foo>

Example from: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing

S E C U R I T Y A N A LY Z E R D E M O

T H A N K Y O U ! Q U E S T I O N S ?

P E T E F R E I TA G P E T E @ F O U N D E O . C O M

D A V I D E P L E R D E P L E R @ A B O U T W E B . C O M