To all web programmers on El Reg
Please include the following simple lines of code at the start of your CGI scripts (PHP will be similar):
for $key ( $cgi->param() )
{
$input{$key} = $cgi->param($key);
$apos = q{#}; $quot = q{"}; $opren = q{(}; $cpren = q{)}; $intr = q{?}; $astr = q{*}; $lt = q{<}; $gt = q{>}; $amp = q{&}; $eq = q{=}; $semi = q{;};
$input{$key} =~ s/\'/$apos/g; $input{$key} =~ s/\"/$quot/g; $input{$key} =~ s/\(/$opren/g; $input{$key} =~ s/\)/$cpren/g; $input{$key} =~ s/\?/$intr/g;
$input{$key} =~ s/\*/$astr/g; $input{$key} =~ s/\</$lt/g; $input{$key} =~ s/\>/$gt/g; $input{$key} =~ s/\&/$amp/g; $input{$key} =~ s/\=/$eq/g; $input{$key} =~ s/\;/$semi/g;
if (($input{$key} ~= /DELETE\s+FROM/i) || ($input{$key} ~= /SELECT\s+\D+\s+FROM/i) || ($input{$key} =~ /UPDATE\s+TABLE/i) || ($input{$key} =~ /INSERT\s+INTO/i) || ($input{$key} =~ /TRUNCATE\s+TABLE/i))
{
$input{$key} = q{};
}
}
Now use only the %input hash for processing your input parameters. This code snippet escapes all the HTML, Javascript and SQL control and delimiter characters, rendering any attempted code injection into garbage that will merely display as literal text instead of executing on your server or in the viewer's browser. Further, any direct SQL commands submitted as input that modify the database are detected and erased. More subtle SQL injection (eg ' OR 1 = 1) used to bypass login authentication breaks because characters like the apostrophe and equals sign are escaped, causing an SQL error. And Javascript will break both because a) the HTML script tags required to embed it are escaped, and b) the end-of-line semicolons required in Javascript are also escaped.
It's not rocket science, and it doesn't require a million-dollar security solution. Always parse your input before exposing your database to it, that's all. The above code does exactly that, and you can have it for free! :)