Compare commits

...

2 Commits

2 changed files with 70 additions and 7 deletions

View File

@ -378,6 +378,27 @@ final class MD_STD {
}
/**
* Wrapper around the finfo functions to get the mime content type of a file.
*
* @param string $filepath Expected file path.
*
* @return string
*/
public static function mime_content_type(string $filepath):string {
if (!($finfo = \finfo_open(FILEINFO_MIME_TYPE))) {
throw new Exception("Cannot open finfo context");
}
if (!($mime_type = finfo_file($finfo, $filepath))) {
throw new MDWrongFileType("Cannot get mime type of file: " . basename($filepath));
}
\finfo_close($finfo);
return $mime_type;
}
/**
* Checks if a file exists, with one of the expected mime types.
*
@ -397,13 +418,7 @@ final class MD_STD {
return;
}
if (!($finfo = \finfo_open(FILEINFO_MIME_TYPE))) {
throw new Exception("Cannot open finfo context");
}
if (!($mime_type = finfo_file($finfo, $filepath))) {
throw new MDWrongFileType("Cannot get mime type of file: " . basename($filepath));
}
\finfo_close($finfo);
$mime_type = self::mime_content_type($filepath);
if (!\in_array($mime_type, $accepted_mimetype, true)) {
throw new MDWrongFileType("Incorrect mime type of file " . \basename($filepath) . ". Mime type is " . \mime_content_type($filepath) . ", accepted any of ['" . \implode("', '", $accepted_mimetype) . "']");

48
MD_STD_SEC.php Normal file
View File

@ -0,0 +1,48 @@
<?PHP
/**
* Gathers wrappers for handling basic security operations.
*/
declare(strict_types = 1);
/**
* Class providing static functions with basic security operations.
*/
final class MD_STD_SEC {
/**
* Function for retrieving the anti-csrf token or generating it if need be.
*
* @return string
*/
public static function getAntiCsrfToken():string {
if (empty($_SESSION['csrf-token'])) {
$_SESSION['csrf-token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf-token'];
}
/**
* Function for validating anti-csrf tokens. Each anti-csrf token is removed
* after use.
*
* @return boolean
*/
public static function validateAntiCsrfToken():bool {
$validity = false;
if (!empty($_POST['csrf-token'])
&& !empty($_SESSION['csrf-token'])
&& hash_equals($_SESSION['csrf-token'], $_POST['csrf-token']) === true
) {
$validity = true;
}
$_SESSION['csrf-token'] = null; unset($_SESSION['csrf-token']);
return $validity;
}
}