Skip to content

Instantly share code, notes, and snippets.

@chihiro-adachi
Created June 17, 2021 02:03
Show Gist options
  • Save chihiro-adachi/2959de58f4028adada7db70527153def to your computer and use it in GitHub Desktop.
Save chihiro-adachi/2959de58f4028adada7db70527153def to your computer and use it in GitHub Desktop.
XssProtector
namespace Customize\EventListener;
use Eccube\Request\Context;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class XssProtector implements EventSubscriberInterface
{
/**
* @var Context
*/
protected $requestContext;
public function __construct(Context $requestContext)
{
$this->requestContext = $requestContext;
}
public function detectXss(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$query = strtolower(urldecode($request->getQueryString()));
$body = strtolower(urldecode($request->getContent()));
if ($query === '' && $body === '') {
return;
}
if (!$this->requestContext->isAdmin()) {
$pattern = "/<script.*?>|<\/script>|javascript:|<svg.*(onload|onerror).*?>|<img.*(onload|onerror).*?>|<body.*onload.*?>|<iframe.*?>|<object.*?>|<embed.*?>|<.*onmouse.*?>/i";
if (preg_match_all($pattern, $body, $matches)) {
// TODO attack.log
throw new BadRequestHttpException();
}
if (preg_match_all($pattern, $query, $matches)) {
// TODO attack.log
throw new BadRequestHttpException();
}
}
}
public static function getSubscribedEvents()
{
return [
'kernel.request' => ['detectXss', 768],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment