Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python CGIHTTPServer crashes with "OSError: [Errno 13] Permission denied"

Tags:

python

linux

cgi

I am running the following command from my home directory:

python -m CGIHTTPServer

This runs the server, but when I try to access a script in the cgi-bin directory I get:

Traceback (most recent call last):
  File "/usr/lib/python2.7/CGIHTTPServer.py", line 251, in run_cgi
    os.execve(scriptfile, args, env)
OSError: [Errno 13] Permission denied

Running as root does not make a difference. The files seem to have all the right permissions:

student@bandersnatch:~$ ls -lhR
.:
total 12K
drwxr-xr-x 2 student student 4.0K Jun 13 18:38 cgi-bin
drwxr--r-- 2 student student 4.0K Jun 10  2004 kalpy
-rwxrwxrwx 1 student student 2.0K Jun 13 12:37 test.html

./cgi-bin:
total 8.0K
-rwxr-xr-x 1 student student 31 Jun 13 18:38 test.py

Edit: The content of test.py is:

#!/usr/bin/python
print "test"

The shebang is valid:

~$ which python
/usr/bin/python
like image 337
qwertyboy Avatar asked Jun 13 '12 18:06

qwertyboy


3 Answers

Are you, by any chance, running the process as root?

If you use the source, you will see in CGIHTTPServer.py, just before calling execve:

try:
    os.setuid(nobody)
except os.error:
    pass

That is, it will run the CGI script as nobody, if it is able to change the UID, that is if it is root. If it is not root, this call will most likely fail, and pass on.

So my guess is that you are running the server as root, so the script is run as nobody, but this user doesn't have access to the script. Which is expected, as you say that it is in your home dir.

Two solutions that I can think of:

  • The recommended: do not run the server as root!
  • The workaround: copy the script to a directory where nobody can read it (/tmp for example).
like image 90
rodrigo Avatar answered Nov 13 '22 11:11

rodrigo


Personally, unless there's some reason I'm unaware of, I'd recommend using subprocess.Popen instead of os.execve. I have run into Errno 13 before, trying to start a .app with Popen(['open execName.app']). I had to use Popen(['execName.app/Contents/MacOS/execName', 'arg1', 'arg2'...]) instead. Don't know if that helps, but give it a shot.

like image 1
DaveTheScientist Avatar answered Nov 13 '22 10:11

DaveTheScientist


I ran into the same problem from ubuntu Linux. Followed the solution by "Mike", with modification. Instead doing chmod of the "/usr" which has several folders, change the permissions of the folder containing executable file that was denied. (you can check that server would run fine when loading a static html file in the same location, and shows error only when script is run).

cd /pathto/folder/with/deniedscript
sudo chmod -R 755 ./

Now the script has permission, so should run fine. Note that -R gives the permission to all files in this folder(and subfolders if any).

like image 1
Malaya Avatar answered Nov 13 '22 09:11

Malaya