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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.