简体   繁体   中英

Cgi-bin script to cat a file owned by a user

I'm using Ubuntu server and I have a cgi-bin script doing the following . . .

#!/bin/bash
echo Content-type: text/plain
echo ""
cat /home/user/.program/logs/file.log | tail -400  | col -b > /tmp/o.txt
cat /tmp/o.txt

Now if I run this script with I am "su" the script fills o.txt and then the host.com/cgi-bin/script runs but only shows up to the point I last ran it from the CLI

My apache error log is showing "permission denied" errors. So I know the user apache is running under somehow cannot cat this file. I tried using chown to no avail. Since this file is in a user directory, what is the best way to either duplicate it or symbolic link it or what?

I even considered running the script as root in a crontab to sort of "update" the file in /tmp/ but that did not work for me. How would somebody experienced with cgi-bin handle access to a file in a users directory?

The Apache user www-data does not have write access to a temporary file owned by another user.

But in this particular case, no temporary file is required.

tail -n 400 logfile | col -b

However, if Apache is running in a restricted chroot , it also has no access to /home .

The log file needs to be chmod o+r and all directories leading down to it should be chmod o+x . Make sure you understand the implications of this! If the user has a reason to want to prevent access to an intermediate directory, having read access to the file itself will not suffice. (Making something have www-data as its group owner is possible in theory, but impractical and pointless, as anybody who finds the CGI script will have access to the file anyway.)

More generally, if you do need a temporary file, the simple fix (not even workaround) is to generate a unique temporary file name, and remove it afterwards.

temp=$(mktemp -t cgi.XXXXXXXX) || exit $?
trap 'rm -f "$temp"' 0
trap 'exit 127' 1 2 15

tail -n 400 logfile | col -b >"$temp"

The first trap makes sure the file is removed when the script terminates. The second makes sure the first trap runs if the script is interrupted or killed.

I would be inclined to change the program that creates the log in the first place and write it to some place visible to Apache - maybe through symbolic links.

For example:

ln -s /var/www/cgi-bin/logs /home/user/.program/logs

So your program continues to write to /home/user/.program/logs but the data actually lands in /var/www/cgi-bin/logs where Apache can read it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM