Next: CGI Environmental Variables
Up: CGI (Common Gateway Interface):
Previous: Introduction to CGI
  Contents
If you write a CGI script that accepts information from the outside world, and then
uses that information to access another program (through, for example the system
function of the os module), it's very important to make sure that you don't
inadvertently send a malicious command to the operating system. There are two things
that will minimize the risk of this happening. First, make sure that your CGI program
has access to only the minimum set of programs it needs by using a very simple command
path; on unix, a line like the following in your CGI script will serve this purpose.
os.environ['PATH'] = '/bin:/usr/bin'
Secondly, you should insure that any variables which are transmitted to your program and
will be used as part of an operating system command do not contain any special characters;
that is, they are composed of letters, digits and the underscore only. Regular expressions
(Section 8.5) can be used to test this. For example, the following function
ensures that any word passed to it contains no special characters:
def chkname(name,extra=''):
valid = r'\w'
if extra:
valid = r'[' + valid + extra + r']'
if re.match(r'^%s+$' % valid,name):
return 1
else return 2
To accommodate common email addresses, extra='@.' could be passed to
chkname
Next: CGI Environmental Variables
Up: CGI (Common Gateway Interface):
Previous: Introduction to CGI
  Contents
Phil Spector
2003-11-12