Skip to content
Advertisement

How to ban all executable files on Apache

I would like to find out the most effective way to ban any executable files from one specific sub folder on my server. I allow file uploads by users into that folder, and would like to make that folder accessible from the web. I have the root folder pretty much locked down with mod_rewrite. In that one unprotected sub-folder I have .htaccess with:

Options +Indexes  
IndexOptions +FancyIndexing +FoldersFirst +HTMLTable  
RewriteEngine off

I know it is best to just restrict file uploads to a certain allowable file types, and I am already doing this in php. I am checking file extension, and mime type before allowing an upload like this:

$allmime=array('image/gif', 'image/png', 'image/jpeg', 'application/msword', 'application/pdf');
$allext=array('png', 'jpg', 'gif', 'doc', 'pdf');
$path=pathinfo($_FILES['file']['name']);
$mime=trim(shell_exec("file -bi " . $_FILES['file']['tmp_name']));
if( !in_array( $path['extension'], $allext) || !in_array($mime, $allmime) ){
    //ban
}else{
    //allow
}

However I am not certain if there is some convoluted hack out there that will still allow a shell script to be uploaded and executed on the server, since all of the successfully uploaded files will be visible immediately.

I know there is another option in .htaccess to filter out files like this:

<FilesMatch ".(sh|asp|cgi|php|php3|ph3|php4|ph4|php5|ph5|phtm|phtml)$">
    order allow, deny
    deny from all
</FilesMatch>

However I am not certain that this list is all-inclusive, plus this is hard to maintain, as new extensions might be installed in the future.

To sum it all up: Anyone knows a good way to disallow all server executables, with the exception of php scripts directly executed by the %{HTTP_HOST}?

Advertisement

Answer

How about disabling the server-side handlers for that specific directory? Something like:

<Directory /path/to/restrict>
    SetHandler None
    Options None
    AllowOverride None
</Directory>

This is untested, but seems like it might work.

UPDATE: Apparently, I was wrong … but sticking AddHandler default-handler in an .htaccess does seem to work.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement