Skip to content
Permalink
Browse files Browse the repository at this point in the history
Add CSRF-token for comments
  • Loading branch information
morontt committed Jun 23, 2022
1 parent 589dc00 commit 36b2d4a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
31 changes: 30 additions & 1 deletion application/controllers/IndexController.php
Expand Up @@ -154,6 +154,7 @@ public function topicAction()

$form = new Application_Form_Comment();
$form->topicId->setValue($post->id);
$form->getElement('csrfToken')->setValue($this->generateCommentToken());

$this->view->form = $form;

Expand Down Expand Up @@ -234,7 +235,10 @@ public function ajaxaddcommentAction()
if ($form->isValid($this->getRequest()->getPost())) {
$formData = $form->getValues();

$this->saveComment($topicId, $url, $formData);
if ($this->validCommentToken($formData['csrfToken'])) {
$this->saveComment($topicId, $url, $formData);
}

$result['valid'] = true;
} else {
$formView = new Zend_View;
Expand Down Expand Up @@ -413,4 +417,29 @@ protected function isCDN()
&& (stripos($_SERVER['HTTP_VIA'], 'BunnyCDN') !== false
|| strpos($_SERVER['HTTP_VIA'], 'cdn77') !== false);
}

private function generateCommentToken($time = null): string
{
$time = $time ?? time();
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

return base64_encode($time . ':' . hash('md5', 'MD5_' . $userAgent . $time, true));
}

private function validCommentToken($token): bool
{
$raw = base64_decode($token, true);
if ($raw === false) {
return false;
}

$position = strpos($raw, ':');
if ($position === false) {
return false;
}

$time = substr($raw, 0, $position);

return hash_equals($this->generateCommentToken($time), $token);
}
}
4 changes: 4 additions & 0 deletions application/forms/Comment.php
Expand Up @@ -85,6 +85,10 @@ public function init()
$this->checkCookie();
}

$csrfToken = new Zend_Form_Element_Hidden('csrfToken');
$csrfToken->addValidator('NotEmpty');
$this->addElement($csrfToken);

$this->setElementDecorators($this->elementDecorators);
}

Expand Down
1 change: 1 addition & 0 deletions application/views/scripts/index/formcomment.phtml
Expand Up @@ -17,6 +17,7 @@
<?php echo $this->form->topicId; ?>
<?php echo $this->form->parentId; ?>
<?php echo $this->form->cookie; ?>
<?php echo $this->form->csrfToken; ?>
</div>
<div class="ym-fbox-button">
<button type="submit" class="ym-button ym-add" id="submit" name="submit">Добавить комментарий</button>
Expand Down

0 comments on commit 36b2d4a

Please sign in to comment.