[Tutor] Untainting CGI parameters

Kent Johnson kent37 at tds.net
Wed Aug 10 18:32:38 CEST 2005

Jan Eden wrote:
> Hi,
> I would like to untaint all parameters with which my CGI script is called. Example:
> if parameters.has_key('type'):
>     match = re.search('\w+', parameters['type'].value)
>     type = match.group()
> else: type = 'page'

OK, I don't know much Perl but I don't think these two snippets do the same thing. For one thing the regexes are different, second in the Python you need to check if the match succeeds. I would write it as

type = 'page'
if parameters.has_key('type'):
    match = re.search('^\w+$', parameters['type'].value)
    if match:
        type = match.group()

or maybe
    match = re.search('^\w+$', parameters['type'].value)
    type = match.group()
except KeyError, AttributeError:
    type = 'page'

> In Perl, I used the ternary operator to write it like this:
> my $type = ($parameters{type} && ($parameters{type} =~ /^(\w+)$/)) ? $1 : 'page';
> While this is not the most beautiful code to look at, I have a
> weakness for compact programs - so can I shorten the Python
> equivalent somehow?

mmm, not sure how to do that...Python doesn't put such a premium on compactness. If you have to do it a lot just put it in a function and call that...


More information about the Tutor mailing list