Browser Validation


The Web server is responsible for securing data from prying eyes as it traverses the Internet to the browser. However, the Web server cannot guarantee the integrity of the data exchanged between the client and the back-end system. Hackers can still compromise sites running SSL. Because it is the doorway to the back-end systems, protecting the site from these attacks is ColdFusion's job.

Cross-site scripting, tampered-with form and URL values, and contaminated file uploads are social engineering methods used by hackers and script bunnies to attack your site. Validating all browser input is the most effective panacea for these attacks. ColdFusion provides several functions and tags as useful countermeasures. These countermeasures should be a fundamental part of every methodology for securing ColdFusion applications.

Cross-Site Scripting (XSS)

In February 2000, CERT (www.cert.org), DoD-CERT (www.cert.mil), et al., created the term cross-site scripting (XSS) to describe the injection of code by one source into the Web pages of another source. This attack involves using cookies, form and URL parameters, and other valid HTML to upload JavaScript, ActiveX, or other executable scripts into an unsuspecting Web site, enabling arbitrary code to run against the client's browser and/or the Web server.

NOTE

For the Macromedia Security Bulletin on Cross-Site Scripting, see ASB00-05 at http://www.macromedia.com/devnet/security/security_zone/asb00-05.html. For Macromedia's list of best practices for validating browser input, see TechNote Article 17502 at http://www.macromedia.com/cfusion/knowledgebase/index.cfm?id=tn_17502.


Cross-site scripting works because the Web server accepts nonvalidated input from the browser, and processes or redisplays the malicious code. Because the server uses the nonvalidated input to dynamically generate Web pages, the server treats the embedded script as if it came from a trusted sourcenamely itselfand runs it in the security context of the server's own pages. So in this vein, a hacker can inject malicious code into a secured (SSL) site, and dupe a consumer into sending their credit card information to their personal server.

The original CERT advisory (www.cert.org/advisories/CA-2000-02.html) lists the following example code:

 <A HREF="http://example.com/comment.cgi? mycomment=<SCRIPT>malicious code</SCRIPT>"> Click here</A> 

Changing the HTML character set, inserting database queries into cookies, sending hexadecimal character shell commands, and other Web-server-specific attacks are examples of recent XSS attacks.

TIP

Another XSS technique is to purposely request an incorrect URL from a site and append some JavaScript as the query string that will execute when the Web server displays the 404 error. The default error-handler templates in earlier versions of ColdFusion did not check the URL for invalid characters. Macromedia's Security Bulletin (MPS03-06) recommends either creating your own error handlers, or downloading the Macromedia patch at http://www.macromedia.com/devnet/security/security_zone/mpsb03-06.html. The updated templates are included in ColdFusion MX 6.1 Updater 1 and in ColdFusion MX 7.


The first line of defense against cross-site attacks is to update your Web server software. Web server vendors update their products (with hot fixes or service packs) and introduce new tools as the vendors are made aware of vulnerabilities. Examples of such tools are Microsoft's IIS Lockdown and URLScan Security tools (www.microsoft.com/technet/security/tools/default.mspx).

In terms of code, Macromedia recommends using the following techniques in your CFML:

  • Use CFHEADER to define a character set in HTML output.

  • Use built-in CFML tags such as CFARGUMENT, CFPARAM, CFQUERYPARAM, CFSWITCH, CFIF-CFELSE, CFLOCATION, CFHEADER, CFHTMLHEAD, etc.

  • Use built-in functions such as HTMLCodeFormat, HTMLEditFormat, URLEncodedFormat, URLDecode, ReplaceList, REReplace, REReplaceNoCase, SetEncoding, StripCR, etc.

  • Properly scope all variables.

  • Escape and replace special characters and tags content in Java.

  • Use the new CFMX 7 Scriptprotect setting, described in the next section.

The Scriptprotect Setting

ColdFusion MX 7 introduces the Scriptprotect attribute to protect ColdFusion variables from cross-site scripting attacks. The XSS protection mechanism is a customizable regular expression ColdFusion applies to one or more specified scopes. When enabled, ColdFusion applies the script protection at the beginning of the request during application setting processing. If one of the filtered words (object, embed, script, applet, or meta by default) is submitted as a tag in the specified scopes, ColdFusion replaces all occurrences with the text InvalidTag. However, the filtered words are allowed as regular text.

The Scriptprotect regular expression is defined in the CrossSiteScriptPatterns entry in the cf_root\lib\neo-security.xml (server configuration) or cf_root\WEB-INF\cfusion\lib\neo-security.xml (J2EE configuration):

 <var name="CrossSiteScriptPatterns">   <struct type="coldfusion.server.ConfigMap">     <var name="<\s*(object|embed|script|applet|meta)">       <string><InvalidTag</string>     </var>   </struct> </var> 

