110 points · by jamescun · 15y ago · 70 comments
<Directory /var/www/website>
# Only execute /index.php and no other PHP files
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} .php$
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule ^(.*)$ not_happening [L,F]
</Directory>
# Remove other file types from PHP execution
RemoveHandler .phtml .php3
This way attackers can upload whatever PHP file they want but they can't execute it though an Apache request.What if the attacker names their trojan "index.php"? Doesn't matter, only top-level index.php of the site can be executed.
I mean, I'm trying to imagine another web application language where "attackers can upload whatever (X) file they want" is even a valid case, ever. I mean, imagine a war file being wholesale replaced-- it isn't possible without going out of your way to misconfigure your app server. This, I think, is the base problem with PHP; the default configuration is predicated upon content and code not being segregated at all, and hot redeploy is the norm, without any notification to the admin that it's actually happening.
Unfortunately, a lot of people who use PHP are stuck with third-party apps with questionable security records, such as WordPress. If you want to have anything resembling security in such an environment, you need to resort to band-aid solutions such as disabling functions. It's far from optimal, I admit, but at least it helps reduce damages if (or rather, when) the third-party app gets hacked.
This may inherently be due to PHP's age. As an early dynamic language, it could be expected that the earliest shared source code and tutorials would likely contain bugs.
Unfortunately, a lot of recent PHP tutorials published in seemingly up-to-date websites also contain WTF code. Case in point: this tutorial [1] showed up on reddit a couple of days ago.
[1] http://www.anil2u.info/2011/06/object-oriented-programming-i...
Nowadays, I view any PHP code outside of Stack Overflow and Github with the utmost suspicion.
server
{
server_name domainname.com;
root /srv/sites/domainname.com/httpdocs;
index index.php;
access_log /srv/sites/domainname.com/logs/access.log main;
error_log /srv/sites/domainname.com/logs/error.log info;
try_files $uri $uri/ /index.php?$query_string;
location ~ \.php$
{
try_files $uri $uri/ /index.php?$query_string =403;
include /usr/local/nginx/conf/fastcgi_params;
fastcgi_pass phpfpm;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
} .php3 .php4 .php5
.ph3 .ph4
.php3p
.phtWhat about apps that don't limit themself to just index.php?
I never understood this obsession with having everything flow through index.php. Apache already has a method to dispatch requests to the proper controller AKA file. Why rewrite it again?
This is fictional security. If someone can upload a file, they can also upload index.php (and from my experience cleaning up a few hacks, that is exactly what they do).
And if you (correctly) set it so they can't write to the top level directory, what you really should do is remove the php handler from the directories they can write to.
The front controller pattern doesn't have much to do with security, though. It also doesn't work with apps like WordPress.
Then if you need to make a change you are still only changing it one spot.
The problem with removing the PHP handler from all other writable directories is the reality of dealing with many 3rd party modules, themes, and apps that have their own upload directories, and sure you can audit all 3rd party code and rewrite it yourself, but you should also assume the code is full of holes anyway and configure the other layers in your stack according to the principle of least privilege.
How? Is there a way to let Apache, for every request to host.domain.com execute /var/www/site/index.php ? I've seen a post somewhere claiming that years ago, and I've tried many times to get it to work or re-find that post but I never managed to do so.
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^/(.*) /index.php/$1
I didn't test it, but it's probably as simple as that.But that's not what I meant. Instead of having index.php look at the url parameters and include the proper controller, just directly execute that controllers .php file. Make a file that you include in each controller that does any prep work you need and that's it, let apache execute the controller directly.
Also, if nearly arbitrary PHP files can be uploaded, the chances might be good that it's possible to upload other files as well, like some additional .htaccess files for subdirectories.
As an alternative, you can simply gzip all uploads automatically. You will save hard drive space and prevent any funny business.
For you to upload a file to your system it has to pass through PHP. That's where the problem is. Once it's on your system, it can be executed by other means ... those means not necessarily being Apache or NGINX. By encoding the upload, you not only reduce the size, but also render it harmless.
then just block apache to serve anything .php
this usually get me covered of most backdoors bugs in pear and such. ...not that i do that because of this reason. it was first only for organizing the code tree.
You can also try to get the PHP eastereggs displayed with something like this, on a PHP generated page:
http://example.com/?=PHPE9568F36-D428-11d2-A769-00AA001ACF42
Trying to provoke errors or weird PHP specific behaviour, maybe with PHP error messages displayed, is another way to gather some informations about the script language used by a site. But this is already more aggressive than simply looking for an X-Powered-By: header.
Just rewriting the file extension does not make a site any safer. Omitting file extensions is generally an interesting alternative, because in case you change from .php to .aspx or whatever, all URLs stay the same. Cool URIs don't change.
Yes, it's security through obscurity, and is absolutely not something you should rely on, but it can reduce the number of people giving your wobbly-looking front door a kick.
Of course, if everyone starts doing this, the scanners will switch to more robust methods of testing for your language and server types and versions.
it was a decision mostly done by usability and code clarity (separate presentation scripts from data/model ones)
But one benefit of not having the regular setup, is that even if i'm a victim of an automated attack, it will probably fail because it did not expected to not be serving .php or .phtml files as php. For a skilled targeted attack i'd still be as hopeless as the person hiding php.
had that happen when one box was compromised because of a ssh key bug. but it turned out, the attack was automated and had vectors that worked with linux x86 and several common unixes. i was running irix on an very old box. so i had just some weird log entries instead of a root kit. not that it prevented the paranoid i am to wipe the system as if i had a root kit.
(It's just a ini file parser; it has nothing to do with PHP settings.)
It's not up to date with 5.3.8 or 5.4 - but they are always slightly behind - but not 5 years behind.
Edit: Now I see that their news page is really out of date - my bad.
some other random ideas for php-security:
If you have to enable some form of option to exec binaries be aware that open_basedir is useless now, because the attacker can just start a python instance and operate under apache user if you are using mod_php
using fastcgi (mod_fcgid or nginx+php-fpm) and restrictive permissions on your directories should at least protect your other users home directories.
another idea is prevent malicous scripts is to firewall apache and php from iptables. there is an iptables module for restricting uid and gid ranges to have access to the outside world. this could at least prevent a trojan dropped in /tmp to connect to their irc-server. but you can also disallow outgoing traffic to port 80, this breaks however all the auto-update features of e.g. wordpress.
A lot of script-kiddie toolkits can also be stopped by not having gcc,wget,python etc.pp available to the user running php.
if you have to host sensitive data on the same host as the php application it's wise to use a jail or at least chroot for php, there are some guides to put a mod_fcgid php into a chroot
and: never ever use the mysql root user for database connectivity!
Also, open_basedir is nice and should be used whenever you can but it doesn't match a system-wide chroot.
Some flush()s output out to the browser (to show some initial feedback), but continue to process and send further output as the upgrade continues.
Secondly, I was kind of disappointed that this wasn't an overview on common mistakes users do when learning PHP. This feels basically feels like teaching someone how to enable safe mode, because you aren't teaching someone why they should escape sql or why they should encode user submitted content, which to me is much more important. (Though teaching someone to install Suhosin and disabling debug output is still important in my opinion, so props for that)
Disable external execution functions, eval, disable disable, disable. It appears to me that this is following the approach of disabling everything and nothing, then start coding without any security concerns, because you 'secured your PHP'.
I'm not a security obsessed person, but after hearing so much fuss about PHP lack of security I headed up to milw0rm a few years ago to see what it was all about. To my surprise (not so much) all the exploits were based on non sanitized user data.
Why would you use user data without sanitizing it? Why would you protect yourself against a file the hacker uploaded? (they should not have uploaded it in the first place) Why would you feed exec, eval, etc with potentially dangerous content?
If a programmer is stupid enough to do so, disabling such functions won't prevent him/her from screwing up big time some other way.
My advice: write proper applications with proper standard security in mind. It's not that hard.
Here is an ancient example: NT Web Technology Vulnerabilities, written by rain.forest.puppy, Phrack Magazine Volume 8, Issue 54 Dec 25th, 1998.
http://www.phrack.org/issues.html?issue=54&id=8#article
This is one of the oldest articles on SQL injection I know of.
He was going to do some big conference or something on the subject and drum up new business, but nothing ever came of it.
My guess is that many don't know what they are so they apply follow 'secure PHP' guides and feel safe, though they are not.
What planet are you from?
The number of pitfalls and traps you can fall into almost surpasses the 'safe' parts of the language (and its environment).
The huge vulnerability that opens up is that of data validation, and you can tighten up your server config all you want, but it won't mean shit without any of that.
Of course, since PHP is such a comparatively simple language, everyone thinks they're an expert once they know how to open a mysql connection (through the now deprecated bindings, of course) and code a simple blog script with basic CRUD functionality.
As a result, there's a 'simple/complicated' dichotomy when it comes to online documentation and tutorials, where the beginner developer ignores the complicated (and typically well thought-out) stuff, and goes for what they can easily copy and paste or get their head around.
Typically none of that code has any sort of validation or sanitisation. Half of it might go on about `magic_quotes_gpc` and `mysql_real_escape_string` and other PHP4-tastic curios, and the rest won't even mention that because checking user input is seemingly only related to db communication.
I feel pretty strongly about it because I've seen people post code snippets for PHP, trying to be helpful, but the code is dangerous. They serve better as examples of exactly what you shouldn't do.
And the one thing PHP beginners (and intermediates) need is better, simpler explanations of responsible coding practices, and how it isn't hard to do at all (it's only tedious); because the sooner they know, the better.
I should write a book or something.
> Except that building a "properly written PHP app" is way harder than in almost every other language in widespread use.
This makes no sense. PHP doesn't force you to do things the right way, but it doesn't force you to do things the wrong way either. It just doesn't force you either way.
Those of us who know what we're doing can make intelligent decisions ... and those of us who can't, shouldn't be writing in PHP.