Lista de Classes
- App\Middleware\Cors
- App\Middleware\Auth
- App\Middleware\Env
- AppMin
- Application
- Route
- Data\Database
- Data\Db2Database
- Data\OdbcDatabase
- Data\Validator
- Data\KeyValue\SqliteStorage
- Data\Log\FileLogger
- Data\Log\HtmlLogger
- Encoding\Base64Url
- Encoding\Json
- Encoding\Utf8
- Environment\DotEnv
- Environment\System
- FileSystem\Search
- FileSystem\Security
- FileSystem\Sync
- Lang\I18N
- Lang\L10N
- Lang\Time
- Media\Image
- Net\Config
- Net\Email
- Net\HttpClient
- Net\HttpResponse
- Net\IP
- Net\SmtpClient
- Security\Crypto
- Security\Password
- Security\Crypto\Encryption
- Security\Crypto\FileEncryption
- Security\Crypto\JWT
- Security\Crypto\PublicKey
- Security\Crypto\Random
- Security\Crypto\SignedData
- Security\Web\CsrfSession
- Security\Web\CsrfStateless
- Security\Web\RateLimit
- Web\Request
- Web\Response
FastSitePHP\FileSystem\Security
File System Security
Código Fonte
Código de Exemplo
Segurança de Sistema de Arquivos
// A Classe FileSystem Security contém funções para validar arquivos.
// Previna ataques Path Traversal verificando se um nome de arquivo existe
// em um diretório específico. Ataque Path Transversal podem ocorrer se um
// usuário tem concedida a permissão de especificar um arquivo em um
// sistema de arquivos através e input e usa um padrão como '/../' para
// obter arquivos de outro diretório.
// Exemplos:
// Assuma que ambos os arquivos existem e retornariam [true] da função
// integrada [is_file()]. [false] seria retornado para o segundo arquivo
// ao utilizar [Security::dirContainsFile()].
$file1 = 'user_image.jpg';
$file2 = '../../index.php';
$file_exists_1 = \FastSitePHP\FileSystem\Security::dirContainsFile($dir, $file1);
$file_exists_2 = \FastSitePHP\FileSystem\Security::dirContainsFile($dir, $file2);
// A função [dirContainsFile()] só permite que arquivos diretamente sob a
// pasta raiz então outra função existe para procurar subdiretórios a
// [dirContainsPath()].
$path1 = 'icons/clipboard.svg'; // Retorna [true]
$path2 = '../../app/index.php'; // Retorna [false]
$path_exists_1 = \FastSitePHP\FileSystem\Security::dirContainsPath($dir, $path1);
$path_exists_2 = \FastSitePHP\FileSystem\Security::dirContainsPath($dir, $path2);
// [dirContainsPath()] contains an optional 3rd parameter [$type] which defaults
// to 'file' and allows for one of the following options ['file', 'dir', 'all'].
$path3 = 'icons';
$exists = \FastSitePHP\FileSystem\Security::dirContainsPath($dir, $path3, 'dir');
// [dirContainsDir()] pode ser utilizada para verificar diretórios/pastas.
$dir1 = 'icons';
$dir2 = '../../app';
$dir_exists_1 = \FastSitePHP\FileSystem\Security::dirContainsDir($dir, $file1);
$dir_exists_2 = \FastSitePHP\FileSystem\Security::dirContainsDir($dir, $file2);
// Valide Arquivos de Imagem
// A função [fileIsValidImage()] pode ser utilizada para verificar se
// arquivos de imagem criados de outro input de usuário, são válidos. Por
// exemplo um usuário malicioso pode tentar renomear um script PHP ou
// arquivo executável como se fosse uma imagem e enviá-lo para um site.
// Retorna [true] se um arquivo de imagem [jpg, gif, png, webp, svg] for
// válido e a extensão do arquivo corresponder ao tipo de imagem.
$is_image = \FastSitePHP\FileSystem\Security::fileIsValidImage($image_file);
Métodos
dirContainsFile($dir, $file)
Prevent Path Traversal Attacks by verifying if a file name exists in a specified directory. Path Traversal Attacks can happen if a user is allowed to specify a file on a file system through input and uses a pattern such as '/../' to obtain files from another directory.
This function returns [true] if the file exists in the directory and the file name matches exactly to the [$file] parameter. The [$dir] parameter can be a relative path with '../' characters so it should not come from a user. The [$dir] parameter is required to be a valid directory otherwise an exception is thrown as it indicates a logic or permissions error in the app.
Example:
// Assume both files exist and would return [true] from built-in function [is_file()].
// False is returned for the 2nd file because a '/' character was used.
$dir = __DIR__ . '/../img';
true = Security::dirContainsFile($dir, 'user_image.jpg')
false = Security::dirContainsFile($dir, '../../index.php')
Retorna: bool
- https://en.wikipedia.org/wiki/Directory_traversal_attack
- https://www.owasp.org/index.php/Path_Traversal
- http://php.net/manual/en/security.filesystem.php
dirContainsPath($dir, $path)
Prevent Path Traversal Attacks by verifying if a file exists under the specified directory. Sub-directories can be specified, however path traversal using '../' or '..\' is not allowed for the [$path] paramater.
See additional comments and links in [dirContainsFile()].
Example:
// Assume both files exist and would return [true] from built-in function [is_file()].
// False is returned for the 2nd file because a '../' was used.
$dir = __DIR__ . '/../img';
true = Security::dirContainsPath($dir, 'icons/clipboard.svg')
false = Security::dirContainsPath($dir, '../../app/app.php')
Retorna: bool
dirContainsDir($root_dir, $dir_name)
Prevent Path Traversal Attacks by verifying if a directory exists in a specified directory.
This function returns [true] if the directory exists in the directory and the directory name matches exactly to the [$dir_name] parameter.
See additional comments and links in [dirContainsFile()].
Example:
// Assume both directories exist and would return [true] from built-in function [is_dir()].
// False is returned for the 2nd file because a '/' character was used.
$dir = __DIR__ . '/../img';
true = Security::dirContainsDir($dir, 'icons')
false = Security::dirContainsDir($dir, '../../app')
Retorna: bool
fileIsValidImage($full_path)
Returns [true] if a image file (jpg, jpeg, gif, png, webp, svg) is valid and the file's extension matches the image type.
This function can be used to verify if image files created from user input are valid. For example a malicious user may try to rename a PHP Script or executable file as an image and upload it to a site.
For SVG Files this function simply verifies that the file is a valid XML file with [svg] as the root element.
For other images types such as JPG or PNG this function uses the [FastSitePHP\Media\Image] class to check if a file is valid. If you intended on using the [Image] class from the same calling function then using this function is not needed as it would open the same image file twice.
If your app or site needs to resize an image after a user upload then the [Image] class is recommend, however if you simply need to verify an image then this helper function allows for simple and clear code.
Retorna: bool