Quick and dirty CAPTCHA Guide - for ColdFusion 8

A few months ago I posted a quick guide to walk folks through adding CAPTCHA's to forms:

Quick and dirty CAPTCHA Guide

This guide made use of the excellent Lyla CAPTCHA component. One of the new features of ColdFusion 8 is a built in CAPTCHA generator. So let's take a look at how we can do it the CF8 way...

First off, let's start with a simple contact us style form. I won't go into details about this form. It's a basic self-posting form with validation for a name and comment box.

<cfset showForm = true>
<cfparam name="form.name" default="">
<cfparam name="form.comments" default="">

<cfif isDefined("form.send")>
   <cfset errors = "">
   
   <cfif not len(trim(form.name))>
      <cfset errors = errors & "You must include your name.<br />">
   </cfif>

   <cfif not len(trim(form.comments))>
      <cfset errors = errors & "You must include your comments.<br />">
   </cfif>
      
   <cfif errors is "">
      <!--- do something here --->
      <cfset showForm = false>
   </cfif>
   
</cfif>

<cfif showForm>

   <cfoutput>
   <p>
   Please fill the form below.
   </p>
   
   <cfif isDefined("errors")>
   <p>
   <b>Correct these errors:<br />#errors#</b>
   </p>
   </cfif>
   
   <form action="#cgi.script_name#" method="post" >
   <table>
      <tr>
         <td>Name:</td>
         <td><input name="name" type="text" value="#form.name#"></td>
      </tr>
      <tr>
         <td>Comments:</td>
         <td><textarea name="comments">#form.comments#</textarea></td>
      </tr>
      <tr>
         <td> </td>
         <td><input type="submit" name="send" value="Send Comments"></td>
      </tr>
   </table>
   </form>
   </cfoutput>
   
<cfelse>

   <cfoutput>
   <p>
   Thank you for submitting your information, #form.name#. We really do care
   about your comments. Seriously. We care a lot.
   </p>
   </cfoutput>
   
</cfif>

Hopefully nothing above is new to you. So lets start updating this with some CAPTCHA love. First off, creating a CAPTCHA in ColdFusion 8 is incredibly easy. It takes all of one tag:

<cfimage action="captcha" width="300" height="75" text="paris">

The width and height determine the size of the image. The text determines what text will be displayed on the CAPTCHA. You can also determine what fonts to use - as well as the difficulty level.

So that part is easy. Everything after that takes a little bit of work. The first thing you need to figure out is what text to use. In the example above I used a hard coded value, paris, but in the real world you wouldn't do that. If you do, spammers would get past your CAPTCHA rather quickly.

You can create a list of random words - but unless your list is pretty big, you will again have the issue of spammers being able to guess the word. Instead, I recommend a random set of letters. I've built a UDF just for this purpose. Let's take a look:

<cffunction name="makeRandomString" returnType="string" output="false">
   <cfset var chars = "23456789ABCDEFGHJKMNPQRS">
   <cfset var length = randRange(4,7)>
   <cfset var result = "">
   <cfset var i = "">
   <cfset var char = "">
   
   <cfscript>
   for(i=1; i <= length; i++) {
      char = mid(chars, randRange(1, len(chars)),1);
      result&=char;
   }
   </cfscript>
      
   <cfreturn result>
</cffunction>

