On Mon, Feb 24, 2014 at 5:16 PM, Mike Miller <mbmiller+l at gmail.com> wrote:

> On Mon, 24 Feb 2014, Mike Miller wrote:
>
>  zip -r "$DIR".zip "$DIR" &>/dev/null
>>
>
> After all I wrote earlier, I forgot my zero option!  It should have been:
>
> zip -0r "$DIR".zip "$DIR" &>/dev/null


Some other language will give you better handling for query string
parameters and to safety check user inputs, but the script below might
work.

The most immediate danger that comes to mind is that a user might request
"../../../path/to/personal/files" and get whatever they want from your
server, all zipped up neatly.  Other dangers like shellcode could exist
too.

--
Michael



#!/bin/bash

# Usage: http://localhost/cgi-bin/zip.sh?path=selectedDir

# Base dir for all photos
BASEPATH="/fatty/Photos/2014"

# This is a simple way to split the query string. Thanks SO!
http://stackoverflow.com/questions/3919755/how-to-parse-query-string-from-a-bash-cgi-script
saveIFS=$IFS
IFS='=&'
param=($QUERY_STRING)
IFS=$saveIFS

# Grab the requested directory. Assume that it's value 1
DIR=${param[1]}

# Allowing a user to specify a path to zip and return to them is
# a huge security vulnerability. I doubt this solves the problem
# but it mitigates it slightly

REALPATH=$(readlink -m $BASEPATH/$DIR)

if [[ $BASEPATH =~ ^$REALPATH ]]
then
    # Someone requested a path that left the BASEPATH
    echo -e "Content-type: text/plain\n"
    echo "$REALPATH is not within the allowed path!"
    exit
fi

# Check if the requested directory exists
if [[ ! -d $REALPATH ]]
then
    echo -e "Content-type: text/plain\n"
    echo "The requested directory doesn't exist"
    exit
fi


# Make a temp file
TMPFILE=$(mktemp -u --suffix .zip)

# Change to the parent of the requested directory
cd $(dirname $REALPATH)


# Zip the requested directory into the temp file

zip -0 --quiet -r $TMPFILE $(basename $REALPATH)

# Bad exit from zip. Sad.
ZIPEXIT=$?
if [[ $ZIPEXIT -ne 0 ]]
then
    echo -e "Content-type: text/plain\n"
    echo "Zip had a problem ($ZIPEXIT). Sorry."
    exit
fi

# Get filesize
FILESIZE=$(wc -c $TMPFILE)

echo "Content-type: application/octet-stream"
echo "Content-Disposition: attachment; filename='mydownload.zip'"
echo "Content-Length: $FILESIZE"
echo ""

# Send it and remove it
cat $TMPFILE
rm $TMPFILE
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.mn-linux.org/pipermail/tclug-list/attachments/20140224/908b8562/attachment.html>