Skip to content

Commit cbf5ee0

Browse files
committed
Fix XSS vulnerability #128
1 parent fb925a1 commit cbf5ee0

3 files changed

Lines changed: 24 additions & 9 deletions

File tree

src/Service/User/PropertyService.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ public function sanitizeHtml(Property $property, bool $isHtmlAllowed): Property
6868
if (!$isHtmlAllowed) {
6969
$property = $this->propertyTransformer->contentToPlainText($property);
7070
$property = $this->propertyTransformer->contentToHtml($property);
71+
} else {
72+
$property = $this->propertyTransformer->removeScriptsFromHtml($property);
7173
}
7274

7375
return $property;

src/Transformer/PropertyTransformer.php

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,25 @@ final class PropertyTransformer
1111
{
1212
public function contentToHtml(Property $property): Property
1313
{
14-
$htmlContent = HtmlHelper::text2Html($property->getPropertyDescription()->getContent());
15-
$property->setPropertyDescription(
16-
$property->getPropertyDescription()->setContent($htmlContent)
17-
);
18-
19-
return $property;
14+
return $this->transformContent($property, HtmlHelper::text2Html(...));
2015
}
2116

2217
public function contentToPlainText(Property $property): Property
2318
{
24-
$htmlContent = $property->getPropertyDescription()->getContent();
25-
$textContent = HtmlHelper::html2Text($htmlContent);
19+
return $this->transformContent($property, HtmlHelper::html2Text(...));
20+
}
21+
22+
public function removeScriptsFromHtml(Property $property): Property
23+
{
24+
return $this->transformContent($property, HtmlHelper::removeScriptsFromHtml(...));
25+
}
26+
27+
private function transformContent(Property $property, callable $transformFunction): Property
28+
{
29+
$content = $property->getPropertyDescription()->getContent();
30+
$transformedContent = \call_user_func($transformFunction, $content);
2631
$property->setPropertyDescription(
27-
$property->getPropertyDescription()->setContent($textContent)
32+
$property->getPropertyDescription()->setContent($transformedContent)
2833
);
2934

3035
return $property;

src/Utils/HtmlHelper.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,12 @@ public static function text2Html(string $text): string
1717
{
1818
return preg_replace("/\r\n|\r|\n/", '<br>', $text);
1919
}
20+
21+
public static function removeScriptsFromHtml(string $html): string
22+
{
23+
$sanitizedHtml = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);
24+
$sanitizedHtml = preg_replace('# on\w+="[^"]*"#i', '', (string) $sanitizedHtml);
25+
26+
return preg_replace("# on\w+='[^']*'#i", '', (string) $sanitizedHtml);
27+
}
2028
}

0 commit comments

Comments
 (0)