This UDF simply creates a random string from 4 to 7 characters long. You can tweak that size all you want, but any more than 7 will probably tick off your visitors. Also note the range of characters. I removed things like 1 (number one), l (lower case 'el'), and I (upper case "eye') since they can be confusing. Thanks to the NYCFUG members for feedback on this.

So once we have the UDF, we can now generate random text. But now we have another problem. When we submit the form, we are going to need to validate that the text you entered is the same as the text in the image. To do that, we need to store the text. Imagine if we did this:

<cfset captcha = makeRandomString()>
<input type="hidden" name="captchatext" value="#captcha#">

As you can imagine, this is not very secure. A spammer would simply look for the hidden form field. So we need to encrypt the string somehow. ColdFusion offers multiple ways of doing this. For example though I'll just hash it:

<cfset captcha = makeRandomString()>
<cfset captchaHash = hash(captcha)>

Then I can add the CAPTCHA to my form like so:

<tr>
   <td>Enter Text Below:</td>
   <td><input type="text" name="captcha"></td>
</tr>
<tr>
   <td colspan="2">
   <cfimage action="captcha" width="300" height="75" text="#captcha#">
   <input type="hidden" name="captchaHash" value="#captchaHash#">
   </td>
</tr>

Now the form has both the captcha and the text in hashed form. The last step is to just add the new validation. I do this by hashing the user's text against the hidden form field:

<cfif hash(ucase(form.captcha)) neq form.captchaHash>
   <cfset errors = errors & "You did not enter the right text. Are you a spammer?<br />">
</cfif>

And that's it. I'm done. The complete template is below. Enjoy.

<cffunction name="makeRandomString" returnType="string" output="false">
   <cfset var chars = "23456789ABCDEFGHJKMNPQRS">
   <cfset var length = randRange(4,7)>
   <cfset var result = "">
   <cfset var i = "">
   <cfset var char = "">
   
   <cfscript>
   for(i=1; i <= length; i++) {
      char = mid(chars, randRange(1, len(chars)),1);
      result&=char;
   }
   </cfscript>
      
   <cfreturn result>
</cffunction>

<cfset showForm = true>
<cfparam name="form.name" default="">
<cfparam name="form.comments" default="">
<cfparam name="form.captcha" default="">
<cfparam name="form.captchaHash" default="">

<cfif isDefined("form.send")>
   <cfset errors = "">
   
   <cfif not len(trim(form.name))>
      <cfset errors = errors & "You must include your name.<br />">
   </cfif>

   <cfif not len(trim(form.comments))>
      <cfset errors = errors & "You must include your comments.<br />">
   </cfif>

   <cfif hash(ucase(form.captcha)) neq form.captchaHash>
      <cfset errors = errors & "You did not enter the right text. Are you a spammer?<br />">
   </cfif>
      
   <cfif errors is "">
      <!--- do something here --->
      <cfset showForm = false>
   </cfif>
   
</cfif>

<cfif showForm>

   <cfset captcha = makeRandomString()>
   <cfset captchaHash = hash(captcha)>

   <cfoutput>
   <p>
   Please fill the form below.
   </p>
   
   <cfif isDefined("errors")>
   <p>
   <b>Correct these errors:<br />#errors#</b>
   </p>
   </cfif>
   
   <form action="#cgi.script_name#" method="post" >
   <table>
      <tr>
         <td>Name:</td>
         <td><input name="name" type="text" value="#form.name#"></td>
      </tr>
      <tr>
         <td>Comments:</td>
         <td><textarea name="comments">#form.comments#</textarea></td>
      </tr>
      <tr>
         <td>Enter Text Below:</td>
         <td><input type="text" name="captcha"></td>
      </tr>
      <tr>
         <td colspan="2">
         <cfimage action="captcha" width="300" height="75" text="#captcha#">
         <input type="hidden" name="captchaHash" value="#captchaHash#">
         </td>
      </tr>      
      <tr>
         <td> </td>
         <td><input type="submit" name="send" value="Send Comments"></td>
      </tr>
   </table>
   </form>
   </cfoutput>
   
<cfelse>

   <cfoutput>
   <p>
   Thank you for submitting your information, #form.name#. We really do care
   about your comments. Seriously. We care a lot.
   </p>
   </cfoutput>
   
</cfif>

Comments

Will's Gravatar Hey Ray, we are trying to use a CAPTCHA in our application but for various reason we are writing the file to a location before using it on screen. Most CF tags that give an option to display something or write to a destination, do one OR the other. It seems with cfimage and CAPTCHA, even if you specify a destination attribute it ALSO tries to write it to the browser. For example, if I put destination="c:\image.jpg", it writes the file to the c drive then renders <img src="c:\image.jpg"> in the final HTML. Not at all what I would expect from the documentation or past experience with other CF tags. Would you consider that normal behavior or a bug?
# Posted By Will | 2/29/08 7:32 AM
Raymond Camden's Gravatar Confirmed. You can fix this by wrapping the tag in cfsavecontent. That will suppress it. I'm filing a bug report now.
# Posted By Raymond Camden | 2/29/08 8:18 AM
Will's Gravatar Thanks, Ray - for both the fix and filing the bug. You're a life saver!
# Posted By Will | 2/29/08 8:34 AM
Bob's Gravatar Very helpful.
May I ask why you use the ucase function when validating in this line:

<cfif hash(ucase(form.captcha)) neq form.captchaHash>

Thanks.
# Posted By Bob | 5/6/08 9:49 AM
Raymond Camden's Gravatar I've had issues with case and hashes before, so this just removes it.
# Posted By Raymond Camden | 5/6/08 10:00 AM
Nate's Gravatar Occasionally the captcha image has an icon character in it, like a skull and crossbones or the international "rewind" symbol (like <<). Is there a way to restrict it to just numbers and letters? I don't expect my site users to know the hotkeys for dingbat symbols, etc. :-)

I put an example up at http://www.centralscene.com/captcha/captcha.png (keyboard icon).

Thanks for the great example, and the help!
# Posted By Nate | 5/8/08 5:34 PM
Raymond Camden's Gravatar @Nate:

