You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

CFDJ Feature — Strip Tease

Formatting complex user input to prevent cross-site scripting

I don't like browser-based WYSIWYG editors. There are a reasonably large number of them and several of the recent versions are even cross-browser-compatible with Mozilla and even some less popular browsers (although Safari continues to be problematic).

The technical issues surrounding the implementation of WYSIWYG editors aren't the reason I don't like them, in spite of continuing problems with their interfaces such as lack of support for tab indexes. I don't like WYSIWYG editors because users can't be trusted not to put lime green, blinking text on a hot pink background. It's inevitable, however, that if we want to keep our clients happy we have to adopt WYSIWYG editors in our applications. The genie is out of the bottle and there's no putting it back, and thanks to our friendly neighborhood spammers, there's something else we can't trust our users to do: provide HTML content without defiling our sites with pop-up ads and other malicious JavaScript.

There's a name for malicious code injected by a user into a web application: it's called a Cross-Site Scripting attack (CSS or XSS to avoid confusion with Cascading Style Sheets). There are a number of ways to deal with XSS attacks, most notably the ColdFusion native HTMLEditFormat() function that everyone should use (although almost no one does) to create form input elements (when CFINPUT isn't used). Although we still need this function and should continue to use it for forms and some other displayed text, it doesn't address the problem of dealing with input provided by WYSIWYG editors. The HTMLEditFormat() function - while crucial - doesn't allow the user to provide HTML content because it converts any characters provided in the input element into properly escaped HTML entities and so when this content is displayed the user will see HTML code instead of rendered HTML.

The problem of users providing HTML content requires a different solution: remove potentially malicious tags from the input. The process of removing these tags should always occur when the user provides the content (not when it's displayed later) to prevent the process from needlessly creating a performance bottleneck on your server.

Several years ago I contributed to the Common Function Library Project what appears to have become the de facto standard for removing potentially malicious tags from user-provided input. Every few months someone on the cf-talk mailing list asks how to remove malicious tags and inevitably, someone else on the list suggests the function I wrote. It's called StripTags() and can be found at www.cflib.org/udf.cfm?ID=774.

While I'm glad that ColdFusion developers have enjoyed this function and found it useful in developing their applications, this article isn't about that function. I've actually stopped using it myself in favor of what I believe is a more robust solution.

What's my secret? Extensible Style Language Transformations (XSLT) while more challenging to implement than a UDF provides a way to accomplish the same end results as the StripTags() function and provides greater control over the final result.

Why is this? One reason is that the StripTags() function uses Regular Expressions which while powerful are limited to a more or less one-dimensional view of the content, with no built-in understanding of attributes or the parent/child relationships of nodes.

Another reason is that the arguments of the StripTags() function are simple and their simplicity (a strength with regard to ease of use and time-to-market) limit the amount of control they can provide.

XSLT for XSS and Other X-cronyms
What does using XSLT to strip malicious tags entail? First, users who provide HTML content must provide their content as properly formatted XHTML, which is slightly different from traditional HTML in ways that will frustrate most non-programming users who have been forced to become comfortable with HTML. Fortunately, if you use any of the recent WYSIWYG editors there's a good chance it will ensure proper XHTML formatting, making the whole process invisible to the user.

Second, although the ColdFusion tags and functions for handling XML have allowed us to be lackadaisical about case-sensitivity, the standard for XML is that it is case-sensitive. As a result, your XSL template will need to address the difference between a "script" tag and a "SCRIPT" tag and a "ScRiPt" tag. Frustratingly the XSLT engine that drives the ColdFusion server's native XMLTransform() function doesn't support the lower-case() function yet. I'll show an only moderately annoying workaround for this later in the article.

Lastly, there's all that learning a new language (XSL) and dealing with all the little things in the new language that seem strange or difficult to grasp, which are often not well documented or that you may not realize at first are necessary, in some cases even after testing.

If after reading the last section you're interested in moving your malicious tag removal to an XSL solution, I'll describe some of the specifics. Listing 1 is a sample XSL template that can be used with the ColdFusion native XMLTransform() function to remove malicious tags once we know the content string is valid XHTML. At the top, the doctype declaration contains several entities to ensure that the XML transformation won't throw an error if the user provides a common entity such as   which is declared in the HTML specification but not in the specification for generic XML.

Following the doctype declaration is the document root element xsl:stylesheet, with a namespace (xmlns:xsl) that tells the XML processor where to find information about "xsl:" tags. Inside the xsl:stylesheet element it's necessary to declare the output method with the xsl:output tag - this tells the XML processor what the XML will be transformed into, in this case more XML.

Following the output are several xsl:variable tags that create variables that can be used throughout the document by adding the $ symbol to the beginning of the variable name, i.e., the "ucase" variable is referenced as $ucase. The first two of these variables are used to help us make the document case-insensitive so a user can't trick the filter by changing the case of the tags. The last variable specifies a list of HTML tags that will be removed when the transformation is applied. Setting the variable here, however, doesn't remove the tags - that's done in the fourth xsl:template tag from the top.

The first xsl:template tag matching "text()" copies any text nodes the user has provided. This is the actual content - everything else is formatting, and so this is the most important element to retain. Thus, if you wanted to remove all tags, you could do so by removing all the xsl:template tags in this XSL document except for the xsl:template tag matching "text()".

The second xsl:template tag matching "comment()" lets the user to put HTML comments in their content. Since HTML comments aren't dangerous, they can be allowed even though a user isn't likely to provide them.

The third XSL template tag matching "*" copies all HTML tags into the resulting output. You may be thinking to yourself, "I thought this was supposed to remove tags" - and you're right, but to remove only the desired set of tags it's necessary to copy all the tags first.

Besides copying these tags the xsl:template tag matching "*" also removes potentially malicious attributes including any attribute beginning with "on" such as "onmouseover" or "onclick" and any attribute containing the string "javascript:" at its beginning such as href="javascript:alert('I\'m an XSS attack');".

Subsequent xsl:template tags then remove any tags they match from the resulting XHTML content by matching the tag and omitting the xsl:copy tag. For some (script, style, iframe) the tag and all children of the tag are removed, and these xsl:template tags are ended with the / at the end of the opening tag. For others such as html and body, which are removed because it's assumed this content will appear in a formed HTML document, child tags are retained by including the xsl:apply-templates tag as a child of the xsl:template tag.

Check Yourself Before You Wreck Yourself
Unfortunately, it's not enough to simply slap an XSL transformation on the incoming content. This is partly because doing so can result in an error if the content isn't well-formed XML though it's also partly because the input element may not be required. Mostly, however, the content must be pre-formatted to eliminate the need for the user to enter all the content in a document root element. Users don't know what a document root element is, nor will they ever care, they just want to make the text bold, so you can't require them to add a div tag to any content they provide, it's just going to frustrate them and reflect badly on you.

Listing 2 is a tidy little CFC containing all the methods you'll need to handle testing and formatting user-provided HTML content. The parseXHTML() method converts user-provided content into an XML document to which the XSL Transformation can be applied. This method ensures compatibility with ColdFusion version 6 or 6.1 (ColdFusion 7 doesn't require that an XML document be parsed before it's transformed) and uses the XHTML doctype to ensure that HTML entities such as   won't produce an error. The method is private because it will produce an error if the content provided by the user isn't valid XHTML. The job of the following two methods is to remove malicious tags and test the validity of the XHTML content string by attempting to execute the parseXHTML() method against the content string internally.

To put this in focus, a ColdFusion page receiving content from a WYSIWYG editor would use the following code to create this CFC:

<cffile action="read" variable="xslFilter" file="#expandpath('inputFilter.xsl')#">
<cfset Guardian = CreateObject("component","HtmlGuardian").init(xslFilter)>

Once the guardian object is created, it can be used in one of two ways. The first method is to simply attempt to filter the content provided by the user and if an error occurs, remove all the content entirely. This is done with the following code:

<cfset form.content = Guardian.filterXHTMLInput(form.content)>

If the system requires the provided content, it will be necessary to test the content for validity to provide users with a validation message indicating that their content isn't valid and can't be saved. This can be done either by checking the length of the string after attempting to filter it, or by checking the length of the string, then testing its validity as below.

<cfif not len(trim(form.content)) or not Guardian.inputIsXHTML(form.content)>
    <!--- invalid content provided --->

The Denouement
Although I've focused on the task of removing malicious tags in this article, it's also possible (and certainly more secure) to focus instead on allowing only a specific subset of known tags to allow, say, bold and italic tags. Although I haven't covered this subject specifically the samples provided should give you a good starting point from which this technique can be streamlined to suit your specific application needs.

More Stories By Isaac Dealey

Isaac Dealey has worked with ColdFusion since 1997 (version 3) for clients from small businesses to large enterprises, including MCI and AT&T Wireless. He evangelizes ColdFusion as a volunteer member of Team Macromedia, is working toward becoming a technical instructor, and is available for speaking engagements.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

Most Recent Comments
SYS-CON Brasil News Desk 04/17/06 04:18:00 PM EDT

I don't like browser-based WYSIWYG editors. There are a reasonably large number of them and several of the recent versions are even cross-browser-compatible with Mozilla and even some less popular browsers (although Safari continues to be problematic).

IoT & Smart Cities Stories
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...