Features

Snuffleupagus has a lot of features that can be divided in two main categories: bug-classes killers and virtual-patching. The first category provides primitives to kill various bug families (like arbitrary code execution via unserialize for example) or raise the cost of exploitation. The second category is a highly configurable system to patch functions in php itself.

Bug classes killed or mitigated

system injections

The system function executes an external program and displays the output. It is used to interact with various external tools, like file-format converters. Unfortunately, passing user-controlled parameters to it often leads to arbitrary command execution.

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

The PHP documentation about system

We’re mitigating it by filtering the $, |, ;, `, \n and & chars in our default configuration, making it a lot harder for an attacker to inject arbitrary commands.

Remote code execution via file-upload

Some PHP applications allows users to upload content like avatars to a forum. Unfortunately, content validation often isn’t implemented properly (if at all), meaning arbitrary file upload often leads to an arbitrary code execution, contrary to the documentation.

Not validating which file you operate on may mean that users can access sensitive information in other directories.

The PHP documentation about file uploads

We’re killing it, like Suhosin, by automatically calling a script upon file upload, if it returns something else than 0, the file will be removed (or stored in a quarantine, for further analysis).

We’re recommending to use the vld project inside the script to ensure the file doesn’t contain any valid PHP code, with something like this:

$ php -d vld.execute=0 -d vld.active=1 -d extension=vld.so $file

Examples of related vulnerabilities

  • CVE-2017-6090: Unauthenticated remote code execution in PhpCollab
  • EDB-38407: Authenticated remote code execution in GLPI
  • CVE-2013-5576: Authenticated remote code execution in Joomla
  • EDB-19154: Authenticated remote code execution in qdPM

Weak-PRNG via rand/mt_rand

The functions rand and mt_rand are often used to generate random numbers used in sensitive context, like password generation, token creation. Unfortunately, as stated in the documentation, the quality of their entropy is low, leading to the generation of guessable values.

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes.

The PHP documentation about rand

We’re addressing this issue by replacing every call to rand and mt_rand with a call to the random_int, a CSPRNG.

It’s worth noting that the PHP documentation contains the following warning:

min max range must be within the range getrandmax(). i.e. (max - min) <= getrandmax(). Otherwise, rand() may return poor-quality random numbers.

The PHP documentation about rand

This is of course addressed as well by the harden_rand feature.

Examples of related vulnerabilities

XXE

Despite the documentation saying nothing about this class of vulnerabilities, XML eXternal Entity (XXE) often leads to arbitrary file reading, SSRF and sometimes even arbitrary code execution.

XML documents can contain a Document Type Definition (DTD), enabling definition of XML entities. It is possible to define an (external) entity by a URI, that the parser will access and embed its content back into the document for further processing.

For example, providing an url like file:///etc/passwd will read the file’s content. Since the file is not valid XML, the application will spit it out in an error message, thus leaking its content.

We’re killing this class of vulnerabilities by calling the libxml_disable_entity_loader function with its parameter set to true at startup, and then nop’ing it, so it won’t do anything if ever called again.

Examples of related vulnerabilities

  • CVE-2015-5161: Unauthenticated arbitrary file disclosure on Magento
  • CVE-2014-8790: Unauthenticated remote code execution in GetSimple CMS
  • CVE-2011-4107: Authenticated local file disclosure in PHPMyAdmin

Exploitation, post-exploitation and general hardening

Virtual-patching

PHP itself exposes a number of functions that might be considered dangerous and that have limited legitimate use cases. system(), exec(), dlopen() - for example - fall into this category. By default, PHP only allows us to globally disable some functions.

However, (ie. system()) they might have legitimate use cases in processes such as self upgrade etc., making it impossible to effectively disable them - at the risk of breaking critical features.

Snuffleupagus allows the user to restrict usage of specific functions per file, or per file with a matching (sha256) hash, thus allowing the use of such functions only in the intended places. It can also restrict per CIDR, to restrict execution to users on the LAN for example. There are a lot of different filters, so make sure to read the corresponding documentation.

Furthermore, running the following script will generate an hash and line-based whitelist of dangerous functions, droping them everywhere else:

<?php

function help($name) {
	die("Usage: $name [-h|--help] [--without-hash] folder\n");
}

if ($argc < 2) {
	help($argv[0]);
}

$functions_blacklist = ['shell_exec', 'exec', 'passthru', 'php_uname', 'popen',
	'posix_kill', 'posix_mkfifo', 'posix_setpgid', 'posix_setsid', 'posix_setuid',
	'posix_setgid', 'posix_uname', 'proc_close', 'proc_nice', 'proc_open',
	'proc_terminate', 'proc_open', 'proc_get_status', 'dl', 'pnctl_exec',
	'pnctl_fork', 'assert', 'system', 'curl_exec', 'curl_multi_exec', 'function_exists'];

$extensions = ['php', 'php7', 'php5', 'inc'];

$path = realpath($argv[count($argv) - 1]);
$parsedArgs = getopt('h', ['without-hash', 'help']);

if (isset($parsedArgs['h']) || isset($parsedArgs['help'])) {
	help($argv[0]);
}

$useHash = !isset($parsedArgs['without-hash']);

$output = Array();

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($objects as $name => $object){
	if (FALSE === in_array (pathinfo($name, PATHINFO_EXTENSION), $extensions, true)) {
		continue;
	}

	$hash = '';
	$file_content = file_get_contents($name);

	if ($useHash) {
		$hash = '.hash("' . hash('sha256', $file_content) . '")';
	}

	foreach(token_get_all($file_content) as $token) {
		if ($token[0] != 319) {
			continue;
		}

		if (in_array($token[1], $functions_blacklist, true)) {
			$output[] = 'sp.disable_function.function("' . $token[1] . '").filename("' . $name . '")' . $hash . '.allow();' . "\n";
		}
	}
}
foreach($functions_blacklist as $fun) {
	$output[] = 'sp.disable_function.function("' . $fun . '").drop();' . "\n";
}

foreach (array_unique($output) as $line) {
 	echo $line;
}

The intent is to make post-exploitation process (such as backdooring of legitimate code, or RAT usage) a lot harder for the attacker.

Global strict mode

By default, PHP will coerce values of the wrong type into the expected one if possible. For example, if a function expecting an integer is given a string, it will be coerced in an integer.

PHP7 introduced a strict mode, in which variables won’t be coerced anymore, and a TypeError exception will be raised if the types aren’t matching. Scalar type declarations are optional, but you don’t have to use them in your code to benefit from them, since every internal function from php has them.

This option provide a switch to globally activate this strict mode, helping to uncover vulnerabilities like the classical strcmp bypass and various other types mismatch.

This feature is largely inspired from the autostrict module from krakjoe.

Preventing sloppy comparisons

The aforementioned strict mode only works with annotated types and native functions, so it doesn’t cover every instances of type juggling <https://secure.php.net/manual/en/language.types.type-juggling.php> during comparisons. Since comparison between different types in PHP is notoriously difficult to get right, Snuffleupagus offers a way to always use the identical operator instead of the equal one (see the operator section for PHP’s documentation for more details), so that values with different types will always be treated as being different.

Preventing execution of writable PHP files

If an attacker manages to upload an arbitrary file or to modify an existing one, odds are that (thanks to the default umask) this file is writable by the PHP process.

Snuffleupagus can prevent the execution of this kind of file. A good practice would be to use a different user to run PHP than for administrating the website, and using this feature to lock this up.

White and blacklist in eval

While eval is a dangerous primitive, tricky to use right, with almost no legitimate usage besides templating and building mathematical expressions based on user input, it’s broadly (mis)used all around the web.

Snuffleupagus provides a white and blacklist mechanism, to explicitly allow and forbid specific functions call from being issued inside eval.

Protection against cross site request forgery

Cross-site request forgery, sometimes abbreviated as CSRF, is when unauthorised commands are issued from a user that the application trusts. For example, if a user is authenticated on a banking website, an other site might present something like <img src="http://mybank.com/transfer?from=user&to=attack&amount=1337EUR">, effectively transferring money from the user’s account to the attacker one.

Snuffleupagus can prevent this (in supported browsers) by setting the samesite attribute on cookies.

Dumping capabilities

It’s possible to apply the dump() filter to any virtual-patching rule, to dump the complete web request, along with the filename and the corresponding line number. By using the right set of restrictive rules (or by using the overly restrictives ones in simulation mode), you might be able to gather interesting vulnerabilities used against your website.

Dumps are stored in the folder that you pass to the dump() filter, in files named sp_dump.SHA with SHA being the sha256 of the rule that matched. This approach allows to mitigate denial of services attacks that could fill up your filesystem.

Misc low-hanging fruits in the default configuration file

Snuffleupagus is shipping with a default configuration file, containing various examples and ideas of things that you might want to enable (or not).

Available functions recon

Usually after compromising a website the attacker does some recon within its webshell, to check which functions are available to execute arbitrary code. Since it’s not uncommon for some web-hosts to disable things like system or passthru, or to check if mitigations are enabled, like open_basedir. This behaviour can be detected by preventing the execution of functions like ini_get or is_callable with suspicious parameters.

chmod hardening

Some PHP applications are using broad rights when using the chmod function, like the infamous chmod(777) command, effectively making the file writable by everyone. Snuffleupagus is preventing this kind of behaviour by restricting the parameters than can be passer to chmod.

Arbitrary file inclusion hardening

Arbitrary file inclusion is a common vulnerability, that might be detected by preventing the inclusion of anything that doens’t match a strict set of file extensions in calls to include or require.

Cheap SQL injections detection

In some SQL injections, attackers might need to use comments, a feature that is often not used in production system, so it might be a good idea to filter queries that contains some. The same filtering idea can be used against SQL functions that are frequently used in SQL injections, like sleep, benchmark or strings like version_info.

On the topic of SQL injections, if a function performing a query returns FALSE (indicating an error), it might be useful to dump the request for further analysis.