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)

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.

IoT & Smart Cities Stories
Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...