Security analysis of PHP temporary files _php Tips

Source: Internet
Author: User
Tags chmod http post openssl php script file permissions

First, Introduction
temporary files, as the name implies, are temporarily generated files, and the life cycle of the file is very short.

However, the operation of many applications can not be separated from temporary files, temporary files on our computers everywhere, mainly in the following forms of temporary files:

1. File or graphic editing program, generated intermediate files
2. Database query, the generated temporary cache files, provide the results of the previous data, to reduce the cost of accessing the database again; services typically used for remote databases or remote XML
3. The file is uploaded on the server side of the temporary storage, its file name is PHP global variable $_files[' userfile ' [' tmp_name '] value
4. In the HTTP request, the temporary files used to hold the session, which are usually sessionid (such as sess_7483ae44d51fe21353afb671d13f7199)
5. In different applications or the same application to pass data, and the other side requires file-based input, at this time using temporary files to store data

Ii. Security features of temporary documents

The most significant feature of a temporary file is its non-persistent, and in addition to security, you can focus on the other features or risks of the temporary file from the following perspectives:

1. location of temporary files

Temporary files are usually created and stored in the default path, and in a typical Linux system, at least two directories or partitions maintain temporary files. One of these is the/tmp directory, and/var/tmp. In the newer Linux kernel system, there may also be/dev/shm, which is loaded with the Tmpfs file system. Occasionally, temporary files may also be placed in a hidden subdirectory in the user's home directory. The advantage of using the default temp file directory is that system processes are easy to find and read and write.

However, the storage directory of default temporary files may become a hotbed of zombies and rootkit that compromise system security. This is because in most cases, anyone (or any process) can write something to these directories, and there are unsafe licensing issues. For example, we all know sticky bit, which can be understood as an anti-deletion bit. If you want users to be able to add files and not delete files at the same time, you can use the sticky bit bit for the file. After this bit is set, the file cannot be deleted even if the user has write permission to the directory. Most Linux distributions set the sticky bit on the temporary directory, which means that user A cannot purge a file that belongs to User B, and vice versa. However, depending on the permissions of the file itself, user A is likely to view and modify the contents of that file.

2. permanence of the temporary document

The previous reference to temporary files is non-persistent and will be deleted at the end of the program, but sometimes temporary files will be forced to persist and not be deleted, such as:

2.1 Application crashes before shutting down, no chance to delete temporary files
2.2 The application is still running, but the operating system is crashing.
2.3 Replication failed due to space problems during file copying, resulting in intermediate files not deleted
2.4 The default temp file directory that the operating system process usually empties periodically, but the deletion fails for some reason
2.5 Poorly written applications may ignore or forget to delete temporary files

3. risk of temporary documents

Useless temporary files like ghosts exist on your server, on the one hand, the hard drive, on the other hand, can be illegally used by other people, save the following risks:

3.1 Visibility

It is well known that exposing private data is risky. Once a user steals your temporary files through some means, such as a shell or FTP, you can gain access to the private data of the user or enterprise, which affects you.

For example: temporary file 2011_confidential_sales_ Strategies.tmp may expose your company's 2011 business strategy, which will be useful for your competitors, and for session hijackers, temporary files that hold user session information Sess_ 95971078f4822605e7a18c612054f658 is critical.

Besides, there are other situations. Temporary files may be peeping, such as: A spell check service, the URL of the return result is: http://bad.example.com/spellcheck.php?tmp_file=spellcheck46, The attacker analyzes your URL parameters and uses HTTP://BAD.EXAMPLE.COM/SPELLCHECK.PHP?TMP_FILE=SPELLCHECK45 to access the previous user's validation results.

3.2 Enforceability

Typically, temporary files are not executable, but if an attacker uploads a PHP script to your temp directory and executes it in some way, that could be a tragedy.

3.3 Temporary files were hijacked

Attackers may hijack your temporary files for their own purposes. He may replace your temporary files, or you may append some information to your temporary files.

The purpose of hijacking temporary documents includes:

(1) Let your application process his data, not your own data
(2) Exposure of privacy data, such as System password files, or other PHP security mode can not read the normal file
(3) Delete data, blocking the normal request
(4) Creating and outputting false data, destroying the result of the request
(5) Damage to applications that use data for next steps by providing false data
(6) Redirect your output to other places to facilitate attackers to access or overwrite system files

Hijacking is usually associated with competitive conditions. Competitive conditions can occur when two different processes operate on the same file. For example, a read process and a write process operate a piece of data at the same time, and when the write process completes only a fraction of the time, the read process is completed, so that the content is read in part by the new, part of the old, which is what we often say read dirty data.

The hijacking of temporary documents, to a certain extent, will result in competitive conditions, unless the hijackers accurately grasp the time and position, otherwise it will cause such security problems.

Iii. prevention of the malicious use of temporary documents

we have previously described the concept of temporary files, as well as the potential hazards of temporary files being used, which mainly introduce strategies to prevent the malicious use of temporary files and mitigate their hazards.

1. Adjust storage location

The most important and easiest step in preventing temporary files from being maliciously exploited is to make your temporary files directory and name difficult to guess. Any malicious use of a temporary file, an attacker must know the name and path of the temporary file, so you should make it as hard as possible to guess your temporary file name and path.

It is recommended that you keep your temporary files in the default directory when choosing the temporary file directory, so that the system process can be easily found and read and written. Instead, put your energy in the name of the name that you want for the filename.

PHP's Tempnam () function, you can create a temporary file, and its auto-generated file name does not conflict with other filenames in the current directory, this function creates a file default permission is 600, that is, RW ——-。

For example

$filename = Tempnam ('.. ', ' mytempfile ');

A file named Mytempfile1af may be generated after the run, and the file name named Mytempfile1b0 is generated the second time it is run.
Maybe some programming practice guides will suggest that when you use Tempnam () to generate files, name it with some meaningful prefix, so that you can see the data contained in the file by file name or the application of this data, but from a security point of view it is best not to do so, which is tantamount to pointing the way for an attacker.

Here is a method that can have a meaning prefix that also makes the attacker less likely to guess, as follows:

<?php
//define
the parts of the filename define (' Tmp_dir ', '/tmp/');
$prefix = ' Skiresort ';
Construct the filename
$tempFilename = uniqid ($prefix, TRUE);
Create the file Touch
($tempFilename);
Restrict Permissions
chmod ($tempFilename, 0600);
Now work
with the file//... assuming data
in $value file_put_contents ($tempFilename, $value);
... When do with temporary file, delete it
unlink ($tempFilename);
? >

This script, through the uniqid () function, generates a file name format of:/tmp/skiresort392942668f9b396c08.03510070, and sets the file permissions to 600 by chmod.

If you need to share information with other applications, such as user passwords or random token generated at run time, you may need to encrypt file names, and only applications that know the key can read or modify the contents of the file.

The following is a simple example of generating an encrypted file name file:

<?php
$pathPrefix = '/tmp/skiresort ';
For demonstration, construct a secret this
$secret = ' Today is '. Date ("L, D F.");
$randomPart = SHA1 ($secret);
$tempFilename = $pathPrefix. $randomPart;
Touch ($tempFilename);
chmod ($tempFilename, 0600);
Now work
with the file//... assuming data
in $value file_put_contents ($tempFilename, $value);
... When do with temporary file, delete it
unlink ($tempFilename);
? >

2. Restricting access rights

To reduce the likelihood of temporary files being executed or hijacked, you need to set the access rights for temporary files and temporary file directories. Normally, the permissions for temporary files are set to the RW ——-, and the permissions for the temporary files directory are rwx ——。

Alternatively, you can restrict access by setting the Apache configuration file (only if you place the temporary files in the WWW directory), as follows:

Order Deny,allow
deny and all

3. Write only known files

Since you are the creator and author of a temporary file, you should always know which files exist and what is in the file. The method mentioned earlier, just makes temporary file hijacking more difficult, but not completely eliminate the hijackers replace files or append some content after the possibility, so when you create or write a file, you need to carefully check whether the contents of the file to meet the requirements.

When you use the W+ method, create a file that should be empty before you start writing, as follows

<?php
if (filesize ($tempFilename) = = 0) {
//write to
the file} else {
exit (' $tempFilename is n OT Empty.\nstart over again. ");
>

If the file is not empty, you may have a problem creating it, and it is possible that the hijacker has done something with the time you created and wrote the file.

It is also possible that you first succeeded in writing a temporary file, but in the course of writing later on, the hijacker took some action on the temporary file, which can be checked in the form of an inspection code, as follows:

<?php
//write something to the file; then hash it
$hashnow = Sha1_file ($tempFilename);
$_session[' hashnow ' = $hashnow;
Later, get ready to write again
$hashnow = Sha1_file ($tempFilename);
if ($hashnow = = $_session[' Hashnow ']) {
//write to the file again
//Get and save a new hash
$hashnow = Sha1_file ($tempFilename);
$_session[' hashnow ' = $hashnow;
} else {
exit ("Temporary file contains unexpected contents.\nstart over again.");
>

4. read-only known files

Similar to write-only known files, you need to check that the test code is consistent before you read the file to prevent the temporary file from being tampered with. In addition, if you use the OpenSSL, you can write the file, the legal certificate at the end of the file, such reading can first check the file at the end of the existence of a legitimate certificate, if you do not use OpenSSL, you can write a specific algorithm generated token, the principle is similar.

5. Check the uploaded files

To determine if the file was uploaded via an HTTP POST

BOOL Is_uploaded_file (String $filename)

Returns TRUE if the file given by FileName is uploaded over an HTTP POST. This can be used to ensure that malicious users cannot spoof scripts to access files that cannot be accessed, such as/etc/passwd. This is especially important if the uploaded file is likely to cause the content to be displayed to users or other users of the system.

In order for the Is_uploaded_file () function to work, you must specify a variable similar to the $_files[' userfile ' [' tmp_name '], rather than the filename uploaded from the client $_files[' userfile ' [' Name ']. Note that Is_uploaded_file returns false, not necessarily the upload file was hijacked, it is possible that the file is too large or upload part, these can be $_files[' userfile ' [' Error '] view.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.