Home >Backend Development >PHP Tutorial >Security Analysis of PHP Temporary Files_PHP Tutorial
1. Introduction
Temporary files, as the name implies, are temporarily generated files, and the life cycle of the files is very short.
However, many applications cannot run without temporary files. Temporary files are everywhere on our computers. There are mainly the following forms of temporary files:
1. Intermediate files generated by file or graphics editing programs
2. When querying the database, the temporary cache file generated provides the previous result data to reduce the cost of accessing the database again; usually used for remote database or remote xml services
3. After the file is uploaded, it is temporarily stored on the server. The file name is the value of the global variable $_FILES['userfile']['tmp_name'] in php
4. In http requests, temporary files used to store sessions, these file names are usually sessionid (such as sess_7483ae44d51fe21353afb671d13f7199)
5. When transferring data between different applications or the same application, and the other party requires file-based input, use temporary files to store the data
2. Security features of temporary files
The biggest feature of temporary files is their non-persistence. In addition, from a security perspective, you can pay attention to other characteristics or risks of temporary files from the following aspects:
1. The location of temporary files
Temporary files are usually created and stored in the default path. In a typical Linux system, there are at least two directories or partitions that hold temporary files. One of them is the /tmp directory, and the other is /var/tmp. On systems with newer Linux kernels, there may also be /dev/shm, which is mounted using the tmpfs file system. Sometimes temporary files may also be placed in hidden subdirectories under the user's home directory. The advantage of using the default temporary file directory is that system processes can easily find, read and write.
However, the default temporary file storage directory may become a breeding ground for zombies and rootkits that compromise system security. This is because in most cases anyone (or any process) can write to these directories, and there are insecure permission issues. For example, we all know the sticky bit, which can be understood as the anti-deletion bit. If you want users to be able to add files but not delete files at the same time, you can use the sticky bit on the file. When this bit is set, the file cannot be deleted even if the user has write permissions on the directory. Most Linux distributions set the sticky bit on the temporary directory, which means that user A cannot clear a file belonging to user B, and vice versa. However, depending on the permissions of the file itself, it is possible for User A to view and modify the contents of that file.
2.Persistence of temporary files
As mentioned earlier, temporary files are non-persistent and will be deleted when the program ends. However, sometimes temporary files are forced to be saved persistently and are not deleted, such as:
2.1 The application crashed before closing without a chance to delete temporary files
2.2 The application is still running, but the operating system crashed
2.3 During the file copying process, the copy failed due to space issues, resulting in the intermediate files not being deleted
2.4 The operating system process usually clears the default temporary file directory regularly, but the deletion may fail for some reasons
2.5 Poorly written applications may ignore or forget to delete temporary files
3. The risks of temporary files
Useless temporary files exist on your server like ghosts. On the one hand, they occupy the hard disk, and on the other hand, they can be used illegally by others. There are some risks as follows:
3.1 Visibility
As we all know, making private data public is risky. Once a user steals your temporary files through some means (such as shell or ftp), the user or enterprise's private data can be obtained, thereby affecting you.
For example: the temporary file 2011_Confidential_Sales_Strategies.tmp may expose your company's business strategy in 2011, which will be very useful to your competitors; and for session hijackers, temporary files that store user session information sess_95971078f4822605e7a18c612054f658 is very critical.
In addition, there are other situations where temporary files may be peeked, such as: a spell check service, the URL returned is: http://bad.example.com/spellcheck.php?tmp_file= spellcheck46, after the attacker analyzes your URL parameters and uses http://bad.example.com/spellcheck.php?tmp_file=spellcheck45, he can access the verification result of the previous user.
3.2 Enforceability
Usually temporary files are not executable, but if an attacker uploads a php script to your temporary directory and executes it in some way, it may cause tragedy.
3.3 Temporary files were hijacked
Attackers may hijack your temporary files for their own purposes. It may replace your temporary file, or it may append some information after your temporary file.
The purpose of hijacking temporary files includes:
(1) Let your application process his data, not your own data
(2) Expose private data, such as system password files, or other files that cannot be read normally in PHP security mode
(3) Deleting data and hindering the normal processing of requests
(4) Create and output false data, destroying the results of the request
(5) By providing false data, causing damage to applications that use the data for further processing
(6) Redirect your output to other places to facilitate attackers to access or overwrite system files
Hijacking is often associated with race conditions. When two different processes operate on the same file, a race condition may occur. For example, a reading process and a writing process operate a piece of data at the same time. When the writing process has only completed part of it, the reading process has completed it. In this way, part of the content read is new and part is old, which is what we often say. Read dirty data.
The hijacking of temporary files will cause race conditions to a certain extent. Unless the hijacker accurately grasps the time and location, it will cause such security problems.
3. Prevent temporary files from being used maliciously
Earlier we introduced the concept of temporary files and the harm that may be caused by the malicious use of temporary files. This section mainly introduces some strategies to prevent temporary files from being used maliciously and reduce the harm caused by them.
1. Adjust the storage location
The most important and simplest step to prevent temporary files from being used maliciously is to make your temporary file directory and name difficult to guess. For any malicious use of temporary files, the attacker must know the name and path of the temporary file, so you should make it as difficult as possible for him to guess your temporary file name and path.
It is recommended that when selecting the temporary file directory, you should place your temporary files in the default directory, so that system processes can easily find, read and write. Instead, focus on coming up with a suitable, hard-to-guess name for the file name.
PHP’s tempnam() function can create a temporary file, and its automatically generated file name will not conflict with other file names in the current directory. The default permissions of the file created by this function are 600, which is rw——- .
For example
$filename = tempnam( ‘..', ‘myTempfile');
After running, a file named myTempfile1af may be generated. When running for the second time, a file named myTempfile1b0 will be generated.
Maybe some programming practice guides will suggest that when you use tempnam() to generate files, name them with some meaningful prefixes, so that the data contained in the files or the applications that need this data can be seen through the file names, but from the perspective of security From the point of view, it is best not to do this, as it points out the direction for the attacker.
Here is a way to introduce a prefix that has a certain meaning and also makes it less difficult for attackers 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 done with temporary file, delete it unlink ( $tempFilename ); ?>
This script uses the uniqid() function to generate a file name in the format: /tmp/skiResort392942668f9b396c08.03510070, and sets the file permissions to 600 through chmod.
If you need to share information with other applications, such as user passwords or random tokens generated at runtime, you may need to encrypt the file name. Only applications that know this key can read or modify the file content.
The following is a simple example of generating an encrypted file name file:
<?php $pathPrefix = ‘/tmp/skiResort'; // for demonstration, construct a secret here $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 done with temporary file, delete it unlink ( $tempFilename ); ?>
2. Restrict access permissions
In order to reduce the possibility of temporary files being executed or hijacked, you need to set the access permissions for temporary files and temporary file directories. Normally, set the permissions of temporary files to rw——- and the permissions of temporary file directories to rwx——.
In addition, you can also restrict access by setting the apache configuration file (only when you place temporary files in the www directory), as follows:
order deny,allow deny from all
3. Only write known files
Since you are the creator and author of temporary files, you should always know which files exist and what content is in the files. The methods mentioned above only make temporary file hijacking more difficult, but they cannot completely eliminate the possibility of the hijacker replacing the file or appending some content after the file. Therefore, when you create or write a file, you need to carefully check whether the file content meets the requirements.
When you use w+ to create a file, the file should be empty before you start writing, as shown below
<?php if ( filesize( $tempFilename ) === 0 ) { // write to the file } else { exit ( “$tempFilename is not empty.\nStart over again.”); } ?>
If the file is not empty, there may be something wrong with your creation, or the hijacker may have done something during the time you were creating and writing the file.
It is also possible that you successfully wrote the temporary file for the first time, but during the subsequent writing process, the hijacker performed some operations on the temporary file. This situation can be checked by using the check 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.只读已知文件
与只写已知文件类似,在读文件前需要检查检验码是否一致,防止临时文件被篡改。除此之外,如果你使用了openssl,可以在写文件的时候,将合法证书放在文件的末尾,这样的读的时候可以先检查文件末尾是否存在合法的证书;如果你没有使用openssl,也可以写入一段特定的算法生成的token,原理类似。
5.检查上传的文件
判断文件是否是通过 HTTP POST 上传的
bool is_uploaded_file ( string $filename )
如果 filename 所给出的文件是通过 HTTP POST 上传的则返回 TRUE。这可以用来确保恶意的用户无法欺骗脚本去访问本不能访问的文件,例如 /etc/passwd。 如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话,这种检查显得格外重要。
为了能使 is_uploaded_file() 函数正常工作,必须指定类似$_FILES['userfile']['tmp_name'] 的变量,而不是从客户端上传的文件名 $_FILES['userfile']['name']。需要注意的是is_uploaded_file返回false,不一定是上传文件被劫持了,也有可能是文件太大或者上传部分等,这些可以通过$_FILES['userfile']['error']查看。