Add anti-CSRF token

phpcs-errors:238 phpunit-status:successful
This commit is contained in:
Joshua Ramon Enslin 2020-07-03 16:41:31 +02:00 committed by Stefan Rohde-Enslin
parent 5af012ba8b
commit 9d73a9b61e
3 changed files with 45 additions and 6 deletions

View File

@ -44,7 +44,7 @@ function lang_getfrombrowser(array $allowed_languages, string $default_language,
// Alle Infos über diese Sprache rausholen
// phpcs:disable Generic.Strings.UnnecessaryStringConcat
$res = preg_match('/^([a-z]{1,8}(?:-[a-z]{1,8})*)' . '(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches);
$res = preg_match('/^([a-z]{1,8}(?:-[a-z]{1,8})*)(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches);
// phpcs:enable
// war die Syntax gültig?
@ -66,9 +66,7 @@ function lang_getfrombrowser(array $allowed_languages, string $default_language,
}
// Bis der Sprachcode leer ist...
// phpcs:disable Squiz.PHP.DisallowSizeFunctionsInLoops
while (count($lang_code)) {
// phpcs:enable
while (!empty($lang_code)) {
// mal sehen, ob der Sprachcode angeboten wird
if (in_array(strtolower(join('-', $lang_code)), $allowed_languages)) {
// Qualität anschauen
@ -252,3 +250,39 @@ function identical_values(array $arrayA, array $arrayB):bool {
return $arrayA == $arrayB;
}
/**
* Function for retrieving the anti-csrf token or generating it if need be.
*
* @return string
*/
function getAntiCsrfToken():string {
if (empty($_SESSION['anti-csrf-token'])) {
$_SESSION['anti-csrf-token'] = bin2hex(random_bytes(32));
}
return $_SESSION['anti-csrf-token'];
}
/**
* Function for validating anti-csrf tokens. Each anti-csrf token is removed
* after use.
*
* @return boolean
*/
function validateAntiCsrfToken():bool {
$validity = false;
if (!empty($_POST['anti-csrf-token'])
&& !empty($_SESSION['anti-csrf-token'])
&& hash_equals($_SESSION['anti-csrf-token'], $_POST['anti-csrf-token']) === true
) {
$validity = true;
}
$_SESSION['anti-csrf-token'] = null; unset($_SESSION['anti-csrf-token']);
return $validity;
}

View File

@ -43,6 +43,7 @@ echo '
<div class="uploader">
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" id="csrf-token" name="csrf-token" aria-label="Anti-CSRF Token" value="' . htmlspecialchars(getAntiCsrfToken()) . '" />
<label for="fileToUpload">' . $csvxml_overview['select_csv_file_for_upload'] . '</label>
<input name="uploaded" type="file" accept=".csv" id="fileToUpload" required />
<button type="submit">' . $csvxml_overview['upload'] . '</button>

View File

@ -6,6 +6,10 @@ $target = "csv/";
$target .= basename($_FILES['uploaded']['name']);
$targetpart = basename($_FILES['uploaded']['name']);
if (validateAntiCsrfToken() === false) {
throw new WrongCsrfTokenException();
}
//This is our size condition
if ($uploaded_size > 40000000) {
echo "Your file is too large.<br>";