Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add signature validation and filename sanitization functions #122

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/Utility/FileUtilities.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,19 @@ public static function importUrlFileToTemp($url, $name = '')
}
}

/**
* @param string $fileName
* @return string
*/
public static function sanitizeFileName($fileName)
{
// Remove any characters that are not alphanumeric, underscores, dots, or dashes
$fileName = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $fileName);

// Replace multiple consecutive dots with a single dot (in order to avoid directory traversal issues)
return preg_replace('/\.+/', '.', $fileName);
}

public static function sendFile($file, $download = false, $chunk = null)
{
if (is_file($file)) {
Expand Down Expand Up @@ -1337,6 +1350,33 @@ public static function rearrangePostedFiles($arr)
return $new;
}

public static function validateFileSignature($filePath, $contentType)
{
$handle = fopen($filePath, 'rb');
if (!$handle) {
return false;
}

$bytes = fread($handle, 8); // 8 bytes should be sufficient for most file types
fclose($handle);

$fileSignatures = [
'jpg' => ["\xFF\xD8\xFF", 'image/jpeg'],
'png' => ["\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 'image/png'],
'pdf' => ["\x25\x50\x44\x46\x2D", 'application/pdf'],
];

foreach ($fileSignatures as $signature) {
[$magicBytes, $expectedContentType] = $signature;

if (strpos($bytes, $magicBytes) === 0 && $contentType === $expectedContentType) {
return true;
}
}

return false;
}

/**
* Updates .env file setting.
*
Expand Down