For backward compatibility, ColdFusion script protection is disabled by default. There are three places to enable it: in the ColdFusion Administrator, in Application.cfc, and in the CFAPPLICATION tag:

  • The Enable Global Script Protection option in the ColdFusion MX 7 Administrator Settings window enables XSS protection for the entire server.

  • In the Application.cfc, set the scriptProtect variable in the This scope; for example: this.scriptProtect=Form.

  • To use the CFAPPLICATION tag, specify the scopes you want to protect in the scriptProtect attribute.

NOTE

The Administrator setting sets the serverwide default value, but the scriptProtect variable and attribute override the Enable Global Script Protection setting at the application level.


Table 7.1 lists valid values for the Application.cfc variable and CFAPPLICATION tag attribute.

Table 7.1. Values for the Scriptprotect Variable/Attribute

VALUE

DESCRIPTION

None

Provides no protection for any scopes

All

Protects CGI, cookie, form, and URL variables

Comma-delimited list

Protects variables specified in the list


TIP

ColdFusion's XSS script protection can be applied to all ColdFusion scopes. However, this places additional processing overhead on the server. For this reason, when you specify a value of All to the scriptProtect variable/attribute, or if you enable it globally in the Administrator, only the commonly attacked scopes are protected (CGI, cookie, form, and URL).


Form and URL Hacks

Form and URL hacking are favorites in cross-site attacks. HTML forms are the chief interfaces used to collect data from clients, used for shopping carts, search engines, application/site security, guest books, and more. Because the browser renders the form, malicious users can download the form, modify the fields, and then submit the form from another server.

URL parameters typically drive dynamic Web pages. URL hacking involves manipulating the URL query string to alter the intended behavior of the rendered Web page. Developers typically evaluate one or more parameters in the URL query string to determine the content of the requested Web page. Perhaps the best example of this is search-engine result pageschanging one of the values in the URL query string usually changes the displayed results.

An attack known as SQL injection or SQL poisoning is the most prevalent version of form and URL hacking. Hackers use SQL injection to manipulate databases by submitting additional SQL statements in form fields and/or URL query strings. The additional SQL is usually something damaging like DROP TABLE Users WHERE 1=1. You can imagine the effects of completely removing a Web site's users table.

Since databases are the heart of most Web sites today, form and URL validation is paramount to ensure data integrity and site security. Web servershence regular HTMLoffer little to no defense against these attacks. Again, it is ColdFusion's responsibility to protect the data it sends to the back-end systems, and ColdFusion provides several tags and functions that perform the job well.

Validation Techniques

Traditionally, ColdFusion offers the following data validation techniques:

  • Decision functions

  • Client- and server-side form validation

  • Variable data-typing with CFARGUMENT, CFPARAM, and CFQUERYPARAM

ColdFusion MX 7 extends the validation techniques by adding more algorithms, options, and functions. This section introduces some of these changes. However, for greater detail see "Form Validation" in Chapter 12 of the Macromedia ColdFusion MX 7 Web Application Construction Kit.

To stop the majority of URL hacks, begin with the same methods highlighted in the Cross-Site Scripting section. Leverage the CF decision functions to stop SQL injections and similar hacks, specifically the following: IsBinary(), IsBoolean(), IsDate(), IsDefined(), IsNumeric(), IsNumericDate(), IsSimpleValue(), IsXML(), LSIsDate(), and LSIsNumeric(). ColdFusion MX 7 introduces the IsValid() function, which combines the functionality of most of the decision functions. In addition to testing regular expressions and numeric ranges, IsValid() can validate any legitimate ColdFusion format: array, binary, Boolean, credit card, date/time/eurodate/U.S. date, email, float/integer/numeric, guid, query, range, regex, ssn, string, struct, telephone, URL, UUID, variableName, XML, and U.S. ZIP code.

TIP

Use IsValid() as the function equivalent of the CFPARAM tag.


ColdFusion MX 7 extends the built-in client-and server-side form validation mechanisms. You can now create XML and Flash forms with extended validation algorithms.

  • The CFFORM tag provides client-side JavaScript for form-field validating in the browser.

  • The CFINPUT tag now provides the mask and validateat attributes. The mask attribute allows developers to create character patterns to control user data input in text fields. The validateat attribute specifies where data validation occurs. It accepts one or more of the following values in a comma-separated list: onBlur, where validation occurs in the browser when the form field loses focus; onSubmit, where validation occurs in the browser before the form is submitted; and onServer, where validation occurs on the server.

