Preventing SQL Injection
Posted by Steve Brownlee on August 28, 2008Aug 28
An old client of mine recently contacted me with a problem. Their home page, several sub-pages, and the administrative section weren’t displaying properly and functionality was broken. Turns out, they were a victim of the recent swarm of SQL injection attacks.
After pulling the old code out of my repository, I discovered that I’d used CFQUERYPARAM (I won’t iterate the hundreds of articles you can find by yourself stating, “USE CFQUERYPARAM, DUMMY!!”) in all of my business logic code, so I couldn’t quite figure out what was going on. While perusing the web for other ideas, I ran across Jason Bartholme’s blog entry about preventing SQL injection attacks. He has a simple bit of code that he put in onRequestStart() so check if the keyword DECLARE was in the URL.
<cfif not structIsEmpty(URL) >
<cfloop list="#StructKeyList(URL)#" index="i">
<cfif URL[i] CONTAINS "4445434C415245">
<cfmail to="me@mysite.com" from="them@theirsite.com" subject="SQL Injection Attempt" type="html">
<cfdump var="#URL#">
<cfdump var="#CGI#">
</cfmail>
<cfabort>
</cfif>
</cfloop>
</cfif>
This worked like a charm and allowed me to see what exactly these jerkoffs were doing. Turned out I had left CFQUERYPARAM out of some queries I was running for the Contact Us page and a few product display pages. Once I added the tags, the attacks stopped.
If you’re seeing SQL injection attacks, just add the code to application.cfm or the onRequestStart() function of application.cfc to see if this is the method the attackers are using and what they are doing.
Thanks Jason!


Hi Steve,
I’m glad the code is helping to prevent further attacks. It’s good to see others using it as well. You may also look into placing constraints on your varchar and text fields to not allow the string ‘<script’ to be inserted/updated. We believe that offers another layer of projection.
Just to clarify, this helps protect against a SPECIFIC sql injection attack that’s been going around, not every sql injection attack in general. That’s what cfqueryparam is for.
Thanks for the code post! It will definitely come in handy as an added layer of protection against this.
Yes, Eric, very good point. It’s simply one tool your should have in the arsenal!
Just knocked out a more expansive version of the IF statement to track a larger group of SQL commands in HEX and plain text:
<cfif URL[i] CONTAINS ‘4445434C415245′ OR URL[i] CONTAINS ‘
hmm… didn’t all fit above… one more try:
<cfif URL[i] CONTAINS ‘4445434C415245′
OR URL[i] CONTAINS ‘