You can control the text since - well - you have to. But what you are seeing is the font being one of the symbol fonts. CF's captcha support lets you specify fonts. I didn't do that in my example as I wanted the code to work on both Macs and Windows machines. In a real production environment you would want to specify a few fonts that you know folks can read.
# Posted By Raymond Camden | 5/9/08 8:36 AM
Eric's Gravatar Working on adding this to my website, but I get an error on the random character generator script.

   <cfscript>
   for(i=1; i <= length; i++) {
      char = mid(chars, randRange(1, len(chars)),1);
      result&=char;
   }
   </cfscript>
# Posted By Eric | 8/9/08 3:02 PM
Raymond Camden's Gravatar Eric - are you sure you are using CF8? What error do you get?
# Posted By Raymond Camden | 8/9/08 3:24 PM
Radek's Gravatar Hi I tried this and it works great, the problem what I have is I have CF 7 and want to make it work but of course it is throwing an error about the cfscript, is there a way or something to make it workunder CF 7?
# Posted By Radek | 9/22/08 5:53 PM
Raymond Camden's Gravatar Change the <= to lte.
# Posted By Raymond Camden | 9/22/08 7:58 PM
farshid's Gravatar Thanks a lot Raymond,

Your solution is very user friend and cool,

Good luck in your life,
# Posted By farshid | 10/13/08 2:14 AM
Mike Pacella's Gravatar Ray,

Excellent post. I used a lot of your code as the basis for my captcha functionality.

One comment, though. What about the problem of a user who submits 1 for your form.captcha field, and then the hash of 1, (which is c4ca4238a0b923820dcc509a6f75849b) for the form.captchaHash field? Way to easy to break that IMO.

In order to fix this, one thing we've done is concatenated a secret suffix to the captcha text before hashing it. For example:

Let the secretSuffix = "iHateRobots".
Let the randomly generated string = "ABCDE";

We would now hash ("ABCDEiHateRobots") and store that in the form.captchaHash field. When checking for validity simply:

Let the user input = "ABCDE";

Hash the userInput & secretSuffix, check against your form.captchaHash field, and this will protect you against that basic CAPTCHA bypass.

With all of that having been said, this post is excellent and superbly captures the basics of creating a captcha. Nice job, and thanks again for the post!

- Mike
# Posted By Mike Pacella | 1/12/09 1:12 PM
Raymond Camden's Gravatar Mike, nope, that is precisely the biggest issue with my code here (and I think someone may have raised it already). What you are doing is referred to as adding a salt (I believe) and would be a smart idea. You could store that salt in the session which is another way to help block a robot as they will not (normally) have a session. You would want the salt to be random as well. Ie, onSessionStart, session.salt = random.
# Posted By Raymond Camden | 1/12/09 1:21 PM
Mike Pacella's Gravatar Even better! Random session salt versus one globally concatenated suffix would work perfectly for us. So simple, yet so very powerful. Thanks again, and keep up the great posts!
# Posted By Mike Pacella | 1/12/09 3:08 PM
Beaglis's Gravatar captcha doesn't display in Palm Blazer v4.5 (Treo 700p). Anybody have any experience with this issue?
# Posted By Beaglis | 1/14/09 1:39 PM
Beaglis's Gravatar I found out the problem with Captcha and Blazer. CFimage generates a PNG file that has 'layers'. If I open the generated captcha image in photoshop and the 'flaten' the image and get rid of the layer and then re-save, then I can view the image in Blazer.

Anyone know how to make CF generate a captcha png without layers? Or some workaround to this?

Thanks.
# Posted By Beaglis | 1/14/09 2:04 PM
Beaglis's Gravatar I found a workaround...

I save the captcha to a destination (use cfsavecontent as mentioned above), then I convert the image format to jpg, then I display the image with IMG tag.

Converting to JPG removes the layers.
# Posted By Beaglis | 1/14/09 2:32 PM
levensok's Gravatar This was an excellent tutorial! I did have one problem with implementation. The captcha cfimage displays fine for about 5 minutes after restarting the app server, then intermittantly will not display unless the page is refreshed a bunch of times. Here's my example:

http://v3.lightspeedvt.net/ebay_reg/register.cfm

If you refresh the page a few time, the captcha image will by displayed and then broken seemingly at random.
# Posted By levensok | 1/21/09 5:37 PM
Raymond Camden's Gravatar I wonder if it is a bad font? If you did not specify the fonts attribute, the font is going to be random. So maybe specify a font that works, and see if it works well 100% of the time.
# Posted By Raymond Camden | 1/21/09 7:59 PM
Andrew's Gravatar Seems like 'levensok' gave up, example url does not have captcha on it any more.
# Posted By Andrew | 2/6/09 6:47 AM
Geoff's Gravatar In addition to the server side checks on the captcha you can use javascript on the client side to check it before allowing submission of the form. There are two hashing libraries for JS available, at least. I'm using SHA-256 in CF and the JS library that offers the same.

