430 likes | 1.33k Views
ColdFusion Code Security. Michael Smith President TeraTech, Inc ColdFusion, database & VB custom development and training. http://www.teratech.com 800-447-9120. Speaker Information. Who am I? Michael Smith President of TeraTech, Inc Rockville MD http://www.teratech.com/
E N D
ColdFusion Code Security Michael Smith President TeraTech, Inc ColdFusion, database & VB custom development and training. http://www.teratech.com 800-447-9120
Speaker Information Who am I? • Michael Smith • President of TeraTech, Inc Rockville MD • http://www.teratech.com/ • ttWebReportServer, CFXGraphicserver • MDCFUG, CFUN-02, Fusebox Conf • Articles in CFDJ, Fusion Authority
Introduction The ColdFusion security challenge: • Keeping hackers out • While still letting users and friendly apps in • Balance security vs easy of use
ColdFusion Security Here is what we will be covering: • Error handling • Form Validation • Page parameter validation • User Authentication • Members Only • Encryption and passwords
Not covered in this talk • Server security • Database security • Hardware security • Operating system security • TeraTech’s CF201 Class covers more security topics than we can cover in an hour.
Error handling • Always have an error handler in Application.cfm • Never display default CF errors - gives out SQL information and template paths • Instead email error to admin • Don’t explain why attempt failed • Standard processing time
Error handling code In Application.cfm: <cferror type="EXCEPTION" template="error_exception.cfm" mailto="#Request.ErrorNotifyEmail#"> <CFMAIL to="#error.MailTo#" from="info@teratech.com" subject="ColdFusion Error"> #error.RemoteAddress# #error.Template# #error.DateTime# #error.Diagnostics# </CFMAIL>
Form Validation • Why it is important • Underscore validation • CFFORM validation • Javascript validation • CF validation • SQL validation • Fake form submits
Why is validation important? • Malicious exploits are possible • Bad data may be entered • Server crashes • Hacker can force an error message
Underscore Validation • AKA Form-level validation • Easiest to implement <Input Type=“Hidden” Name=“field_required” value=“Error message”> • Runs on the server based on this hidden parameter from the form page • Trusts the browser that the form variable is passed • Effectively client-side, although actual validation occurs on the server
CFFORM Validation • Automagically generates form-level validation and javascript validation • Works well enough in simple forms • Does not adapt well for complex forms, need for complex validation, javascript, etc. • Generally roll-your-own is preferred • Still trusts browser
Javascript Validation • Available many places • Swipe from the source code generated by CFForm • http://builder.com/ • Totally browser dependent • With CF Form, won’t even submit if javascript not present • Effectively useless with 508 • BUT! Least server traffic
CF Validation • Occurring on the ACTION page, on the server side • Need not trust the browser • 508 compliant, browser independent • A little more complicated to write, but necessary on public sites
Authentication • Stateless web - any page can call another - this is good for open sites • Hacker pages call your page with false data • Use CGI. HTTP_REFERER to control who calls you • Use CGI. CF_TEMPLATE_PATH application.cfm control what is run. Warning - Can be spoofed by browser
Fake form submits • Hacker copies your HTML source to their machine, edits form fields and submits to your action page. • They can now edit your hidden fields or remove fields to generate error messages • Hidden form field token • Check HTTP_REFERER is in your domain
Fake URLs • Hacker edits your URL to get data they shouldn’t see or to force page error. • Protect URLs with checksum – eg hash() function.
Fake cookies • Cookies can be faked too – they are just in text file on client machine • Don’t assume cookie value is valid • For top security add checksum to cookie.
Page Validation • URL and Form parameters used in SQL • SELECT * FROM EMP WHERE ID = #USERID# • Extra SQL commands on SQL Server http://myserver/page.cfm?ID_VAR=7%3BDELETE%20FROM%20MyCustomerTable • | VBA functions - shell() on Access • xp_cmdshell in SQL Server • Use VAL() on parameters or check for ‘ and | or use <CFQUERYPARAM> • Encrypt Variables • Checksum URLs
CFQUERYPARAM • Code example <CFQUERY NAME="getFirst" DATASOURCE="cfsnippets"> SELECT * FROM courses WHERE Course_ID=<CFQUERYPARAM VALUE="#Course_ID#" CFSQLType="CF_SQL_INTEGER"> </CFQUERY> • Also runs faster SQL too – cached query plan.
Protect CFINCLUDE and CFMODULE files • Don’t let CFINCLUDE and CFMODULE files be run standalone – they may do bad things or generate error messages • Protect using a naming convention/ subdirectory and test in application.cfm of CGI.script_name • Especially important for Fusebox applications with many include files
Code to protect CFINCLUDE files • For Fusebox In Application.cfm: <CFIF CGI.script_name contains “index.cfm”> <!--- ok to run ---> <CFELSE> <CFABORT SHOWERROR="Protected page"> </CFIF> • Non-Fusebox – check filename/directory
Code Defensively • Assume bad things will happen and code for them • Always code the CFELSE and CFDEFAULTCASE • Check input parameters exist using CFPARAM, they are of correct type and are that they are in range. E.g. <CFPARAM NAME="" TYPE="numeric“>
Datasource password • Don’t put datasource userid and password in CF Admin – if any template is compromised hacker can destroy data • Don’t hardcode in every CFQUERY call • Use request variables in application.cfm and encrypt it • Or for super security set up user accounts in Oracle and have users enter userid/password when they logon.
Input massaging • Textarea field may be stored to database for redisplay • Bad users may enter JavaScript or CF functions into your text hoping you will use evaluate() on them. • Strip them out using a regular expression.
CFCONTENT • CFCONTENT can be misused to send back your source code – eg filename/path in URL • Store files it sends in directory outside of webroot.
Logins • Use Strong SSL where available • http://www.thawte.com/ • Require at least 8 chr password • Consider requiring numbers in password • Consider forcing regular password changes depending on application • Strong form validation • Consider blocking accounts after multiple failed attempts
Authentication • Protected Header code In your application.cfm or header.cfm to be included in every page. <CFIF cgi.script_name contains "/intranet/"> <cfif left(CGI.REMOTE_ADDR,11) is not "123.456.789"> <cfif not isdefined("session.authorized")> <CFLOCATION URL=”http://www.teratech.com/logon.cfm”> <cfabort> <cfelse> <cfset session.authorized = TRUE> </cfif> </cfif> Your protected links here </cfif> Warning - spoofed IP numbers will get around this code
Members Only • Session, client and cookies • Refresh issues • Timeouts • Remember me
Session, client and cookies Client Management • Use short timeouts. (conflicts with 508) • Consider rolling your own security • Use CFID / CFToken from URL or create your own cookies • Store information in database with a table to keep track of ID/Token combinations against user Ids • Most flexible method
Session, client and cookies Client Management • If you use session management (as enabled with CFApplication) • Lock your usage<CFLOCK scope=“Session”> • Limit session timeout, minutes not hours • Consider passing session vars into request vars at top and bottom of page
Session, client and cookies Client Management • Use client variables in place of session variables where you do not need to store complex values • Configure storage so that variables are stored in a DB, NOT the registry • Use WDDX if you have the occasional need for a complex variable • Don’t use too many cookies • Manually test for timeout less than 2 hours – client.last_access_datetime
Timeouts • Use as short a timeout as practical • Don’t want users annoyed • Do want to protect against trouble • Consider (also/instead) having cookies go away after browser closing • This is the default with cookies if you do not specify a time • If you create your own session management, you can do more
Session Tracking • Who is logged on now • Keep track of login times to see who’s logged in now, can record activity and determine based on last activity or logoff option • Variable and structure dump • Use CF_Dump or CF5 CFDump tags to output all session variables or all cookies, etc. http://www.smart-objects.com/docs.cfm?f=cf_dump.htm
Session hang over • User logs in then closes browser without logging out. • Hacker uses browser and if the session has not timed out they are logged in as previous user • Use CFCOOKIE on CFID and CFTOKEN to set these session cookies to expire immediately on browser close.
Remember Me Sites with Login functions often have “Remember Me” option • Be careful - want to be clear what this option means • Use <CFCookie> to set your own cookie • Store something other than username / password or a flag - consider some random values • Don’t turn option on by default
Members Only Summary • Session variables can still be used, with locks, but Client or Cookies are preferable • Use <CFLOCATION> after insert/cfmail to avoid issues • Short timeouts for login - experiment • Remember Me is easy with Cookie
Back button hacking • Hacker uses back button to view sensitive information from a users browser • Consider disabling back button, especially on logout <CFHEADER NAME="Expires" VALUE="06 Nov 1994 08:49:37 GMT"> <CFHEADER NAME="Pragma" VALUE="no-cache"> <CFHEADER NAME="cache-control" VALUE="no-cache, no-store, must-revalidate">
Encryption • Encrypt source so even if downloaded can not be read • Be aware that decryption programs exist • Encrypt sensitive data such as credit card numbers in database using CF encrypt() and decrypt(). • Consider storing hash() of password instead of plain text.
Hashing passwords <CFQUERY NAME="CheckPerson" DATASOURCE="UserData"> SELECT PasswordHash FROM SecureData WHERE UserID=<CFQUERYPARAM VALUE="#UserID#" CFSQLType="CF_SQL_CHARVAR"> </CFQUERY> <CFIF Hash(Form.Password) IS NOT CheckPerson.PasswordHash> <CFLOCATION URL="unauthenticated.cfm"> <CFELSE> <CFLOCATION URL="authenticated.cfm"> </CFIF>
Refresh Issues If delete/insert/update pages are refreshed, or other action pages, problems occur – hacker sees error message. • Immediately <CFLOCATION> after one of these actions to avoid this • Use the addtoken=“yes” parameter to keep any session changes across pages
Resources • http://www.allaire.com/developer/securityzone/ • http://www.macromedia.com/v1/developer/securityzone/ • http://www.houseoffusion.com/ Security section
What Security Means • Security is hard because a hacker only needs one window to be open to get in while the poor webmaster must work on closing dozens of holes. • Security is a way of thinking - how can they get in... • More knowledge is power - don’t keep security tips secret!
Next Steps • Conduct a security audit • Download Michael Dinowitz’s http://www.houseoffusion.com/ MunchkinLAN to test your site for holes • Remove CFDOCS • Validate pages • Authenticate pages • TeraTech’s CF201 class • Questions? Email me at michael@teratech.com