TweetFollow Us on Twitter

Enabling CGI Scripts

Volume Number: 19 (2003)
Issue Number: 9
Column Tag: Programming

Untangling the Web

Enabling CGI Scripts

by Kevin Hemenway

Prepare your server for more powerful dynamic capabilities

Last month, we started down the road of adding dynamic content to our web server with the use of Server Side Includes (SSI). Often regarded as "simple" compared to languages like Perl and PHP, they can provide some quick turnaround to minor features like small single-item databases, changing content based on user whim or URL, and so forth. Regardless of whether you plan on using SSIs or not, we laid some important groundwork with our understanding of how modules work, Apache's "block" configuration format, and a soft introduction to GET and POST.

All relatively Lego. Let's break out the Technix.

A Quick 'How do ya do?' To CGI

SSI's are built into Apache through the use of a module--when they're enabled, the web server handles the request of a resource, processes the SSI statements within, and then sends the final output back to the user. Since Apache is a web server and not a programming language, the capabilities of the built-in SSIs are minimal--they're not intended to be a full-fledged coding environment, and they never will be.

This is where CGI comes in. Meaning "Common Gateway Interface", it defines a way for a web server to interact with external programs: Apache handles the request, sends some relevant information to the requested resource, and trusts the resource to handle the rest (including sending back the final content). If the resource doesn't respond properly (either due to bad programming, incorrect permissions, etc.), Apache generates an error.

What does this really mean? Ultimately, it allows you to use any shell programming language to "do stuff" before showing the results to your visitors. Whether this means displaying content from a database, resetting passwords, saving a comment to a weblog, etc., as long as your program finishes properly, Apache doesn't give a darn.

Most commonly, these "CGI scripts" are written in Perl, but you can use PHP, C, Bash, Ruby, Python, and anything else you may be interested in. Likewise, you can use them all in tandem--you're not locked into any one programming language at any one time. Be forewarned, however: you are locked into security concerns: anything possible in your programming language of choice is doable within your CGI script, including deletion of files, exhaustion of memory, buffer overflows, poor security, and impolite use of resources. Add in the fact that all of these errors in judgment become publicly run-able by anyone who accesses your server, and you've got a whole mess of potential trouble.

Enabling The Gateway to Your Scripts

Learning about CGI follows my oft-repeated method of "search the httpd.conf for the feature you want". So, open up /etc/httpd/httpd.conf in your favorite text editor and search for the word "CGI"--our first two matches look vaguely familiar:

LoadModule cgi_module         libexec/httpd/mod_cgi.so
AddModule mod_cgi.c

If you recall from our previous articles, Apache contains most of its features broken up into modules--the equivalent of plugins. To enable a module, two lines must exist uncommented (not preceded by a # character) in the httpd.conf file, an AddModule and a LoadModule. As previously with SSI, so too with CGI: our two lines already exist, and are already enabled. Let's move on to our next search result, which is also similar to what we saw last month:

<Directory "/Library/WebServer/Documents">
    # This may also be "None", "All", or any combination of 
    # "Indexes", "Includes", "FollowSymLinks", "ExecCGI",   
    # or "MultiViews".
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

Whereas last article the above result was triggered by the word Includes, it's ExecCGI this time around. Unfortunately, explaining ExecCGI without some prior knowledge will cause a little bit of confusion, so let's skip ahead to our next few matches before we go much further. I've truncated them for relevance:

# ScriptAlias: This controls which directories
# contain server scripts. ScriptAliases are essentially
# the same as Aliases, except that documents in the 
# realname directory are treated as applications and
# run by the server when requested rather than as
# documents sent to the client. 
#
ScriptAlias /cgi-bin/ "/Library/WebServer/CGI-Executables/"
# "/Library/WebServer/CGI-Executables" should be changed
# to whatever your ScriptAliased CGI directory exists,
# if you have that configured.
#
<Directory "/Library/WebServer/CGI-Executables">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

The most common CGI configuration is all about segregation: "only files in this directory should be executed as programs--everything else, anywhere else, are just plain old files that should be processed normally." From the standpoint of an overbearing system administrator, this makes sense. With only one directory that can execute code unconditionally, and only one person (you) who can put programs there, it can bring a little sanity to your day-to-day security paranoia.

This is how Apache is configured by default, and the above httpd.conf snippet shows these settings. Our first directive, ScriptAlias, lets us pick and choose which directory we'd like CGI scripts to live in. Anything within that directory, CGI script or not, will be executed by the web server as if it were a program. If something goes wrong, Apache will return an "Internal Server Error" to the requesting user-agent (ie. your visitor's browser).

