Skip to content

Commit

Permalink
Fix XSS vulnerability #128
Browse files Browse the repository at this point in the history
  • Loading branch information
Coderberg committed Jun 20, 2024
1 parent fb925a1 commit cbf5ee0
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
2 changes: 2 additions & 0 deletions src/Service/User/PropertyService.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ public function sanitizeHtml(Property $property, bool $isHtmlAllowed): Property
if (!$isHtmlAllowed) {
$property = $this->propertyTransformer->contentToPlainText($property);
$property = $this->propertyTransformer->contentToHtml($property);
} else {
$property = $this->propertyTransformer->removeScriptsFromHtml($property);
}

return $property;
Expand Down
23 changes: 14 additions & 9 deletions src/Transformer/PropertyTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,25 @@ final class PropertyTransformer
{
public function contentToHtml(Property $property): Property
{
$htmlContent = HtmlHelper::text2Html($property->getPropertyDescription()->getContent());
$property->setPropertyDescription(
$property->getPropertyDescription()->setContent($htmlContent)
);

return $property;
return $this->transformContent($property, HtmlHelper::text2Html(...));
}

public function contentToPlainText(Property $property): Property
{
$htmlContent = $property->getPropertyDescription()->getContent();
$textContent = HtmlHelper::html2Text($htmlContent);
return $this->transformContent($property, HtmlHelper::html2Text(...));
}

public function removeScriptsFromHtml(Property $property): Property
{
return $this->transformContent($property, HtmlHelper::removeScriptsFromHtml(...));
}

private function transformContent(Property $property, callable $transformFunction): Property
{
$content = $property->getPropertyDescription()->getContent();
$transformedContent = \call_user_func($transformFunction, $content);
$property->setPropertyDescription(
$property->getPropertyDescription()->setContent($textContent)
$property->getPropertyDescription()->setContent($transformedContent)
);

return $property;
Expand Down
8 changes: 8 additions & 0 deletions src/Utils/HtmlHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,12 @@ public static function text2Html(string $text): string
{
return preg_replace("/\r\n|\r|\n/", '<br>', $text);
}

public static function removeScriptsFromHtml(string $html): string
{
$sanitizedHtml = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);
$sanitizedHtml = preg_replace('# on\w+="[^"]*"#i', '', (string) $sanitizedHtml);

return preg_replace("# on\w+='[^']*'#i", '', (string) $sanitizedHtml);
}
}

0 comments on commit cbf5ee0

Please sign in to comment.