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

refactor: CSRF protection #6320

Merged
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
refactor: extract restoreHash() method
  • Loading branch information
kenjis committed Jul 31, 2022
commit e056312d0c20f51c4d0b7bb64be66883d27b457b
26 changes: 19 additions & 7 deletions system/Security/Security.php
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,21 @@ public function sanitizeFilename(string $str, bool $relativePath = false): strin
return stripslashes($str);
}

/**
* Restore hash from Session or Cookie
*/
private function restoreHash(): void
{
if ($this->isCSRFCookie()) {
if ($this->isHashInCookie()) {
$this->hash = $this->hashInCookie;
}
} elseif ($this->session->has($this->tokenName)) {
// Session based CSRF protection
$this->hash = $this->session->get($this->tokenName);
}
}

/**
* Generates the CSRF Hash.
*/
Expand All @@ -511,13 +526,10 @@ protected function generateHash(): string
// We don't necessarily want to regenerate it with
// each page load since a page could contain embedded
// sub-pages causing this feature to fail
if ($this->isCSRFCookie()) {
if ($this->isHashInCookie()) {
return $this->hash = $this->hashInCookie;
}
} elseif ($this->session->has($this->tokenName)) {
// Session based CSRF protection
return $this->hash = $this->session->get($this->tokenName);
$this->restoreHash();

if ($this->hash !== null) {
return $this->hash;
}

$this->hash = bin2hex(random_bytes(static::CSRF_HASH_BYTES));
Expand Down