This has the advantage of alerting the user before submission that they've got it wrong, which is less stressful than waiting for a response to find out and having the characters change all over again.

It's not going to do much in the way of preventing brute force attacks etc as they'll be posting direct, but it does mitigate some of the negative effects on the user.
# Posted By Geoff | 2/18/09 6:14 PM
Lucas Sá's Gravatar I guess this is not a good method to block flooders. Indeed, it could block a spammer bot if the process doesn't start by a human. For example, if a man read a captcha, he (actually his robot) will be able to post as many things as he want (including in other resources that requires the same captcha), since the code has the Hash in a input hidden, so he could use the same hash (which he knows the captcha) for every post.

A good solution would be save the hash in Session scope, but it has its limitations. It impedes the user to access two pages that requires captcha simultaneously, once the first captcha would be "nullified" by the second.

In this case, I would suggest a mix between both solutions, creating an associative array (map, or a structure in the case of CF) of captchas generated for that user and store it in Session scope with the hash and the value of captchas. Also, put the hash in a hidden field as in this example and verify that hash in the "table" of captchas when user submits. If captcha matches the hash, delete its array register.
# Posted By Lucas Sá | 3/12/09 4:11 PM
Sam's Gravatar Has anybody thought about taking this a step further with regards to accessibility?

Standard captcha will cause problems for the blind and partially sighted. There is some good information about this on the W3C website;
http://www.w3.org/TR/2005/NOTE-turingtest-20051123...

Although these users make up a very small percentage of our visits, some websites need to incorporate alternatives to meet guidelines and to ensure nobody is excluded.

I have not seen an example yet of anybody using text to speech with coldfusion.

Your thoughts and ideas?
# Posted By Sam | 5/27/09 5:46 AM
Raymond Camden's Gravatar There is a Java project, FreeTTS, that could work. I'm looking at this today.
# Posted By Raymond Camden | 5/27/09 7:19 AM
peters's Gravatar Why dont we use encrypt and decrypt ?
# Posted By peters | 6/3/09 8:45 AM
Ron's Gravatar I am randomly getting an error when the page first loads.

"Cannot find the config file. configFile=..."

If you refresh the page, then it's fine, but its the initial load of the page.

Other than that, great script!
# Posted By Ron | 6/12/09 9:39 AM
Raymond Camden's Gravatar Um, what configFile? My demo here doesn't make use of it. Are you using my code here?
# Posted By Raymond Camden | 6/12/09 10:07 AM
Ron's Gravatar Oh wow! Thanks. That made me go back and compare code. It's a leftover from the previous captcha script I was using before I found yours.

Thanks for straightening me out.
# Posted By Ron | 6/12/09 10:26 AM
Sam's Gravatar Ray,

Did you have any success with the FreeTTS?
# Posted By Sam | 6/15/09 7:09 AM
Jeff's Gravatar Hey Ray,

Thanks for the post. Works great!

I find the captcha to always be legible but, is there a simple solution to provide a refresh link that doesn't clear the filled form fields?
# Posted By Jeff | 6/23/09 9:49 PM
Sam's Gravatar Hi Jeff,

I use a JavaScript method;

<a href="javascript:location.reload(false)">Refresh</a>

You can see this in action here;

http://www.stratford.gov.uk/labs/feedback/thickbox...

Hope this helps!

Sam.
# Posted By Sam | 6/24/09 2:56 AM
Sam's Gravatar I've realised the method I described above will not work in IE... the location.reload acts just like a browser refresh and IE will clear out the form fields annoyingly!

Thinking caps back on!
# Posted By Sam | 6/24/09 3:04 AM
Jeff's Gravatar Thanks Sam! I have another question to all... Is there a simple way to add email validation to this form? I like the idea of not using JavaScript to handle error messages but and pretty new to CF. I am using the code pretty much as is above and noticed that as long as the field isn't empty any value can be passed. Any help is appreciated.
# Posted By Jeff | 6/24/09 2:41 PM
Ron's Gravatar Add this to the <cfif isDefined("form.send")>

<cfif not len(trim(form.email)) or not isValid("email", form.email)>
<cfset error = error & "Please include a valid email address!<br>">
</cfif>
# Posted By Ron | 6/24/09 3:01 PM
rencontres's Gravatar nobody answered me about encrypt and decrypt why don't we use them to pass the captcha ? it looks better than hash
# Posted By rencontres | 6/24/09 3:12 PM
Jeff's Gravatar Thanks for that solution Ron! Worked like a charm!
# Posted By Jeff | 6/24/09 3:35 PM