Skip to content

Commit 4019db0

Browse files
committed
[!!!][SECURITY] Fix fluid viewhelper injection in FE
It was possible to use arbitrary viewhelpers in several fields (sendername, senderemail, ...). This is now prevented via a whitelist in extension configuration.
1 parent 892fb87 commit 4019db0

18 files changed

Lines changed: 1462 additions & 14 deletions

‎Classes/Domain/Repository/MailRepository.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,10 @@ public function getVariablesWithMarkersFromMail(Mail $mail, bool $htmlSpecialCha
360360
/**
361361
* Returns senderemail from a couple of arguments
362362
*
363+
* Security: the returned value was submitted by a website visitor and is returned verbatim. It
364+
* must never be used as a Fluid template source. Note that GeneralUtility::validEmail() accepts a
365+
* quoted local part, so being a valid address is no proof that the value is harmless.
366+
*
363367
* @param Mail $mail
364368
* @param string $default
365369
* @return string Sender Email
@@ -385,6 +389,11 @@ public function getSenderMailFromArguments(Mail $mail, string $default = ''): st
385389
/**
386390
* Returns sendername from a couple of arguments
387391
*
392+
* Security: the returned value was submitted by a website visitor and is returned verbatim - it
393+
* is persisted, shown in the backend module and exported, so it must not be modified here. It
394+
* must never be used as a Fluid template source, see
395+
* SendMailService::getKeysAllowedToContainFluid().
396+
*
388397
* @param Mail $mail Given Params
389398
* @param string|array $default String as default or cObject array
390399
* @param string $glue

‎Classes/Domain/Service/Mail/ReceiverMailReceiverPropertiesService.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,11 @@ protected function setReceiverEmails(): void
135135
/**
136136
* Get emails from FlexForm and parse with fluid
137137
*
138+
* Security: this is the only place where settings.receiver.email may be parsed. The result can
139+
* contain values that were substituted in from the submitted data, so parsing it a second time
140+
* would evaluate what a website visitor wrote - see SendMailService::getKeysAllowedToContainFluid(),
141+
* which is why receiverEmail is never parsed there.
142+
*
138143
* @return array
139144
* @throws Exception
140145
*/

‎Classes/Domain/Service/Mail/SendMailService.php‎

Lines changed: 70 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,46 @@ class SendMailService
2929
{
3030
use SignalTrait;
3131

32+
/**
33+
* Keys of the $email array that can hold a Fluid template at all
34+
*/
35+
const PARSABLE_KEYS = [
36+
'receiverName',
37+
'receiverEmail',
38+
'senderName',
39+
'senderEmail',
40+
'subject',
41+
];
42+
43+
/**
44+
* Per mail type those keys of the $email array that were written by an editor (FlexForm) or an
45+
* integrator (TypoScript) and may therefore contain Fluid. That is a documented feature - a
46+
* subject "Message from {firstname}" or a receiver "{f:cObject(typoscriptObjectPath:'lib.x')}".
47+
*
48+
* Every key that is not listed for a type holds a value that a website visitor can submit: the
49+
* sender of a mail to the receiver is the visitor, and the receiver of a mail to the sender is
50+
* the visitor as well. Such a value must never be used as a Fluid template source, because that
51+
* would let a visitor execute ViewHelpers.
52+
*
53+
* receiverEmail is listed for no type: for receiver and disclaimer mails it was already parsed
54+
* in ReceiverMailReceiverPropertiesService::getEmailsFromFlexForm() - with the visitor values
55+
* substituted into it - and it always holds a validated email address afterwards. Note that
56+
* GeneralUtility::validEmail() accepts a quoted local part, so an address is no proof that a
57+
* value is harmless.
58+
*/
59+
const CONFIGURED_KEYS_PER_TYPE = [
60+
'receiver' => ['receiverName', 'subject'],
61+
'disclaimer' => ['receiverName', 'subject'],
62+
'sender' => ['senderName', 'senderEmail', 'subject'],
63+
'optin' => ['senderName', 'senderEmail', 'subject'],
64+
];
65+
66+
/**
67+
* Mail types of other extensions have an unknown provenance, so only the subject is treated as a
68+
* configured value. Override getKeysAllowedToContainFluid() to widen this for an own mail type.
69+
*/
70+
const CONFIGURED_KEYS_FALLBACK = ['subject'];
71+
3272
/**
3373
* @var array
3474
*/
@@ -431,6 +471,9 @@ protected function getConfigurationFromSettings(array $settings): array
431471
/**
432472
* Parsing variables with fluid engine to allow viewhelpers in flexform
433473
*
474+
* Only values that were written in FlexForm or TypoScript are parsed - never a value that was
475+
* submitted by a website visitor, see getKeysAllowedToContainFluid().
476+
*
434477
* @param array $email
435478
* @param Mail $mail
436479
* @return void
@@ -469,21 +512,38 @@ protected function parseAndOverwriteVariables(array &$email, Mail $mail): void
469512
'email'
470513
);
471514
}
472-
$parse = [
473-
'receiverName',
474-
'receiverEmail',
475-
'senderName',
476-
'senderEmail',
477-
'subject'
478-
];
479-
foreach ($parse as $value) {
480-
$email[$value] = TemplateUtility::fluidParseString(
481-
$email[$value],
515+
foreach ($this->getKeysAllowedToContainFluid() as $key) {
516+
$email[$key] = TemplateUtility::fluidParseString(
517+
$email[$key],
482518
$mailRepository->getVariablesWithMarkersFromMail($mail)
483519
);
484520
}
485521
}
486522

523+
/**
524+
* Security: only values that were written by an editor or an integrator may be used as a Fluid
525+
* template source
526+
*
527+
* @see self::CONFIGURED_KEYS_PER_TYPE
528+
* @return string[]
529+
*/
530+
protected function getKeysAllowedToContainFluid(): array
531+
{
532+
$configuredKeys = array_key_exists($this->type, self::CONFIGURED_KEYS_PER_TYPE)
533+
? self::CONFIGURED_KEYS_PER_TYPE[$this->type]
534+
: self::CONFIGURED_KEYS_FALLBACK;
535+
536+
// iterate the full list instead of the allowlist to keep the original parsing order
537+
return array_values(
538+
array_filter(
539+
self::PARSABLE_KEYS,
540+
function (string $key) use ($configuredKeys): bool {
541+
return in_array($key, $configuredKeys, true);
542+
}
543+
)
544+
);
545+
}
546+
487547
/**
488548
* @param Mail $mail
489549
* @param array $settings
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
declare(strict_types = 1);
3+
namespace In2code\Powermail\Fluid\Cache;
4+
5+
use TYPO3Fluid\Fluid\Core\Cache\FluidCacheInterface;
6+
use TYPO3Fluid\Fluid\Core\Cache\FluidCacheWarmerInterface;
7+
use TYPO3Fluid\Fluid\Core\Cache\StandardCacheWarmer;
8+
9+
/**
10+
* Class NullFluidCache
11+
*
12+
* Keeps compiled templates of parsed strings out of the persistent fluid_template cache.
13+
*
14+
* Without this, every distinct value powermail parses - and a sender name or subject can be supplied
15+
* by a website visitor - is compiled into its own PHP class file below the fluid_template cache,
16+
* which is unbounded growth driven from the outside. These strings are short and cheap to parse, so
17+
* there is nothing to gain from caching them.
18+
*/
19+
class NullFluidCache implements FluidCacheInterface
20+
{
21+
/**
22+
* @param string $name
23+
* @return mixed
24+
*/
25+
public function get($name)
26+
{
27+
return null;
28+
}
29+
30+
/**
31+
* @param string $name
32+
* @param mixed $value
33+
* @return void
34+
*/
35+
public function set($name, $value)
36+
{
37+
}
38+
39+
/**
40+
* @param string|null $name
41+
* @return void
42+
*/
43+
public function flush($name = null)
44+
{
45+
}
46+
47+
/**
48+
* Nothing is ever written to this cache, so there is nothing to warm up either - the default
49+
* warmer is returned to satisfy the interface.
50+
*
51+
* @return FluidCacheWarmerInterface
52+
*/
53+
public function getCacheWarmer()
54+
{
55+
return new StandardCacheWarmer();
56+
}
57+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
declare(strict_types = 1);
3+
namespace In2code\Powermail\Fluid\Parser;
4+
5+
use TYPO3Fluid\Fluid\Core\Parser\TemplateProcessor\EscapingModifierTemplateProcessor;
6+
use TYPO3Fluid\Fluid\Core\Parser\TemplateProcessorInterface;
7+
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
8+
9+
/**
10+
* Class NeutralizeModifiersTemplateProcessor
11+
*
12+
* Removes Fluid's inline parser modifiers from a string without applying them.
13+
*
14+
* This replaces two of Fluid's own pre-processors for strings that powermail parses, because both
15+
* give the author of the string control over the rendering engine itself:
16+
*
17+
* - "{escaping=false}" (EscapingModifierTemplateProcessor) switches output escaping off for the
18+
* whole string, which would let submitted values reach the output unescaped.
19+
* - "{parsing off}" (PassthroughSourceModifierTemplateProcessor) makes AbstractTemplateView::render()
20+
* return the source verbatim, bypassing both variable interpolation and escaping.
21+
*/
22+
class NeutralizeModifiersTemplateProcessor implements TemplateProcessorInterface
23+
{
24+
/**
25+
* @param RenderingContextInterface $renderingContext
26+
* @return void
27+
*/
28+
public function setRenderingContext(RenderingContextInterface $renderingContext)
29+
{
30+
}
31+
32+
/**
33+
* @param string $templateSource
34+
* @return string
35+
*/
36+
public function preProcessSource($templateSource)
37+
{
38+
if (strpos($templateSource, '{escaping') !== false) {
39+
$templateSource = (string)preg_replace(
40+
EscapingModifierTemplateProcessor::SCAN_PATTERN_ESCAPINGMODIFIER,
41+
'',
42+
$templateSource
43+
);
44+
}
45+
46+
return str_replace(['{parsing off}', '{parsing on}'], '', $templateSource);
47+
}
48+
}
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
<?php
2+
declare(strict_types = 1);
3+
namespace In2code\Powermail\Fluid;
4+
5+
use In2code\Powermail\Fluid\Cache\NullFluidCache;
6+
use In2code\Powermail\Fluid\Parser\NeutralizeModifiersTemplateProcessor;
7+
use In2code\Powermail\Fluid\ViewHelper\RestrictedViewHelperInvoker;
8+
use In2code\Powermail\Fluid\ViewHelper\RestrictedViewHelperResolver;
9+
use In2code\Powermail\Fluid\ViewHelper\ViewHelperPolicy;
10+
use In2code\Powermail\Utility\ObjectUtility;
11+
use TYPO3\CMS\Core\Utility\GeneralUtility;
12+
use TYPO3\CMS\Fluid\View\StandaloneView;
13+
use TYPO3Fluid\Fluid\Core\Parser\TemplateProcessor\NamespaceDetectionTemplateProcessor;
14+
15+
/**
16+
* Class RestrictedStringRenderer
17+
*
18+
* Renders a string with Fluid so that "{marker}" placeholders are replaced, but only allowlisted
19+
* ViewHelpers may execute.
20+
*
21+
* Background: powermail parses several configured values with Fluid - the mail subject, the receiver
22+
* name and email, field titles and select options - so that editors can write "{firstname}" or
23+
* "{f:cObject(typoscriptObjectPath:'lib.x')}" into them. Some of those values can, depending on the
24+
* mail type, carry data submitted by a website visitor, which turns the whole string into a template
25+
* an attacker controls. Without a restriction, that allows arbitrary ViewHelper execution from an
26+
* unauthenticated request.
27+
*
28+
* @see ViewHelperPolicy for the allowlist
29+
* @see RestrictedViewHelperResolver for the parse time gate
30+
*/
31+
class RestrictedStringRenderer
32+
{
33+
/**
34+
* Controller name of the rendering context, and therefore part of the identifier of the compiled
35+
* template. Keeps compiled templates of restricted renderings separate from the permissive ones.
36+
*/
37+
const CACHE_SCOPE_CONTROLLER = 'PowermailRestrictedString';
38+
39+
/**
40+
* @param string $string
41+
* @param array $variables
42+
* @return string
43+
*/
44+
public function render(string $string, array $variables = []): string
45+
{
46+
if (strpos($string, '{') === false && strpos($string, '<') === false) {
47+
return $string;
48+
}
49+
50+
$policy = ViewHelperPolicy::fromExtensionConfiguration();
51+
$view = ObjectUtility::getObjectManager()->get(StandaloneView::class);
52+
if (!$view instanceof StandaloneView) {
53+
// Another view implementation was registered, so the restriction cannot be installed.
54+
// Replacing markers without Fluid is the only safe thing left to do.
55+
return $this->replaceMarkers($string, $variables);
56+
}
57+
58+
$renderingContext = $view->getRenderingContext();
59+
$resolver = new RestrictedViewHelperResolver($renderingContext->getViewHelperResolver(), $policy);
60+
$renderingContext->setViewHelperResolver($resolver);
61+
$renderingContext->setViewHelperInvoker(new RestrictedViewHelperInvoker($policy, $resolver));
62+
$renderingContext->setTemplateProcessors([
63+
GeneralUtility::makeInstance(NeutralizeModifiersTemplateProcessor::class),
64+
GeneralUtility::makeInstance(NamespaceDetectionTemplateProcessor::class),
65+
]);
66+
$renderingContext->setCache(GeneralUtility::makeInstance(NullFluidCache::class));
67+
$renderingContext->setControllerName(self::CACHE_SCOPE_CONTROLLER);
68+
// the fingerprint invalidates compiled templates when the allowlist changes
69+
$renderingContext->setControllerAction('Parse' . $policy->getFingerprint());
70+
$view->setTemplateSource($string);
71+
$view->assignMultiple($variables);
72+
73+
try {
74+
return $view->render() ?? '';
75+
} catch (\Throwable $throwable) {
76+
ObjectUtility::getLogger(self::class)->warning(
77+
'powermail could not parse a string with Fluid, Fluid syntax was removed from it',
78+
[
79+
'exception' => $throwable->getMessage(),
80+
'string' => mb_substr($string, 0, 200),
81+
]
82+
);
83+
84+
return $this->removeFluidSyntax($string);
85+
}
86+
}
87+
88+
/**
89+
* Fallback that mirrors what Fluid does to a "{marker}" - including the escaping the Escape
90+
* interceptor would apply - without handing the string to the parser.
91+
*
92+
* @param string $string
93+
* @param array $variables
94+
* @return string
95+
*/
96+
protected function replaceMarkers(string $string, array $variables): string
97+
{
98+
$replacements = [];
99+
foreach ($variables as $marker => $value) {
100+
if (is_array($value) || is_object($value)) {
101+
continue;
102+
}
103+
104+
$replacements['{' . $marker . '}'] = htmlspecialchars((string)$value, ENT_QUOTES);
105+
}
106+
107+
return strtr($string, $replacements);
108+
}
109+
110+
/**
111+
* Used when parsing failed. Returning the string unchanged would hand the payload straight to the
112+
* output, and returning an empty string would silently drop mails (an empty subject makes
113+
* SendMailService::sendMail() return early), so every active Fluid construct is removed instead.
114+
*
115+
* @param string $string
116+
* @return string
117+
*/
118+
protected function removeFluidSyntax(string $string): string
119+
{
120+
$string = (string)preg_replace('#</?[a-zA-Z0-9]+:[^>]*>#', '', $string);
121+
// twice, to also catch one level of nested curly braces
122+
$string = (string)preg_replace('#\{[^{}]*\}#', '', $string);
123+
$string = (string)preg_replace('#\{[^{}]*\}#', '', $string);
124+
125+
return trim($string);
126+
}
127+
}

0 commit comments

Comments
 (0)