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).

@ThingsExpo Stories
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
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.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
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...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...