ScriptAlias consists of two space-separated parts: the fake name and the real name. The fake name, /cgi-bin/, defines what URL will be used to access the real name, /Library/WebServer/CGI-Executables/. In the currently configured settings, whenever we access a URL like http://127.0.0.1/cgi-bin/printenv, we'll really be accessing the matching file stored at /Library/WebServer/CGI-Executables/printenv.

The second part of our configuration is a block directive focusing on that specific location of our hard drive. It merely ensures that said directory has no special privileges besides that ScriptAlias: it can't override anything in the Apache configuration (AllowOverride None), and there are no special capabilities (Options None) associated with it.

At this point, if you only care about the directory segregation of CGI, you can skip over to our next subheading, "Let's See One of These CGI Thingies In Action!" If, on the other hand, you'd like to hear me get high-and-mighty over the "right" way of doing things, read on.

CGI EVERYWHERE: "A Brilliant Psychological Thriller!"

In the very first "Untangling the Web", I professed a fondness and desire to teach you the "right" way to create URLs (MacTech Magazine, June 2003, "Untangling The Web", "Familiarity That Breeds An Uh-Oh!"). A good URL will remain in existence until the dusk of time, never needing to be changed, never needing to be refactored. It's not a snap-decision: if you find yourself changing your URLs around, you designed your site poorly (from an engineering, not visual, standpoint).

One of the maxims, which I'll reiterate here, is that "Your URLs Should Not Reveal Your Technical Capabilities". This has absolutely nothing to do with the oft-maligned "security through obscurity"--the belief that hiding information makes you less susceptible to risk. Instead, removing the technicalities of your URL will allow your site to grow with your needs.

Consider the default configuration of CGI: anytime you want to add some dynamic functionality to your site (with Perl, Python, etc.), you've got to stick your script in a directory and point to it with a URL like http://127.0.0.1/cgi-bin/add_user.pl (where .pl denotes a Perl script) or http://127.0.0.1/cgi-bin/del_user.py (.py denoting Python). What happens, though, when you no longer need CGI scripts, but have moved to an embedded language like PHP? Suddenly, all of your pages that point to that ugly /cgi-bin/ URL are broken, useless, and inaccurate. You find yourself refactoring pages to point to new locations.

The solution? Remove /cgi-bin/ and the file extension from the URL. By clearing this needless technical cruft, you get stronger addresses with less need for change. http://127.0.0.1/admin/add_user and http://127.0.0.1/admin/del_user contain no indication of the technology behind them, merely their purpose in the grande scheme of things.

We're already halfway through removing /cgi-bin/ from our URLs (file extensions I keep putting off, but I'll get to 'em eventually, I promise!). Our very first match for our "CGI" search was for an ExecCGI addition to the Options line of our root web directory (/Library/WebServer/Documents/). ExecCGI works similarly to Includes, which helped get our SSIs running last month. By adding it to the Options line of any Directory we, like SSIs, are telling Apache to allow CGI scripts at that location:

Options Indexes FollowSymLinks MultiViews ExecCGI

To make the comparison even more apt, there's one other thing we need to do before we can use CGIs wherever we need them: we need to add a handler that says "Apache! Listen up! Whenever we request a file with this extension, we want you to treat it as an executable program!" This handler was also needed last month--we told Apache that anytime it ran across a file with an shtml extension, it should process it for SSIs statements.

Thankfully, there's not much brainwork involved here, as our final relevant search match for "CGI" brings us to the below. Simply uncomment the AddHandler (by removing the #), restart Apache (sudo apachectl restart in your Terminal) and you're ready to go:

# If you want to use server side includes, or CGI outside
# ScriptAliased directories, uncomment the following lines.
#
# To use CGI scripts:
#
#AddHandler cgi-script .cgi

Two caveats that may be running through head: "what about the cgi extension?" and "what about that security brouhaha you cautioned us about?" Concerning the file extension, yes, we're swapping /cgi-bin/ for cgi, but this will never be an issue once we remove the need for them in our URLs. As for security, there's not much I can say besides "be careful"--you'll no longer have the niceties of a single and central directory for your code execution, so double and triple check the scripts you'll be programming or using. I'll talk a little more about script security in next month's column.

Let's See One of These CGI Thingies In Action!

Browse to your /Library/WebServer/CGI-Executables/ directory, the default location that Apache has been configured for CGI scripts. You should see two files, printenv and test-cgi, there already. These are some default Apache CGI scripts that will help you quickly test if things are a-ok. Since CGI was already pre-configured in the httpd.conf, we should be able to just load one of these files in the browser and see some fireworks, right? Load http://127.0.0.1/cgi-bin/test-cgi, and we'll receive the response in Figure 1.


