Subject: Writing safe shell script CGIs (slightly OT)
To: None <netbsd-help@netbsd.org>
From: Amadeus Stevenson <amadeus.stevenson@gmail.com>
List: netbsd-help
Date: 06/09/2006 01:31:05
Hi guys,
Sorry if this isn't the place to post.
I was wondering how to ensure safe shell-script CGI execution?
I'm running thttpd in chroot/netbsd-3.0:
gateway# pwd
/var/www
gateway# ls -al */*
-r-xr-xr-x 1 www www 10550 Jun 9 00:02 bin/cat
-r-xr-xr-x 1 www www 191533 Jun 9 00:05 bin/ksh
-r-xr-xr-x 1 www www 25595 Jun 9 00:49 bin/sed
-rw-r--r-- 1 www www 53 Jun 9 01:10 etc/rdr_default
-rw-r--r-- 1 www www 1403 Jun 9 00:03 http_docs/index.html
-rw-r--r-- 1 www www 2605 Jun 9 00:04 http_docs/style.css
-r--r--r-- 1 www www 882054 Jun 9 00:43 lib/libc.so.12
-r-xr-xr-x 1 www www 56251 Jun 9 00:39 libexec/ld.elf_so
-rw-r--r-- 1 www www 42270 Jun 9 01:20 log/thttpd.log
http_docs/cgi-bin:
total 8
drwxr-xr-x 2 www www 512 Jun 9 01:03 .
drwxr-xr-x 4 www www 512 Jun 9 00:04 ..
-rw-r--r-- 1 www www 74 Jun 9 01:04 index.html
-rwxr-xr-x 1 www www 326 Jun 9 01:19 redirect.cgi
usr/lib:
total 110
drwxr-xr-x 2 www www 512 Jun 9 00:55 .
drwxr-xr-x 4 www www 512 Jun 9 01:20 ..
lrwxr-xr-x 1 www www 15 Jun 9 00:55 libc.so.12 -> /lib/libc.so.12
-r--r--r-- 1 www www 106591 Jun 9 00:41 libedit.so.2
usr/libexec:
total 60
drwxr-xr-x 2 www www 512 Jun 9 00:52 .
drwxr-xr-x 4 www www 512 Jun 9 01:20 ..
-r-xr-xr-x 1 www www 56251 Jun 9 00:52 ld.elf_so
With
gateway# cat redirect.cgi
#!/bin/ksh
echo "Content-type: text/html"
echo
if [[ -n "$1" && -e "/etc/rdr_$1" ]]; then
cat=$1
else
cat=default
fi
set -A urls `cat "/etc/rdr_$cat" | sed -e 's/\n/ /g'`
num_urls=${#urls[*]}
echo -n '<html><head><meta http-equiv="refresh" content="0,url='
echo -n ${urls[$((RANDOM%num_urls))]}
echo '"></head></html>'
gateway#
The redirect.cgi basically pulls an array of new-line separated URLs
and picks a random one before generating a http meta refresh page.
Nothing's "fool-proof" but to what extent is this "hacker safe"?
I don't really understand the use of "trap" in CGI shell scripts - to
what level can they be useful here?
Is there anything I can do to make this safer? Ie. stop potential
shell code execution?
Thanks
Amadeus
ps. when setting up chroot environment I had to pretty much `strings`
the binaries to find static libraries and copy them. Is there an
easier way of doing this?