CGI input: Filter dict.update() unwanted variables

G

Gnarlodious

In my last post I learned of the necessity of filtering CGI input, so
what I want to do is set a dict of allowable variable names:

allowedVariables = {'eeny':None, 'meeny':None, 'miny':None, 'mo':None}

# Set up a FieldStorage object:
import cgi
inputVariables = cgi.FieldStorage()
for name, value in {"eeny" : "value1", "meeny" : "value2", "miny" :
"value3", "mofo" : "value4"}.items():
inputVariables.list.append(cgi.MiniFieldStorage(name, value))

allowedVariables.update(((key, inputVariables[key].value) for key in
inputVariables))
allowedVariables

As you can see, the variable 'mofo' gets added to allowedVariables,
which is normal behavior. Is there an easy way to limit updates to
ONLY variables in the allowedVariables dict?

And in addition, maybe return an error so the attacker can be blocked?

-- Gnarlie
 
M

Miki Tebeka

Is there an easy way to limit updates to
ONLY variables in the allowedVariables dict?

allowedVariables = ['eeny', 'meeny', 'miny', 'mo']
form = cgi.FieldStorage()
safe_input = dict((key, form.getvalue(key)) for key in allowedVariables)
And in addition, maybe return an error so the attacker can be blocked?
You can check if there is a "non-allowed variable" and then return HTTP error.
if set(form) - set(allowedVariables):
print('Status: 406\n\n')
raise SystemExit()

HTH
 
C

Chris Angelico

You can check if there is a "non-allowed variable" and then return HTTP error.
if set(form) - set(allowedVariables):
   print('Status: 406\n\n')
   raise SystemExit()

I'd be disinclined to do this; ignore unrecognized query variables,
but don't throw back an error. Sometimes it's convenient to let the
browser send a "junk header" that the server will ignore - helps with
integration with other systems. As long as you can be sure that the
script won't do the wrong thing, it should be fine to have an extra
bit of GET/POST data.

ChrisA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top