Skip to content

Commit c611973

Browse files
authored
Merge pull request #67089 from nextcloud/fix/dav/federated-public-access
fix(dav): scope federated and public access to shares
2 parents e44a502 + e23ea43 commit c611973

17 files changed

Lines changed: 981 additions & 29 deletions

‎apps/dav/lib/CalDAV/Federation/CalendarFederationProvider.php‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
use OCP\Federation\ICloudFederationShare;
2424
use OCP\Federation\ICloudIdManager;
2525
use OCP\Federation\IValidationAwareCloudFederationProvider;
26+
use OCP\OCM\IOCMDiscoveryService;
27+
use OCP\Security\Signature\Exceptions\SignatureException;
28+
use OCP\Security\Signature\ISignatureManager;
2629
use OCP\Share\Exceptions\ShareNotFound;
2730
use Psr\Log\LoggerInterface;
2831

@@ -38,6 +41,8 @@ public function __construct(
3841
private readonly IJobList $jobList,
3942
private readonly ICloudIdManager $cloudIdManager,
4043
private readonly FederatedCalendarInvitationService $invitationService,
44+
private readonly IOCMDiscoveryService $ocmDiscoveryService,
45+
private readonly ISignatureManager $signatureManager,
4146
) {
4247
}
4348

@@ -140,6 +145,18 @@ public function shareReceived(ICloudFederationShare $share): string {
140145
$calendar->setState(FederatedCalendarEntity::STATE_PENDING);
141146
$calendar = $this->federatedCalendarMapper->insert($calendar);
142147
} else {
148+
if (!$this->isPartyToCalendar($share, $calendar)) {
149+
$this->logger->warning('Received a federated calendar share for an existing calendar from an unrelated sender', [
150+
'calendar' => $calendar->getRemoteUrl(),
151+
'owner' => $share->getOwner(),
152+
]);
153+
throw new ProviderCouldNotAddShareException(
154+
'Calendar is already shared with the sharee',
155+
'',
156+
Http::STATUS_FORBIDDEN,
157+
);
158+
}
159+
143160
$calendar->setToken($share->getShareSecret());
144161
$calendar->setPermissions($permissions);
145162
$calendar->setComponents($components);
@@ -237,6 +254,24 @@ private function handleSyncCalendarNotification(array $notification): array {
237254
return [];
238255
}
239256

257+
/**
258+
* Owner and sharer of an incoming share are claims of the sender. Only accept changes to an
259+
* existing calendar if the share carries its current token or is signed by the hosting server.
260+
*/
261+
private function isPartyToCalendar(ICloudFederationShare $share, FederatedCalendarEntity $calendar): bool {
262+
if (hash_equals($calendar->getToken(), $share->getShareSecret())) {
263+
return true;
264+
}
265+
266+
try {
267+
$signedRequest = $this->ocmDiscoveryService->getIncomingSignedRequest($share->getOwner());
268+
return $signedRequest !== null
269+
&& $signedRequest->getOrigin() === $this->signatureManager->extractIdentityFromUri($calendar->getRemoteUrl());
270+
} catch (SignatureException) {
271+
return false;
272+
}
273+
}
274+
240275
/**
241276
* @return array{0: CalendarFederationProtocolV1, 1: string, 2: string, 3: ?string, 4: int, 5: string}|null
242277
* [parsed protocol, calendarUrl, displayName, color, access, components], or null when

‎apps/dav/lib/CalDAV/Federation/FederatedCalendarAuth.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ private function validateUserPass(
4848
$ownerPrincipalUri = $row['principaluri'];
4949
[, $ownerUserId] = \Sabre\Uri\split($ownerPrincipalUri);
5050
$shareUri = $row['uri'] . '_shared_by_' . $ownerUserId;
51-
if (str_starts_with($requestPath, "remote-calendars/$remoteUserPrincipalId/$shareUri")) {
51+
$sharePath = "remote-calendars/$remoteUserPrincipalId/$shareUri";
52+
if ($requestPath === $sharePath || str_starts_with($requestPath, "$sharePath/")) {
5253
// Yes? -> return early
5354
return $remoteUserPrincipalUri;
5455
}

‎apps/dav/lib/CalDAV/Federation/FederationSharingService.php‎

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
use OCA\DAV\CalDAV\Federation\Protocol\CalendarFederationProtocolV1;
1313
use OCA\DAV\DAV\RemoteUserPrincipalBackend;
14+
use OCA\DAV\DAV\Sharing\Backend;
1415
use OCA\DAV\DAV\Sharing\IShareable;
1516
use OCA\DAV\DAV\Sharing\SharingMapper;
1617
use OCP\AppFramework\Http;
@@ -62,7 +63,7 @@ private function decodeRemoteUserPrincipal(string $principal): ?string {
6263

6364
/**
6465
* Send a calendar share to a remote instance and create a federated share locally if it is
65-
* accepted.
66+
* accepted. Downgrading an existing share to read-only is applied locally in any case.
6667
*
6768
* @param IShareable $shareable The calendar to be shared.
6869
* @param string $principal The principal to share with (should be a remote user principal).
@@ -71,14 +72,6 @@ private function decodeRemoteUserPrincipal(string $principal): ?string {
7172
public function shareWith(IShareable $shareable, string $principal, int $access): void {
7273
$baseError = 'Failed to create federated calendar share: ';
7374

74-
if (!$this->config->isOutgoingServer2serverShareEnabled()) {
75-
$this->logger->error('cannot share with remote user because federated sharing is disabled on this instance', [
76-
'shareable' => $shareable->getName(),
77-
'encodedShareWith' => $principal,
78-
]);
79-
return;
80-
}
81-
8275
// 1. Validate share data
8376
$shareWith = $this->decodeRemoteUserPrincipal($principal);
8477
if ($shareWith === null) {
@@ -114,7 +107,43 @@ public function shareWith(IShareable $shareable, string $principal, int $access)
114107

115108
$displayName = $getProp('{DAV:}displayname') ?? '';
116109

117-
$token = $this->random->generate(32);
110+
// The remote server only accepts changes to an existing share that carry its current token
111+
$shareWithEncoded = base64_encode($shareWith);
112+
$shareWithPrincipalUri = RemoteUserPrincipalBackend::PRINCIPAL_PREFIX . '/' . $shareWithEncoded;
113+
$existingShares = $this->sharingMapper->getSharesByPrincipalsAndResource(
114+
[$shareWithPrincipalUri],
115+
$shareable->getResourceId(),
116+
'calendar',
117+
);
118+
$existingShare = $existingShares[0] ?? null;
119+
120+
// A downgrade to read-only must not depend on the remote server accepting the new offer
121+
if ($existingShare !== null
122+
&& $access === Backend::ACCESS_READ
123+
&& (int)$existingShare['access'] !== Backend::ACCESS_READ) {
124+
$this->sharingMapper->deleteShare(
125+
$shareable->getResourceId(),
126+
'calendar',
127+
$shareWithPrincipalUri,
128+
);
129+
$this->sharingMapper->shareWithToken(
130+
$shareable->getResourceId(),
131+
'calendar',
132+
Backend::ACCESS_READ,
133+
$shareWithPrincipalUri,
134+
$existingShare['token'],
135+
);
136+
}
137+
138+
if (!$this->config->isOutgoingServer2serverShareEnabled()) {
139+
$this->logger->error('cannot share with remote user because federated sharing is disabled on this instance', [
140+
'shareable' => $shareable->getName(),
141+
'encodedShareWith' => $principal,
142+
]);
143+
return;
144+
}
145+
146+
$token = $existingShare['token'] ?? $this->random->generate(32);
118147
$share = $this->federationFactory->getCloudFederationShare(
119148
$shareWith,
120149
$shareable->getName(),
@@ -131,7 +160,6 @@ public function shareWith(IShareable $shareable, string $principal, int $access)
131160
);
132161

133162
// 2. Send share to federated instance
134-
$shareWithEncoded = base64_encode($shareWith);
135163
$relativeCalendarUrl = "remote-calendars/$shareWithEncoded/" . $calendar->getName() . '_shared_by_' . $ownerUid;
136164
$calendarUrl = $this->url->linkTo('', 'remote.php') . "/dav/$relativeCalendarUrl";
137165
$calendarUrl = $this->url->getAbsoluteURL($calendarUrl);
@@ -172,7 +200,6 @@ public function shareWith(IShareable $shareable, string $principal, int $access)
172200
}
173201

174202
// 3. Create a local DAV share to track the token for authentication
175-
$shareWithPrincipalUri = RemoteUserPrincipalBackend::PRINCIPAL_PREFIX . '/' . $shareWithEncoded;
176203
$this->sharingMapper->deleteShare(
177204
$shareable->getResourceId(),
178205
'calendar',

‎apps/dav/lib/CalDAV/Federation/RemoteUserCalendarHome.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
use Psr\Log\LoggerInterface;
1616
use Sabre\CalDAV\Backend;
1717
use Sabre\CalDAV\CalendarHome;
18+
use Sabre\DAV\Exception\MethodNotAllowed;
1819
use Sabre\DAV\Exception\NotFound;
20+
use Sabre\DAV\MkCol;
1921

2022
class RemoteUserCalendarHome extends CalendarHome {
2123
public function __construct(
@@ -66,4 +68,9 @@ public function getChildren(): array {
6668

6769
return $objects;
6870
}
71+
72+
#[\Override]
73+
public function createExtendedCollection($name, MkCol $mkCol): void {
74+
throw new MethodNotAllowed('Remote users can not create calendars or subscriptions');
75+
}
6976
}

‎apps/dav/lib/CalDAV/PublicCalendarRoot.php‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,13 @@
1515
use Psr\Log\LoggerInterface;
1616
use Sabre\DAV\Collection;
1717
use Sabre\DAV\Exception\NotFound;
18+
use Sabre\DAVACL\ACLTrait;
19+
use Sabre\DAVACL\IACL;
1820
use Sabre\Uri;
1921

20-
class PublicCalendarRoot extends Collection {
22+
class PublicCalendarRoot extends Collection implements IACL {
23+
use ACLTrait;
24+
2125
public function __construct(
2226
protected CalDavBackend $caldavBackend,
2327
protected IL10N $l10n,
@@ -51,6 +55,17 @@ public function getChildren(): array {
5155
return [];
5256
}
5357

58+
#[\Override]
59+
public function getACL(): array {
60+
return [
61+
[
62+
'privilege' => '{DAV:}read',
63+
'principal' => '{DAV:}all',
64+
'protected' => true,
65+
],
66+
];
67+
}
68+
5469
/**
5570
* Checks if the public calendar should be visible or not, based on
5671
* the configuration of the `hide_disabled_user_shares` setting within

‎apps/dav/lib/Connector/Sabre/DavAclPlugin.php‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,16 @@ class DavAclPlugin extends \Sabre\DAVACL\Plugin {
4545
'{http://calendarserver.org/ns/}calendar-proxy-write-for',
4646
];
4747

48-
public function __construct() {
48+
private const PUBLIC_PRINCIPAL = 'principals/system/public';
49+
50+
/**
51+
* @param bool $restrictPublicPrincipal Grant the public principal only the
52+
* privileges given to it by name, not
53+
* those given to {DAV:}authenticated
54+
*/
55+
public function __construct(
56+
private bool $restrictPublicPrincipal = false,
57+
) {
4958
$this->hideNodesFromListings = true;
5059
$this->allowUnauthenticatedAccess = false;
5160
}
@@ -57,6 +66,31 @@ public function initialize(Server $server) {
5766
$server->on('report', [$this, 'beforeReport'], 50);
5867
}
5968

69+
#[\Override]
70+
public function getAcl($node) {
71+
$acl = parent::getAcl($node);
72+
if (!$this->isPublicPrincipalRestricted()) {
73+
return $acl;
74+
}
75+
return array_values(array_filter(
76+
$acl,
77+
static fn (array $ace): bool => $ace['principal'] !== '{DAV:}authenticated',
78+
));
79+
}
80+
81+
#[\Override]
82+
public function principalSearch(array $searchProperties, array $requestedProperties, $collectionUri = null, $test = 'allof') {
83+
if ($this->isPublicPrincipalRestricted()) {
84+
return [];
85+
}
86+
return parent::principalSearch($searchProperties, $requestedProperties, $collectionUri, $test);
87+
}
88+
89+
private function isPublicPrincipalRestricted(): bool {
90+
return $this->restrictPublicPrincipal
91+
&& $this->getCurrentUserPrincipal() === self::PUBLIC_PRINCIPAL;
92+
}
93+
6094
#[\Override]
6195
public function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
6296
$access = parent::checkPrivileges($uri, $privileges, $recursion, false);

‎apps/dav/lib/DAV/PublicAuth.php‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
namespace OCA\DAV\DAV;
1010

11+
use OCP\IUserSession;
1112
use Sabre\DAV\Auth\Backend\BackendInterface;
1213
use Sabre\HTTP\RequestInterface;
1314
use Sabre\HTTP\ResponseInterface;
@@ -17,7 +18,9 @@ class PublicAuth implements BackendInterface {
1718
/** @var string[] */
1819
private $publicURLs;
1920

20-
public function __construct() {
21+
public function __construct(
22+
private IUserSession $userSession,
23+
) {
2124
$this->publicURLs = [
2225
'public-calendars',
2326
'principals/system/public'
@@ -55,6 +58,8 @@ public function __construct() {
5558
#[\Override]
5659
public function check(RequestInterface $request, ResponseInterface $response) {
5760
if ($this->isRequestPublic($request)) {
61+
// Public requests are handled without the session's logged-in user
62+
$this->userSession->setIncognitoMode(true);
5863
return [true, 'principals/system/public'];
5964
}
6065
return [false, 'No public access to this resource.'];
@@ -74,7 +79,7 @@ public function challenge(RequestInterface $request, ResponseInterface $response
7479
private function isRequestPublic(RequestInterface $request) {
7580
$url = $request->getPath();
7681
$matchingUrls = array_filter($this->publicURLs, function ($publicUrl) use ($url) {
77-
return str_starts_with($url, $publicUrl);
82+
return $url === $publicUrl || str_starts_with($url, $publicUrl . '/');
7883
});
7984
return !empty($matchingUrls);
8085
}

‎apps/dav/lib/RootCollection.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ public function __construct() {
9999
$calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
100100
$calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
101101
$remoteUserPrincipals = new Collection($remoteUserPrincipalBackend, RemoteUserPrincipalBackend::PRINCIPAL_PREFIX);
102+
$remoteUserPrincipals->disableListing = $disableListing;
102103
$calendarSharingBackend = Server::get(Backend::class);
103104

104105
$filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');

‎apps/dav/lib/Server.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ public function __construct(
162162
));
163163
$this->server->addPlugin(new AnonymousOptionsPlugin());
164164
$authPlugin = new Plugin();
165-
$authPlugin->addBackend(new PublicAuth());
165+
$authPlugin->addBackend(new PublicAuth(\OCP\Server::get(IUserSession::class)));
166166
$this->server->addPlugin($authPlugin);
167167

168168
// allow setup of additional auth backends
@@ -198,7 +198,7 @@ public function __construct(
198198
$this->server->addPlugin(new \Sabre\DAV\Sync\Plugin());
199199

200200
// acl
201-
$acl = new DavAclPlugin();
201+
$acl = new DavAclPlugin(restrictPublicPrincipal: true);
202202
$acl->principalCollectionSet = [
203203
'principals/users',
204204
'principals/groups',

0 commit comments

Comments
 (0)