Reputation: 641
My PHP web application parses incoming email messages and stores it in MySQL table. After email content is parsed I use MySQL prepared statements to store different email parts such as "To", "From", "Subject", "Body" etc. to prevent any code injections.
If an email has an attachment I would need to store it in a folder and if it is encrypted with PGP to run gpg external command through PGP EXEC function.
This files handling seems to be code injectable, i.e. if someone call an attahcment something like:
"mydoc.doc mysqldump_to_www_root and_format_all_partitions"
Maybe I'm wrong. To prevent that I decided to check if the file exists right after its creation like that:
//Here I save the file to a folder
$filename = $attachment->filename;
if ($fp = fopen($save_dir.$filename, 'w')) {
while($bytes = $attachment->read()) {
fwrite($fp, $bytes);
}
fclose($fp);
}
//Here I check for injection
If(!is_file($attach_dir.'/'.$filename)) {
// something wrong, do not proceed
}
My OS is Ubuntu with EXT4 file system. Would that shceme save me from possible code injections in email file attachments? Do I need to worry about it in the first place if eventually I want to do the follwoing for example:
$cmd = "gpg --passphrase *** '$attachedir/$filename'";
exec($cmd, $output);
In other words does storing a file to a disk sanitize/filter the file name or there could be exceptions?
Upvotes: 0
Views: 438
Reputation: 34563
PHP has an escapeshellarg()
function that escapes shell metacharacters in a string to ensure that it's treated as a single argument, not a group of arguments or separate commands. Use this on the filename when building the command string that you pass to exec()
.
Upvotes: 1