Skip to content

Commit bf6563c

Browse files
fix(dav): Rate limit calendar/subscription creation
Signed-off-by: Christoph Wurst <christoph@winzerhof-wurst.at>
1 parent b94c1f9 commit bf6563c

File tree

7 files changed

+324
-0
lines changed

7 files changed

+324
-0
lines changed

apps/dav/appinfo/v1/caldav.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
// Backends
2929
use OC\KnownUser\KnownUserService;
3030
use OCA\DAV\CalDAV\CalDavBackend;
31+
use OCA\DAV\CalDAV\Security\RateLimitingPlugin;
3132
use OCA\DAV\Connector\LegacyDAVACL;
3233
use OCA\DAV\CalDAV\CalendarRoot;
3334
use OCA\DAV\Connector\Sabre\Auth;
@@ -116,6 +117,7 @@
116117
$server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class));
117118
}
118119
$server->addPlugin(new ExceptionLoggerPlugin('caldav', \OC::$server->getLogger()));
120+
$server->addPlugin(\OC::$server->get(RateLimitingPlugin::class));
119121

120122
// And off we go!
121123
$server->exec();

apps/dav/composer/composer/autoload_classmap.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
'OCA\\DAV\\CalDAV\\Search\\Xml\\Filter\\PropFilter' => $baseDir . '/../lib/CalDAV/Search/Xml/Filter/PropFilter.php',
9191
'OCA\\DAV\\CalDAV\\Search\\Xml\\Filter\\SearchTermFilter' => $baseDir . '/../lib/CalDAV/Search/Xml/Filter/SearchTermFilter.php',
9292
'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport' => $baseDir . '/../lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php',
93+
'OCA\\DAV\\CalDAV\\Security\\RateLimitingPlugin' => $baseDir . '/../lib/CalDAV/Security/RateLimitingPlugin.php',
9394
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObject' => $baseDir . '/../lib/CalDAV/Trashbin/DeletedCalendarObject.php',
9495
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObjectsCollection' => $baseDir . '/../lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php',
9596
'OCA\\DAV\\CalDAV\\Trashbin\\Plugin' => $baseDir . '/../lib/CalDAV/Trashbin/Plugin.php',

apps/dav/composer/composer/autoload_static.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ class ComposerStaticInitDAV
105105
'OCA\\DAV\\CalDAV\\Search\\Xml\\Filter\\PropFilter' => __DIR__ . '/..' . '/../lib/CalDAV/Search/Xml/Filter/PropFilter.php',
106106
'OCA\\DAV\\CalDAV\\Search\\Xml\\Filter\\SearchTermFilter' => __DIR__ . '/..' . '/../lib/CalDAV/Search/Xml/Filter/SearchTermFilter.php',
107107
'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport' => __DIR__ . '/..' . '/../lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php',
108+
'OCA\\DAV\\CalDAV\\Security\\RateLimitingPlugin' => __DIR__ . '/..' . '/../lib/CalDAV/Security/RateLimitingPlugin.php',
108109
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObject' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/DeletedCalendarObject.php',
109110
'OCA\\DAV\\CalDAV\\Trashbin\\DeletedCalendarObjectsCollection' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php',
110111
'OCA\\DAV\\CalDAV\\Trashbin\\Plugin' => __DIR__ . '/..' . '/../lib/CalDAV/Trashbin/Plugin.php',

apps/dav/lib/CalDAV/CalDavBackend.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,27 @@ public function getCalendarsForUserCount($principalUri, $excludeBirthday = true)
305305
return $column;
306306
}
307307

