Ask Ben: Protecting Database Table Names In ColdFusion CFQuery

<!--- Param the table name in the FORM scope. --->
<cfparam
	name="FORM.table"
	type="string"
	default=""
	/>
 
 
<!---
	Before we even check anything, let's clean characters
	out of the table name that we KNOW cannot be valid.
	Things like single quotes and semi colons might be a
	sign of a SQL injection attack. Let's strip out anything
	that is not standard.
--->
<cfset FORM.table = FORM.table.ReplaceAll(
	"[^\w\-_]+",
	""
	) />
 
<!---
	Passing in a database Table as a variable is VERY
	risky because it leaves you open to all kinds of
	malicious attacks and tomfoolery. Therefore, we
	have to be ultra careful about how we handle this.
	Make sure that the table is a valid table and
	only allow table names that are in the following list.
--->
<cfsavecontent variable="strTableList">
	address
	contact
	phone
	notes
</cfsavecontent>
 
<!---
	Check to see if the table is valid. Tread the space,
	tab, line break, and carriage return all as list
	delimiters - this just makes the list easier to read.
	Also, do NOT use NOCASE search. Let proper name
	case be yet another layer of security.
--->
<cfif ListFind(
	strTableList,
	FORM.table,
	" #Chr( 9 )##Chr( 13 )##Chr( 10 )#"
	)>
 
	<!---
		Get the record count for the given table. When
		putting in the table name, be sure to use the []
		notation so that we do not get any invalid table
		name exceptions.
	--->
	<cfquery name="qTable" datasource="#REQUEST.DSN.Source#">
		SELECT
			COUNT( * ) AS count
		FROM
			[#FORM.table#]
	</cfquery>
 
 
	<!--- Output record count. --->
	<p>
		Records in #FORM.table#: #qTable.count#
	</p>
 
<cfelse>
 
	<!---
		A valid table name was NOT found. Throw an error
		or handle in some other way.
	--->
	<cfthrow
		type="TableNotFoundException"
		message="The table [#FORM.table#] is not valid"
		/>
 
</cfif>

For Cut-and-Paste