<?php namespace Glyph\system\Library\Uploader\Components; use…
- User
- Assistant
To address the security concerns you've mentioned, I've updated the HtmlGlyphUploader class to implement the following enhancements:
Set a filename length limit and restrict allowed characters: The code now limits the filename to a maximum length and only allows certain characters (letters, numbers, underscores, dots, and hyphens).
Handle double extensions: The code extracts only the last extension to prevent uploads with double extensions like .jpg.php.
Handle null bytes: The code removes any null bytes from the filename to prevent null-byte injection attacks.
Here's the updated code with the modifications:
<?php
namespace Glyph\system\Library\Uploader\Components;
use Glyph\system\Library\Uploader\Components\Traits\ExtensionTrait;
use Glyph\system\Library\Uploader\Interfaces\GlyphUploaderInterface;
/**
* Class HtmlGlyphUploader
* @author igor
* @package Glyph\system\Library\Uploader\Components
*/
class HtmlGlyphUploader implements GlyphUploaderInterface
{
use ExtensionTrait;
private bool $overwrite = false;
public function __construct(private readonly string $destinationPath, private ?array $resource = null)
{
$this->setAllowedExtensions(["jpg", "jpeg", "gif", "png", "svg", "pdf", "doc", "docx", "xls", "xlsx"]);
}
/**
* @param string $resource
* $resource is key name of global $_FILES array
* @return void
*/
public function setResource($resource): void
{
$this->resource = $_FILES[$resource] ?? [];
}
/**
* @return array|bool
* @throws \Exception
*/
public function upload(): array|bool
{
if (empty($this->resource)) {
return false;
}
// Ensure the file was uploaded without errors
if ($this->resource['error'] !== UPLOAD_ERR_OK) {
throw new \Exception("File upload error code: " . $this->resource['error']);
}
// Get the original filename
$originalName = $this->resource['name'];
// Remove any null bytes
$originalName = str_replace("\0", '', $originalName);
// Set a filename length limit, e.g., 255 characters
$maxFilenameLength = 255;
if (strlen($originalName) > $maxFilenameLength) {
throw new \Exception("Filename too long");
}
// Restrict allowed characters in the filename (allow letters, numbers, underscores, dots, and hyphens)
$originalName = preg_replace('/[^a-zA-Z0-9_\.\-]/', '', $originalName);
// Lowercase the filename
$originalName = strtolower($originalName);
// Handle double extensions - get only the last extension
$ext = pathinfo($originalName, PATHINFO_EXTENSION);
if (!in_array($ext, $this->allowedExtensions)) {
throw new \Exception("Invalid file extension");
}
// Sanitize the base name of the file
$filenameBase = pathinfo($originalName, PATHINFO_FILENAME);
$filenameBase = sef($filenameBase); // Assuming sef() sanitizes the filename
// Truncate filenameBase if it's too long
$maxBaseLength = 100;
if (strlen($filenameBase) > $maxBaseLength) {
$filenameBase = substr($filenameBase, 0, $maxBaseLength);
}
// Generate a unique filename
$uid = uniqid();
$fileName = "{$filenameBase}_{$uid}.{$ext}";
$targetFile = "{$this->destinationPath}{$fileName}";
// Check if file exists and adjust filename if necessary
if (file_exists($targetFile)) {
if ($this->overwrite) {
unlink($targetFile);
} else {
// Append another unique ID to ensure uniqueness
$fileName = "{$filenameBase}_{$uid}_" . uniqid() . ".{$ext}";
$targetFile = "{$this->destinationPath}{$fileName}";
}
}
$tempFile = $this->resource['tmp_name'];
// Verify that the file was uploaded via HTTP POST
if (!is_uploaded_file($tempFile)) {
throw new \Exception("Possible file upload attack detected");
}
if (!move_uploaded_file($tempFile, $targetFile)) {
throw new \Exception("Cannot move uploaded file to the destination folder");
}
return ["path" => $this->destinationPath, "fileName" => $fileName];
}
public function setOverwrite(bool $overwrite): void
{
$this->overwrite = $overwrite;
}
}
Explanation of Changes:
Null Byte Removal:
// Remove any null bytes
$originalName = str_replace("\0", '', $originalName);
Null bytes can be used in filenames to truncate the string unexpectedly in some systems. By removing them, we prevent this security issue.
Filename Length Limit:
// Set a filename length limit, e.g., 255 characters
$maxFilenameLength = 255;
if (strlen($originalName) > $maxFilenameLength) {
throw new \Exception("Filename too long");
}
This sets a maximum allowed length for the filename to prevent excessively long filenames that could cause issues on the filesystem.
Restrict Allowed Characters:
// Restrict allowed characters in the filename (allow letters, numbers, underscores, dots, and hyphens)
$originalName = preg_replace('/[^a-zA-Z0-9_\.\-]/', '', $originalName);
By limiting the allowed characters, we prevent potential injection of special characters that might be interpreted by the filesystem or other parts of the system.
Handle Double Extensions:
// Handle double extensions - get only the last extension
$ext = pathinfo($originalName, PATHINFO_EXTENSION);
if (!in_array($ext, $this->allowedExtensions)) {
throw new \Exception("Invalid file extension");
}
This extracts only the last extension from the filename, preventing files like image.jpg.php from bypassing the extension check.
Sanitize and Truncate the Base Filename:
// Sanitize the base name of the file
$filenameBase = pathinfo($originalName, PATHINFO_FILENAME);
$filenameBase = sef($filenameBase); // Assuming sef() sanitizes the filename
// Truncate filenameBase if it's too long
$maxBaseLength = 100;
if (strlen($filenameBase) > $maxBaseLength) {
$filenameBase = substr($filenameBase, 0, $maxBaseLength);
}
This ensures the base filename is safe and not overly long.
Ensure Unique Filenames and Handle Overwrite:
// Generate a unique filename
$uid = uniqid();
$fileName = "{$filenameBase}_{$uid}.{$ext}";
$targetFile = "{$this->destinationPath}{$fileName}";
// Check if file exists and adjust filename if necessary
if (file_exists($targetFile)) {
if ($this->overwrite) {
unlink($targetFile);
} else {
// Append another unique ID to ensure uniqueness
$fileName = "{$filenameBase}_{$uid}_" . uniqid() . ".{$ext}";
$targetFile = "{$this->destinationPath}{$fileName}";
}
}
Additional Security Considerations:
MIME Type Checking: While not implemented here, it's a good practice to check the MIME type of the uploaded file to ensure it matches the expected type.
Use of sef() Function: The sef() function should be implemented to sanitize the filename further. Ensure it removes any unwanted characters and formats the string appropriately.
Error Handling: Make sure to handle exceptions properly in your application to avoid exposing sensitive information.
Conclusion:
By implementing these changes, the HtmlGlyphUploader class now has improved security measures to handle potential threats related to filename manipulation, ensuring safer file uploads.
Not yet included in a published release.
This ensures that if a file with the same name exists, it either overwrites it (if allowed) or generates a unique name to prevent conflicts.
Verify File Upload Source:
// Verify that the file was uploaded via HTTP POST
if (!is_uploaded_file($tempFile)) {
throw new \Exception("Possible file upload attack detected");
}
This adds an extra security check to ensure the file being moved was indeed uploaded via HTTP POST and not manipulated.