308+
/**
309+
* Return the number of subscriptions for a principal
310+
*/
311+
public function getSubscriptionsForUserCount(string $principalUri): int {
312+
$principalUri = $this->convertPrincipal($principalUri, true);
313+
$query = $this->db->getQueryBuilder();
314+
$query->select($query->func()->count('*'))
315+
->from('calendarsubscriptions');
316+
317+
if ($principalUri === '') {
318+
$query->where($query->expr()->emptyString('principaluri'));
319+
} else {
320+
$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
321+
}
322+
323+
$result = $query->executeQuery();
324+
$column = (int)$result->fetchOne();
325+
$result->closeCursor();
326+
return $column;
327+
}
328+
308329
/**
309330
* @return array{id: int, deleted_at: int}[]
310331
*/
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* @copyright 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
7+
*
8+
* @author 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
9+
*
10+
* @license GNU AGPL version 3 or any later version
11+
*
12+
* This program is free software: you can redistribute it and/or modify
13+
* it under the terms of the GNU Affero General Public License as
14+
* published by the Free Software Foundation, either version 3 of the
15+
* License, or (at your option) any later version.
16+
*
17+
* This program is distributed in the hope that it will be useful,
18+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
19+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20+
* GNU Affero General Public License for more details.
21+
*
22+
* You should have received a copy of the GNU Affero General Public License
23+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
24+
*/
25+
26+
namespace OCA\DAV\CalDAV\Security;
27+
28+
use OC\Security\RateLimiting\Exception\RateLimitExceededException;
29+
use OC\Security\RateLimiting\Limiter;
30+
use OCA\DAV\CalDAV\CalDavBackend;
31+
use OCA\DAV\Connector\Sabre\Exception\TooManyRequests;
32+
use OCP\IConfig;
33+
use OCP\IUserManager;
34+
use Psr\Log\LoggerInterface;
35+
use Sabre\DAV;
36+
use Sabre\DAV\Exception\Forbidden;
37+
use Sabre\DAV\ServerPlugin;
38+
use function count;
39+
use function explode;
40+
41+
class RateLimitingPlugin extends ServerPlugin {
42+
43+
/** @var Limiter */
44+
private $limiter;
45+
/** @var IUserManager */
46+
private $userManager;
47+
/** @var CalDavBackend */
48+
private $calDavBackend;
49+
/** @var IConfig */
50+
private $config;
51+
/** @var LoggerInterface */
52+
private $logger;
53+
/** @var string|null */
54+
private $userId;
55+
56+
public function __construct(Limiter $limiter,
57+
IUserManager $userManager,
58+
CalDavBackend $calDavBackend,
59+
LoggerInterface $logger,
60+
IConfig $config,
61+
?string $userId) {
62+
$this->limiter = $limiter;
63+
$this->userManager = $userManager;
64+
$this->calDavBackend = $calDavBackend;
65+
$this->config = $config;
66+
$this->logger = $logger;
67+
$this->userId = $userId;
68+
}
69+
70+
public function initialize(DAV\Server $server): void {
71+
$server->on('beforeBind', [$this, 'beforeBind'], 1);
72+
}
73+
74+
public function beforeBind(string $path): void {
75+
if ($this->userId === null) {
76+
// We only care about authenticated users here
77+
return;
78+
}
79+
$user = $this->userManager->get($this->userId);
80+
if ($user === null) {
81+
// We only care about authenticated users here
82+
return;
83+
}
84+
85+
$pathParts = explode('/', $path);
86+
if (count($pathParts) === 3 && $pathParts[0] === 'calendars') {
87+
// Path looks like calendars/username/calendarname so a new calendar or subscription is created
88+
try {
89+
$this->limiter->registerUserRequest(
90+
'caldav-create-calendar',
91+
(int) $this->config->getAppValue('dav', 'rateLimitCalendarCreation', '10'),
92+
(int) $this->config->getAppValue('dav', 'rateLimitPeriodCalendarCreation', '3600'),
93+
$user
94+
);
95+
} catch (RateLimitExceededException $e) {
96+
throw new TooManyRequests('Too many calendars created', 0, $e);
97+
}
98+
99+
$calendarLimit = (int) $this->config->getAppValue('dav', 'maximumCalendarsSubscriptions', '30');
100+
if ($calendarLimit === -1) {
101+
return;
102+
}
103+
$numCalendars = $this->calDavBackend->getCalendarsForUserCount('principals/users/' . $user->getUID());
104+
$numSubscriptions = $this->calDavBackend->getSubscriptionsForUserCount('principals/users/' . $user->getUID());
105+
106+
if (($numCalendars + $numSubscriptions) >= $calendarLimit) {
107+
$this->logger->warning('Maximum number of calendars/subscriptions reached', [
108+
'calendars' => $numCalendars,
109+
'subscription' => $numSubscriptions,
110+
'limit' => $calendarLimit,
111+
]);
112+
throw new Forbidden('Calendar limit reached', 0);
113+
}
114+
}
115+
}
116+
117+
}

apps/dav/lib/Server.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
use Psr\Log\LoggerInterface;
4343
use OCA\DAV\AppInfo\PluginManager;
4444
use OCA\DAV\CalDAV\BirthdayService;
45+
use OCA\DAV\CalDAV\Security\RateLimitingPlugin;
4546
use OCA\DAV\CardDAV\HasPhotoPlugin;
4647
use OCA\DAV\CardDAV\ImageExportPlugin;
4748
use OCA\DAV\CardDAV\MultiGetExportPlugin;
@@ -185,6 +186,8 @@ public function __construct(IRequest $request, string $baseUri) {
185186
\OC::$server->getConfig(),
186187
\OC::$server->getURLGenerator()
187188
));
189+
190+
$this->server->addPlugin(\OC::$server->get(RateLimitingPlugin::class));
188191
}
189192

