Skip to content

Commit 17fdf33

Browse files
authored
fix: a reset link is not built from a header the caller chose (#915)
The password-reset mail's link came from UriContextInterface::getWebUri(), which is $request->getHttpHost() . $webRoot — and getHttpHost() prefers Forwarded / X-Forwarded-Host. Nothing calls setTrustedProxies(), so those headers are whatever the caller sent; verified against the running instance, where X-Forwarded-Host: evil.example.com comes straight back out in Access-Control-Allow-Origin. userPassReset/saveRequest needs no session, so an unauthenticated caller who knew a login and its email address could choose the host in the message the real user then received: a genuine reset mail, from the real installation, whose link carries the one-time hash to somebody else's server. Six other link builders already prefer the configured application URL; these two were the exception. The base URI is now decided inside UserPassRecover::getMailMessage(), which takes the config and the URI context rather than a caller-supplied string, so no future caller can pass the wrong one. The fallback is a new getUnforwardedWebUri() rather than getWebUri(), because preferring the application URL only helps an installation that configured one — with it unset, the default, the header would still choose the link. getHttpHost() is untouched: preferring the forwarded headers is right for a URL the same caller is about to be shown, and wrong only for one mailed to somebody else with a token.
1 parent 1be43fc commit 17fdf33

8 files changed

Lines changed: 131 additions & 4 deletions

File tree

‎src/Application/User/Services/UserPassRecover.php‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
use SP\Application\Application;
3030
use SP\Domain\Core\Messages\MailMessage;
3131
use SP\Domain\Common\Providers\Password;
32+
use SP\Domain\Config\Ports\ConfigDataInterface;
33+
use SP\Domain\Core\Bootstrap\UriContextInterface;
3234
use SP\Domain\Common\Services\Service;
3335
use SP\Domain\Common\Services\ServiceException;
3436
use SP\Domain\Core\Exceptions\ConstraintException;
@@ -66,8 +68,33 @@ public function __construct(
6668
parent::__construct($application);
6769
}
6870

69-
public static function getMailMessage(string $hash, string $baseUri): MailMessage
70-
{
71+
/**
72+
* The mail carrying a one-time reset link, and the address that link points at.
73+
*
74+
* The base URI is decided here rather than taken from the caller, because both callers used to
75+
* pass `UriContextInterface::getWebUri()` — which prefers `Forwarded` / `X-Forwarded-Host`,
76+
* headers supplied by whoever made the request, with no `setTrustedProxies()` anywhere to
77+
* restrict them. Verified against the running instance: `X-Forwarded-Host: evil.example.com`
78+
* comes straight back out of the application.
79+
*
80+
* `saveRequestAction()` needs no session, so an unauthenticated caller who knows a login and
81+
* its email address could choose the host in the mail the real user then receives — a
82+
* legitimate message, from the real installation, whose link hands the one-time hash to
83+
* somebody else.
84+
*
85+
* Six other link builders in this application already prefer the configured application URL
86+
* (`AccountHelper`, `ViewLinkController`, `PublicLinkViewBase`, `AccountSearchItem`,
87+
* `Template`, `Account\SaveRequestController`); these two were the exception. The fallback is
88+
* the unforwarded host rather than `getWebUri()`, so the header cannot choose it even when no
89+
* application URL has been configured.
90+
*/
91+
public static function getMailMessage(
92+
string $hash,
93+
ConfigDataInterface $configData,
94+
UriContextInterface $uriContext
95+
): MailMessage {
96+
$baseUri = $configData->getApplicationUrl() ?: $uriContext->getUnforwardedWebUri();
97+
7198
$mailMessage = new MailMessage();
7299
$mailMessage->setTitle(__('Password Change'));
73100
$mailMessage->addDescription(__('A request for changing your user password has been done.'));

‎src/Domain/Core/Bootstrap/UriContextInterface.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ interface UriContextInterface
3737
*/
3838
public function getWebUri(): string;
3939

40+
/**
41+
* The same URI, built without consulting `Forwarded` / `X-Forwarded-*`.
42+
*/
43+
public function getUnforwardedWebUri(): string;
44+
4045
/**
4146
* The current request path relative to the application root (e.g. files/index.php)
4247
*

‎src/Domain/Http/Ports/RequestService.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,11 @@ public function verifySignature(string $key, ?string $param = null): void;
100100
*/
101101
public function getHttpHost(): string;
102102

103+
/**
104+
* The host this request actually arrived at, without consulting the forwarded headers.
105+
*/
106+
public function getHttpHostIgnoringForwarding(): string;
107+
103108
/**
104109
* Return forward data per RFC 7239
105110
*

‎src/Infrastructure/Adapter/In/Web/Controllers/User/UserSaveBase.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ final protected function checkChangeUserPass(int $userId, User $userData): void
122122
$this->mailService->send(
123123
__('Password Change'),
124124
$userData->getEmail() ?? '',
125-
UserPassRecover::getMailMessage($hash, $this->uriContext->getWebUri())
125+
UserPassRecover::getMailMessage($hash, $this->configData, $this->uriContext)
126126
);
127127
}
128128
}

‎src/Infrastructure/Adapter/In/Web/Controllers/UserPassReset/SaveRequestController.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ public function saveRequestAction(): ActionResponse
122122
$this->mailService->send(
123123
__('Password Change'),
124124
$email,
125-
UserPassRecover::getMailMessage($hash, $this->uriContext->getWebUri())
125+
UserPassRecover::getMailMessage($hash, $this->configData, $this->uriContext)
126126
);
127127
} catch (Exception $e) {
128128
// Recorded and counted, not reported. The tracking still runs, so guessing is still

‎src/Infrastructure/Bootstrap/UriContext.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,14 @@
3636
private string $subUri;
3737
private string $webRoot;
3838
private string $webUri;
39+
private string $unforwardedWebUri;
3940

4041
public function __construct(RequestService $request)
4142
{
4243
$this->subUri = $this->buildSubUri($request);
4344
$this->webRoot = $this->buildWebRoot($request);
4445
$this->webUri = $request->getHttpHost() . $this->webRoot;
46+
$this->unforwardedWebUri = $request->getHttpHostIgnoringForwarding() . $this->webRoot;
4547
}
4648

4749
private function buildSubUri(RequestService $request): string
@@ -62,6 +64,21 @@ private function buildWebRoot(RequestService $request): string
6264
return '';
6365
}
6466

67+
/**
68+
* The same URI, built without consulting `Forwarded` / `X-Forwarded-*`.
69+
*
70+
* `getWebUri()` prefers those headers so that an installation behind a reverse proxy reports
71+
* the address its users actually type. They are supplied by whoever made the request, though,
72+
* and nothing here calls `setTrustedProxies()` — verified against the running instance, where
73+
* `X-Forwarded-Host: evil.example.com` comes straight back out. That is the right trade for a
74+
* displayed URL and the wrong one for a link that is mailed to somebody else and carries a
75+
* one-time token, which is what this exists for.
76+
*/
77+
public function getUnforwardedWebUri(): string
78+
{
79+
return $this->unforwardedWebUri;
80+
}
81+
6582
public function getWebUri(): string
6683
{
6784
return $this->webUri;

‎src/Infrastructure/Http/Services/Request.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,19 @@ public function getHttpHost(): string
387387
return strtolower(sprintf('%s://%s', $forwarded['proto'], $forwarded['host']));
388388
}
389389

390+
return $this->getHttpHostIgnoringForwarding();
391+
}
392+
393+
/**
394+
* The host this request actually arrived at, without consulting the forwarded headers.
395+
*
396+
* Those headers are supplied by whoever made the request — nothing here calls
397+
* `setTrustedProxies()` — so `getHttpHost()` answers whatever a caller asks it to. That is
398+
* acceptable for a URL the same caller is about to be shown, and not for one that is mailed to
399+
* somebody else with a one-time token in it.
400+
*/
401+
public function getHttpHostIgnoringForwarding(): string
402+
{
390403
/** @noinspection HttpUrlsUsage */
391404
$protocol = 'http://';
392405

‎tests/Integration/Infrastructure/Adapter/In/Web/Controllers/UserPassReset/SaveRequestControllerTest.php‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
use PHPUnit\Framework\MockObject\Exception;
3131
use Psr\Container\ContainerExceptionInterface;
3232
use Psr\Container\NotFoundExceptionInterface;
33+
use SP\Application\Notification\Ports\MailService;
34+
use SP\Domain\Core\Messages\MailMessage;
3335
use SP\Domain\User\Models\User as UserModel;
3436
use SP\Domain\Common\Dtos\QueryResult;
3537
use SP\Tests\Support\Generators\UserDataGenerator;
@@ -78,4 +80,62 @@ public function testSaveRequestBuildsTheResetMailWithoutFataling(): void
7880

7981
$this->expectOutputRegex('/"status":"OK","description":"Request sent"/');
8082
}
83+
84+
/**
85+
* The mailed link points where the installation lives, not where the caller said it does.
86+
*
87+
* `saveRequestAction()` needs no session, and the base URI came from
88+
* `UriContextInterface::getWebUri()`, which prefers `Forwarded` / `X-Forwarded-Host`. Nothing
89+
* in this application calls `setTrustedProxies()`, so those headers are whatever the caller
90+
* sent — verified against the running instance, where `X-Forwarded-Host: evil.example.com`
91+
* comes straight back out.
92+
*
93+
* So an unauthenticated caller who knew a login and its email address could choose the host in
94+
* the message the real user then received: a genuine mail, from the real installation, whose
95+
* link hands the one-time hash to somebody else's server.
96+
*
97+
* @throws ContainerExceptionInterface
98+
* @throws Exception
99+
* @throws NotFoundExceptionInterface
100+
*/
101+
public function testTheResetLinkIgnoresAForwardedHost(): void
102+
{
103+
$login = 'resetme';
104+
$email = 'resetme@example.com';
105+
106+
$userData = UserDataGenerator::factory()->buildUserData()->mutate(
107+
['login' => $login, 'email' => $email, 'isDisabled' => false, 'isLdap' => false]
108+
);
109+
110+
$this->addDatabaseMapperResolver(UserModel::class, new QueryResult([$userData]));
111+
112+
$sent = null;
113+
$mailService = $this->createStub(MailService::class);
114+
$mailService->method('send')->willReturnCallback(
115+
static function (string $subject, string|array $to, MailMessage $mailMessage) use (&$sent): void {
116+
$sent = $mailMessage->composeText();
117+
}
118+
);
119+
120+
$container = $this->buildContainer(
121+
IntegrationTestCase::buildRequest(
122+
'post',
123+
'index.php',
124+
['r' => 'userPassReset/saveRequest'],
125+
['login' => $login, 'email' => $email],
126+
[],
127+
self::CSRF_TOKEN,
128+
['HTTP_X_FORWARDED_HOST' => 'evil.example.com', 'HTTP_X_FORWARDED_PROTO' => 'https']
129+
),
130+
[MailService::class => $mailService]
131+
);
132+
133+
IntegrationTestCase::runApp($container);
134+
135+
self::assertNotNull($sent, 'the reset mail has to be sent for this to say anything');
136+
self::assertStringNotContainsString('evil.example.com', $sent);
137+
self::assertStringContainsString('localhost', $sent);
138+
139+
$this->expectOutputRegex('/"status":"OK","description":"Request sent"/');
140+
}
81141
}

0 commit comments

Comments
 (0)