Figure 1: An error after loading our test-cgi, but why?

If CGI scripts were already configured, why this rather rude error message? Let's check Apache's error_log, which will always contain some sort of light bulb enlightening response. After running tail /var/log/httpd/error_log on the command line, we'll see something similar to the below as the last line of output:

[Sun Aug 17 10:41:16 2003] [error] [client 127.0.0.1] file 
permissions deny server execution: /Library/WebServer/CGI-
Executables/test-cgi

This is one of the more common errors you'll experience with CGI scripts: the test-cgi file doesn't have the proper credentials to be considered an executable program. I won't get into the vagaries of file ownership or permissions, but follow through the bolded commands below to give both of the default CGI files "execute" access for all users:

> cd /Library/WebServer/CGI-Executables/
> ls -l
total 24
-rw-r--r--  1 root  admin  5398 Jul 27  2002 printenv
-rw-r--r--  1 root  admin   757 Jul 27  2002 test-cgi
> sudo chmod 755 *
Password: **********
> ls -l
total 24
-rwxr-xr-x  1 root  admin  5398 Jul 27  2002 printenv
-rwxr-xr-x  1 root  admin   757 Jul 27  2002 test-cgi

Now, let's try our URL again. Figure 2 shows our new output:


Figure 2: The correct output of our test-cgi script.

Figure 3 shows the output from the other script, http://127.0.0.1/cgi-bin/printenv:


Figure 3: Similar output from the default printenv script.

