Select your language

CGI (Common Gateway Interface) allows you to run scripts in random programming languages on a server which can feed data to your homepages. The previous article showed you how to  set-up Apache server. Now will you learn how to enable the execution of CGI scripts in a few steps and which rules you should obey to run them safely.

Allow CGI scripts on Apache 2

To execute them you need to start with allowing Apoache to run these scripts at first. Plus you need to define a standard path where the scripts are located. We can do both by editing the config file below 

sudo nano /etc/apache2/sites-enabled/000-default.conf

Add the lines below and save the file.

You can use any other directory if you don't like /usr/lib/cgi-bin. You can run scripts in any language but you need to tell Apache which you want to use. That is done in the line AddHandler. Since I am running Python scripts only that list is short and consists only of .py.

After a restart is the system ready to run CGI scripts.

sudo service apache2 restart

Run a first script

The first script is a little hello world example. Start with creating a file with the name test.py in the previously defined folder for the scripts.

sudo nano /usr/lib/cgi-bin/test.py

The script itself looks like that.

#!/usr/bin/env python

print('Content-type: text/html\n')
print('Hello world')

Now you have to manage rights for that file. A solid standard would be to give the user root all rights, the users can read and execute and all others can only execute the script. That is done with the following line.

sudo chmod 755  /usr/lib/cgi-bin/test.py

Check the success of the rights change by the command

sudo ls -al  /usr/lib/cgi-bin/test.py

Seems like it worked. 

The result can be seen in a browser of your choice.

Safe handling of CGI scripts

CGI scripts are just a piece of software. And like all software can they mess massively with your system.

User rights

Always make sure that the script has no more than the 755 pattern of user rights. If you grant more rights everybody who can logon to your system could change your script and hijack it.

User input

If you have a script that takes user input from a homepage and processes it, you need to check carefully that the input does only contain input you expect and does not contain e.g. executable commands. That could easily damage your databases or similar.

Passwords and User names

Never ever store a password or user name in a script.