Writing secure CGI scripts

Any time that a program is interacting with a networked client, there is the
possibility of that client attacking the program to gain unauthorized access.
Even the most innocent looking script can be very dangerous to the integrity of
your system.

With that in mind, we would like to present a few guidelines to making sure
your program does not come under attack.

-------------------------------------------------------------------------------

   *  Beware the eval statement

     Languages like PERL and the Bourne shell provide an eval command which
     allow you to construct a string and have the interpreter execute that
     string. This can be very dangerous. Observe the following statement in the
     Bourne shell:

     eval `echo $QUERY_STRING | awk 'BEGIN{RS="&"} {printf "QS_%s\n",$1}' `

     This clever little snippet takes the query string, and convents it into a
     set of variable set commands. Unfortunately, this script can be attacked
     by sending it a query string which starts with a ;. See what I mean about
     innocent-looking scripts being dangerous?

   *  Do not trust the client to do anything

     A well-behaved client will escape any characters which have special
     meaning to the Bourne shell in a query string and thus avoid problems with
     your script misinterpreting the characters. A mischevious client may use
     special characters to confuse your script and gain unauthorized access.

   *  Be careful with popen and system.

     If you use any data from the client to construct a command line for a call
     to popen() or system(), be sure to place backslashes before any characters
     that have special meaning to the Bourne shell before calling the function.
     This can be achieved easily with a short C function.

   *  Turn off server-side includes

     If your server is unfortunate enough to support server-side includes, turn
     them off for your script directories!!!. The server-side includes can be
     abused by clients which prey on scripts which directly output things they
     have been sent.

-------------------------------------------------------------------------------
Rob McCool robm@ncsa.uiuc.edu
