Welcome!

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 --->
</cfif>

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
DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
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...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, 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.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
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 ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"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.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, 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.
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...
SYS-CON Events announced today that Telecom Reseller 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, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.