packetcode logo
Preventing Remote Execution in PHP

Preventing Remote Execution in PHP

3199 views 1 year ago Tutorials PHP

Remote execution attack, it involve misusing the internal logic of your application in order to execute arbitrary commands or scripts on the server. Since it takes place in your protected environment on the server, it is a very serious problem.

How it works

A remote execution attack aims to take direct control of your application by exploiting a scriptable interface within it. One such interface is a template system in php where the attacker embeds PHP code in $variables, and when the template system will execute it, we fall into the trap.

The other possibility is through user input that is used as a part of shell command. Here a crafty attacker can build an input value that, when injected into the shell, turns the single command into a scripted series of commands leading to collapse of the system.In general, applications vulnerable to remote execution attack are those that allow a user-submitted value to run through eval() in PHP, or injected into one of PHP’s five program execution functions: exec(), passthru(), proc_open(), shell_exec(), and system().

Sometimes attacker generates via file uploads too.Here the php code is embedded into the media file which the users cannot detect but when its rendered or executed the background script runs.

Strategies for Preventing Remote Execution

Limit Allowable Filename Extensions for Uploads

Apache uses a file’s extension to determine the Content-Type header to send with the file, or to hand the file off to a special handler such as PHP. If your application allows users to determine the filenames and extensions of files they are uploading, then an attacker might be able to simply upload a file with a .php extension and execute it by calling it.

One solution to this problem is to use an array of allowed extensions, and default to .upload for anything that isn’t allowed (or reject the uploaded file out of hand as a probable attack). You could even append an .upload extension to the original extension, rendering the file harmless while still keeping the type information intact.

Another solution is to rely on the Content-Type information sent by the browser when the file is uploaded, which you can find in the $_FILES[ $name ]['type'] value. Although you have no way of knowing whether this mime type is correct, as it could be spoofed, you can still use it to give the file one of several innocuous extensions, rather than trusting the extension it was sent with.

Store Uploads Outside the Web Document Root

Another preventive measure is not to store uploaded files within your web tree, thus removing the danger that an uploaded executable can subsequently be executed by the Apache webserver user.It is never a good idea to allow a world-writable (aka other-writable) directory within your web document root, even if your application does not directly upload files to it. If an attacker has or gains FTP or shell access to the server, she may be able to create a script in that directory, and use the webserver to execute it. To ensure that no such directories exist, you can use the following chmod command to recursively turn off the other-writable bit on all files in the web root:


chmod -R o-w /path/to/web/docroot

It is important to remember that storing files and scripts outside the web root does not render them immune to being executed by means of the include() or require() functions, or to being abused by other scripting agents on the server. Any file that is readable by the webserver or another scripting host is fair game for execution. But at least it means that an attacker cannot call scripts directly via a plain URI.

Allow Only Trusted, Human Users to Import Code

Advanced PHP applications often incorporate third-party modules like those available at such large code repositories as SourceForge (see http://sourceforge.net) or PECL (the PHP Extension Community Library; see http://www.pecl.php.net/). Such modules are self-contained collections of code, assets, and configuration files that fit into the larger framework of the application in order to implement custom functionality. Typically, these modules are installed and configured using the command shell, but users on shared hosts may not have shell access, and so an administrative web interface can be used to allow module installation.

Such an interface must be particularly sensitive to security concerns, and should be made available only to administrators authenticated over SSL. It should also be disabled by default, and refuse to execute over an insecure connection.

Sanitize Untrusted Input to eval()

If you can find ways to avoid using eval() in your scripts, do so. If you never use it, then you won’t need to worry about the possibility that it can be abused. But sometimes eval() is necessary (see http://php.net/eval for more information). In those cases, be relentless in sanitizing anything whatsoever that could be used to build a script.

You can sanitize the PHP metacharacters in a string with a function that combines addslashes() (to disarm all quotation marks) and str_replace() (to translate other metacharacters).


<?php
					
// use this function to sanitize input for eval()				
	function safeForEval( $string ) {
	  // newline check
	  $nl = chr(10);
	  if ( strpos( $string, $nl ) ) {

	   exit( "$string is not permitted as input." );
	  }


	  $meta = array( '$', '{', '}', '[', ']', '`', ';' );
	  $escaped = array('&#36', '&#123', '&#125', '&#91',
					   '&#93', '&#96', '&#59' );
	  // addslashes for quotes and backslashes
	  $out = addslashes( $string );
	  // str_replace for php metacharacters
	  $out = str_replace( $meta, $escaped, $out );
	  return $out;					
	} 

?>

You first check to see whether the input contains a newline character; if it does, you exit immediately with an appropriate message. Otherwise, you sanitize any PHP metacharacters you find in the input string by transforming them using decimal ASCII encoding. This technique will effectively render harmless any attempts at remote PHP execution, generating a parse error that can be caught by your application and handled appropriately.

Conclusion

Remote execution is one among the potential threats so it has to be handled properly. Metacharacter filter can help preventing to some extent but additional precautions also need to be taken as mentioned above to stay safe.

im krishna Teja, im a computer science engineer by qualification, a physics teacher by profession and a programmer by interest. I'm an expert in building visually stunning web apps using javascript, ...