190193
// addressbook plugins
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* @copyright 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
7+
*
8+
* @author 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
9+
*
10+
* @license GNU AGPL version 3 or any later version
11+
*
12+
* This program is free software: you can redistribute it and/or modify
13+
* it under the terms of the GNU Affero General Public License as
14+
* published by the Free Software Foundation, either version 3 of the
15+
* License, or (at your option) any later version.
16+
*
17+
* This program is distributed in the hope that it will be useful,
18+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
19+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20+
* GNU Affero General Public License for more details.
21+
*
22+
* You should have received a copy of the GNU Affero General Public License
23+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
24+
*/
25+
26+
namespace OCA\DAV\Tests\unit\CalDAV\Security;
27+
28+
use OC\Security\RateLimiting\Exception\RateLimitExceededException;
29+
use OC\Security\RateLimiting\Limiter;
30+
use OCA\DAV\CalDAV\CalDavBackend;
31+
use OCA\DAV\CalDAV\Security\RateLimitingPlugin;
32+
use OCA\DAV\Connector\Sabre\Exception\TooManyRequests;
33+
use OCP\IConfig;
34+
use OCP\IUser;
35+
use OCP\IUserManager;
36+
use PHPUnit\Framework\MockObject\MockObject;
37+
use Psr\Log\LoggerInterface;
38+
use Sabre\DAV\Exception\Forbidden;
39+
use Test\TestCase;
40+
41+
class RateLimitingPluginTest extends TestCase {
42+
43+
/** @var Limiter|MockObject */
44+
private $limiter;
45+
46+
/** @var Limiter|CalDavBackend */
47+
private $caldavBackend;
48+
49+
/** @var Limiter|IUserManager */
50+
private $userManager;
51+
52+
/** @var Limiter|LoggerInterface */
53+
private $logger;
54+
55+
/** @var Limiter|IConfig */
56+
private $config;
57+
58+
/** @var Limiter|string */
59+
private $userId = 'user123';
60+
61+
/** @var Limiter|RateLimitingPlugin */
62+
private $plugin;
63+
64+
protected function setUp(): void {
65+
parent::setUp();
66+
67+
$this->limiter = $this->createMock(Limiter::class);
68+
$this->userManager = $this->createMock(IUserManager::class);
69+
$this->caldavBackend = $this->createMock(CalDavBackend::class);
70+
$this->logger = $this->createMock(LoggerInterface::class);
71+
$this->config = $this->createMock(IConfig::class);
72+
$this->plugin = new RateLimitingPlugin(
73+
$this->limiter,
74+
$this->userManager,
75+
$this->caldavBackend,
76+
$this->logger,
77+
$this->config,
78+
$this->userId,
79+
);
80+
}
81+
82+
public function testNoUserObject(): void {
83+
$this->limiter->expects(self::never())
84+
->method('registerUserRequest');
85+
86+
$this->plugin->beforeBind('calendars/foo/cal');
87+
}
88+
89+
public function testUnrelated(): void {
90+
$user = $this->createMock(IUser::class);
91+
$this->userManager->expects(self::once())
92+
->method('get')
93+
->with($this->userId)
94+
->willReturn($user);
95+
$this->limiter->expects(self::never())
96+
->method('registerUserRequest');
97+
98+
$this->plugin->beforeBind('foo/bar');
99+
}
100+
101+
public function testRegisterCalendarCreation(): void {
102+
$user = $this->createMock(IUser::class);
103+
$this->userManager->expects(self::once())
104+
->method('get')
105+
->with($this->userId)
106+
->willReturn($user);
107+
$this->config
108+
->method('getAppValue')
109+
->with('dav')
110+
->willReturnArgument(2);
111+
$this->limiter->expects(self::once())
112+
->method('registerUserRequest')
113+
->with(
114+
'caldav-create-calendar',
115+
10,
116+
3600,
117+
$user,
118+
);
119+
120+
$this->plugin->beforeBind('calendars/foo/cal');
121+
}
122+
123+
public function testCalendarCreationRateLimitExceeded(): void {
124+
$user = $this->createMock(IUser::class);
125+
$this->userManager->expects(self::once())
126+
->method('get')
127+
->with($this->userId)
128+
->willReturn($user);
129+
$this->config
130+
->method('getAppValue')
131+
->with('dav')
132+
->willReturnArgument(2);
133+
$this->limiter->expects(self::once())
134+
->method('registerUserRequest')
135+
->with(
136+
'caldav-create-calendar',
137+
10,
138+
3600,
139+
$user,
140+
)
141+
->willThrowException(new RateLimitExceededException());
142+
$this->expectException(TooManyRequests::class);
143+
144+
$this->plugin->beforeBind('calendars/foo/cal');
145+
}
146+
147+
public function testCalendarLimitReached(): void {
148+
$user = $this->createMock(IUser::class);
149+
$this->userManager->expects(self::once())
150+
->method('get')
151+
->with($this->userId)
152+
->willReturn($user);
153+
$user->method('getUID')->willReturn('user123');
154+
$this->config
155+
->method('getAppValue')
156+
->with('dav')
157+
->willReturnArgument(2);
158+
$this->limiter->expects(self::once())
159+
->method('registerUserRequest')
160+
->with(
161+
'caldav-create-calendar',
162+
10,
163+
3600,
164+
$user,
165+
);
166+
$this->caldavBackend->expects(self::once())
167+
->method('getCalendarsForUserCount')
168+
->with('principals/users/user123')
169+
->willReturn(27);
170+
$this->caldavBackend->expects(self::once())
171+
->method('getSubscriptionsForUserCount')
172+
->with('principals/users/user123')
173+
->willReturn(3);
174+
$this->expectException(Forbidden::class);
175+
176+
$this->plugin->beforeBind('calendars/foo/cal');
177+
}
178+
179+
}

0 commit comments

Comments
 (0)