For server-side form validation, ColdFusion MX 7 also extends the existing hidden form-field validation support with an additional 12 validation rules. It also changes the special rule identifiers to suffixes beginning with _cf, but continues to support the original syntax for backward compatibility. The onServer value for the CFINPUT validateat attribute produces the same server-side validation rules as the hidden form-field method.

TIP

Both validateat=onServer and hidden form fields provide the same validation rules. However, use hidden form fields if you want to apply multiple validation rules to a single form field, or if you want to provide server-side validation for regular form fields.


Client- and server-side validation each has its pros and cons, but they share one common fatal flaw: They rely on code in the client. CFFORM (and related tags) generate form fields and the JavaScript code that evaluates them in the browser. ColdFusion's server-side validation relies on hidden form fields for the validation rules. Savvy hackers will save the rendered HTML forms and remove the JavaScript and/or hidden form fields, thus bypassing all validation.

TIP

A nice method of protection against user-modified form submittals is to code conditional logic that compares the CGI.HTTP_HOST and CGI.HTTP_REFERER values. For example:

 <cfif NOT FindNoCase(CGI.HTTP_HOST, CGI.HTTP_REFERER)> Invalid Form submittal <cflocation url="byebye.cfm"> </cfif> 

If this returns false, then you know the form was submitted from an external server.


A combination of client- and server-side validation is the best protection. However, be sure to also code your own CFML to perform data typing before sending values back-end systems. Use proper variable scoping and tags such as CFARGUMENT, CFPARAM, and CFQUERYPARAM to ensure that the correct variable exists and is of the correct type. Use IF-ELSE and SWITCH-CASE blocks to apply conditional logic and set default values.

Working with validation techniques requires more effort on your partbut considering the potential aftermath of a hack, an ounce of prevention….

File Uploads

The attacks described in this section center around affecting your site by directly manipulating your code and data. Allowing users to upload files directly to your Web server potentially exposes your entire system and network to harm. Electronic libraries and head-hunter sites are examples that typically allow file uploads. If unchecked, hackers can freely upload viruses, worms, Trojan horses, and so on, to your Web server, which can spread to your server farm, and eventually cripple your entire network.

The best defense against harmful file uploads is to avoid uploads altogether. If this feature is a vital part of your application's functionality, however, use software such as Norton Anti-Virus or McAfee to stop the spreading of worms and block Trojan horses. Limit uploading features to authenticated users. Only allow uploads of certain file types and lengths, and to a separate physical server running anti-virus software.

ColdFusion is not anti-virus, but you can write CFML that controls the destination, MIME type, and size restrictions, and that sets attributes of uploaded files. You can also code your own security routine in CFML that will limit uploading to authenticated users, as shown in Listing 7.3.

Listing 7.3. Limiting File Upload to Authorized Users

[View full width]

 <!---#### Name of file: uploader.cfm Description of the script: Displays cookies values captured from one site and set in the  URL of the local site. Sarge, ssargent@macromedia.com Date created: February 9, 2005 Change History: ####---> <cfsetting enablecfoutputonly="no"> <!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN> <html> <head>  <title>ColdFusion MX 7 Upload Test</title> </head> <body> <h2>ColdFusion MX 7 Uploader</h2> <cfif NOT IsUserInRole("publisher")>   <cfinclude template="loginform.cfm">   <a href="index.cfm">Back to index</a><cfabort> <cfelseif IsDefined("FORM.upload")>   <cfparam name="uploaddir" default="j:\otherserver\images">   <cftry>     <cffile action="upload" filefield="form.newfile" destination="#uploaddir#"  nameconflict="error" accept="image/jpeg; image/gif" attributes="readonly">     <cfif file.filesize gt 1024>       <cffile action="delete" file="#uploaddir#\#file.servername#">       <cfthrow message="your file is bigger than 1mb. try again!">       <cflocation url="#cgi.script_name#">     </cfif>     <cfcatch type="any">       <cfoutput>       <strong>message:</strong> #cfcatch.message#<br>       <strong>detail:</strong> #cfcatch.detail#<br>       </cfoutput>     </cfcatch>   </cftry> <cfelse>   <cfform enctype="multipart/form-data">   <cfinput type="file" name="item" size="25" message="you must choose a file to upload!"  required="yes">   <cfinput type="submit" name="upload" value="Upload!">   </cfform>   <a href="index.cfm">Back to index</a> </cfif> </body> </html> 



Advanced Macromedia ColdFusion MX 7 Application Development
Advanced Macromedia ColdFusion MX 7 Application Development
ISBN: 0321292693
EAN: 2147483647
Year: 2006
Pages: 240
Authors: Ben Forta, et al

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net