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

Fix: prevent forbidden characters in captcha id and double use of captcha #36

Merged
merged 10 commits into from
Jan 6, 2025
5 changes: 4 additions & 1 deletion src/AbstractWord.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use function count;
use function is_array;
use function md5;
use function preg_match;
use function random_bytes;
use function random_int;
use function strlen;
Expand Down Expand Up @@ -394,7 +395,7 @@ public function isValid($value, $context = null)
$input = strtolower($value['input']);
$this->setValue($input);

if (! isset($value['id'])) {
if (! isset($value['id']) || ! preg_match('/^[a-f0-9][a-f0-9_\\\\]+$/i', (string) $value['id'])) {
$this->error(self::MISSING_ID);
return false;
}
Expand All @@ -404,6 +405,8 @@ public function isValid($value, $context = null)
$this->error(self::BAD_CAPTCHA);
return false;
}
//Invalidate the captcha by generating a new word after successful use
$this->setWord($this->generateWord());

return true;
}
Expand Down
19 changes: 19 additions & 0 deletions test/ImageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use function mkdir;
use function sleep;
use function strlen;
use function substr;
use function sys_get_temp_dir;
use function unlink;

Expand Down Expand Up @@ -226,6 +227,24 @@ public function testMissingNotValid(): void
$this->assertFalse($this->captcha->isValid($input));
}

public function testDoubleSubmitNotValidates(): void
{
$this->captcha->generate();
$input = ["id" => $this->captcha->getId(), "input" => $this->captcha->getWord()];
$this->assertTrue($this->captcha->isValid($input));
$this->assertFalse($this->captcha->isValid($input));
}

public function testInvalidIDCharactersSubmittedNotValidates(): void
{
$this->captcha->generate();
$id = $this->captcha->getId();
$input = ["id" => substr($id, 0, strlen($id) - 1) . "+", "input" => $this->captcha->getWord()];
$this->assertFalse($this->captcha->isValid($input));
$input = ["id" => substr($id, 0, strlen($id) - 1) . "-", "input" => $this->captcha->getWord()];
$this->assertFalse($this->captcha->isValid($input));
}

public function testWrongWordNotValid(): void
{
$this->captcha->generate();
Expand Down