If you followed the instructions under the "CGI EVERYWHERE!" subheading, you can also move either of the printenv or test-cgi scripts out of their current location and stick them in /Library/WebServer/Documents/ with a cgi file extension. Once you do so, you should then be able to run them under the non-/cgi-bin/ URL and receive the same output (if not, what's your first course of action? Check the error_log!).

Assuming you get similar output as Figures 2 and 3, what does all this gibberish mean? What exactly did we just do? Both scripts show a number of environment variables, which is just a fancy term for data that exists "invisibly" and floats around waiting to be used or read. Some of the variables were set by the browser (like HTTP_USER_AGENT), and some have been set by the server (like SERVER_PROTOCOL). When I first introduced CGI, I mentioned that Apache "sends some relevant information to the requested resource". This "relevant information" is stored in environment variables.

Environment variables can exist outside of your web server too. For instance, if you run printenv in your Terminal, you'll see a listing of variables similar to Figure 4:


Figure 4: Environment variables in your Terminal.

Believe it or not, we've dealt with environment variables already in this series. In our article on Server Side Includes, we checked the $QUERY_STRING variable to see which quote should be displayed at the user's request. If you check back to Figure 3, you'll see an environment variable named QUERY_STRING, which is currently empty. Try adding ?q02 to the end of our URL (http://127.0.0.1/cgi-bin/printenv?q02), and see how that changes the output (Figure 5):


Figure 5: Our QUERY_STRING now has a value.

With the above two scripts working correctly, our CGI capabilities are ready for use.

Homework Malignments

In our next column, we'll chat further about CGI: how to begin creating our own, the most common errors during development and deployment, security issues we should be aware of, and how to find the "good ones" from the immense ocean of crap. If we have time, we'll show you how to install a few that have stood the test of time. For now, students may contact the teacher at morbus@disobey.com.

  • Take a look inside printenv and test-cgi in a text editor.

  • View the printenv script from various browsers and machines. Determine how the output changes, and see if you can figure out what each setting actually means.

  • Forgive me for not including anything amusing in this article.


Kevin Hemenway, coauthor of Mac OS X Hacks, is better known as Morbus Iff, the creator of disobey.com, which bills itself as "content for the discontented." Publisher and developer of more home cooking than you could ever imagine (like the popular open-sourced aggregator AmphetaDesk, the best-kept gaming secret Gamegrene.com, articles for Apple's Internet Developer and the O'Reilly Network, etc.), he's been spending the last two months listening to every song in his iTunes library twice. Contact him at morbus@disobey.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Jump into one of Volkswagen's most...
We spoke about PUBG Mobile yesterday and their Esports development, so it is a little early to revisit them, but we have to because this is just too amusing. Someone needs to tell Krafton that PUBG Mobile is a massive title because out of all the... | Read more »
PUBG Mobile will be releasing more ways...
The emergence of Esports is perhaps one of the best things to happen in gaming. It shows our little hobby can be a serious thing, gets more people intrigued, and allows players to use their skills to earn money. And on that last point, PUBG Mobile... | Read more »
Genshin Impact 5.1 launches October 9th...
If you played version 5.0 of Genshin Impact, you would probably be a bit bummed by the lack of a Pyro version of the Traveller. Well, annoyingly HoYo has stopped short of officially announcing them in 5.1 outside a possible sighting in livestream... | Read more »
A Phoenix from the Ashes – The TouchArca...
Hello! We are still in a transitional phase of moving the podcast entirely to our Patreon, but in the meantime the only way we can get the show’s feed pushed out to where it needs to go is to post it to the website. However, the wheels are in motion... | Read more »
Race with the power of the gods as KartR...
I have mentioned it before, somewhere in the aether, but I love mythology. Primarily Norse, but I will take whatever you have. Recently KartRider Rush+ took on the Arthurian legends, a great piece of British mythology, and now they have moved on... | Read more »
Tackle some terrifying bosses in a new g...
Blue Archive has recently released its latest update, packed with quite an arsenal of content. Named Rowdy and Cheery, you will take part in an all-new game mode, recruit two new students, and follow the team's adventures in Hyakkiyako. [Read... | Read more »
Embrace a peaceful life in Middle-Earth...
The Lord of the Rings series shows us what happens to enterprising Hobbits such as Frodo, Bilbo, Sam, Merry and Pippin if they don’t stay in their lane and decide to leave the Shire. It looks bloody dangerous, which is why September 23rd is an... | Read more »
Athena Crisis launches on all platforms...
Athena Crisis is a game I have been following during its development, and not just because of its brilliant marketing genius of letting you play a level on the webpage. Well for me, and I assume many of you, the wait is over as Athena Crisis has... | Read more »
Victrix Pro BFG Tekken 8 Rage Art Editio...
For our last full controller review on TouchArcade, I’ve been using the Victrix Pro BFG Tekken 8 Rage Art Edition for PC and PlayStation across my Steam Deck, PS5, and PS4 Pro for over a month now. | Read more »
Matchday Champions celebrates early acce...
Since colossally shooting themselves in the foot with a bazooka and fumbling their deal with EA Sports, FIFA is no doubt scrambling for other games to plaster its name on to cover the financial blackhole they made themselves. Enter Matchday, with... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra available today at Apple fo...
Apple has several Certified Refurbished Apple Watch Ultra models available in their online store for $589, or $210 off original MSRP. Each Watch includes Apple’s standard one-year warranty, a new... Read more
Amazon is offering coupons worth up to $109 o...
Amazon is offering clippable coupons worth up to $109 off MSRP on certain Silver and Blue M3-powered 24″ iMacs, each including free shipping. With the coupons, these iMacs are $150-$200 off Apple’s... Read more
Amazon is offering coupons to take up to $50...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for up to $110 off MSRP, each including free delivery. Prices are valid after free coupons available on each mini’s product page, detailed... Read more
Use your Education discount to take up to $10...
Need a new Apple iPad? If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $100 off the... Read more
Apple has 15-inch M2 MacBook Airs available f...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
Mac Studio with M2 Max CPU on sale for $1749,...
B&H Photo has the standard-configuration Mac Studio model with Apple’s M2 Max CPU in stock today and on sale for $250 off MSRP, now $1749 (12-Core CPU and 32GB RAM/512GB SSD). B&H offers... Read more
Save up to $260 on a 15-inch M3 MacBook Pro w...
Apple has Certified Refurbished 15″ M3 MacBook Airs in stock today starting at only $1099 and ranging up to $260 off MSRP. These are the cheapest M3-powered 15″ MacBook Airs for sale today at Apple.... Read more
Apple has 16-inch M3 Pro MacBook Pro in stock...
Apple has a full line of 16″ M3 Pro MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $440 off MSRP. Each model features a new outer case, shipping is free, and an... Read more
Apple M2 Mac minis on sale for $120-$200 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $110-$200 off MSRP this weekend, each including free delivery: – Mac mini M2/256GB SSD: $469, save $130 – Mac mini M2/512GB SSD: $689.... Read more
Clearance 9th-generation iPads are in stock t...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on clearance sale for starting at only $199 on their online store for a limited time. Sale prices for online orders only, in-store prices may vary... Read more

Jobs Board

Senior Mobile Engineer-Android/ *Apple* - Ge...
…Trust/Other Required:** NACI (T1) **Job Family:** Systems Engineering **Skills:** Apple Devices,Device Management,Mobile Device Management (MDM) **Experience:** 10 + Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Full Time (80 hrs/pay period) Evenings General Summary Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.