Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 204 additions & 28 deletions apps/dav/lib/Connector/Sabre/DavAclPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,20 @@

namespace OCA\DAV\Connector\Sabre;

use OCA\DAV\CalDAV\CachedSubscription;
use OCA\DAV\CalDAV\Calendar;
use OCA\DAV\CardDAV\AddressBook;
use Sabre\CalDAV\Calendar;
use Sabre\CalDAV\CalendarHome;
use Sabre\CalDAV\Principal\User;
use Sabre\CalDAV\Xml\Request\CalendarMultiGetReport;
use Sabre\CardDAV\AddressBook;
use Sabre\CardDAV\AddressBookHome;
use Sabre\CardDAV\Xml\Request\AddressBookMultiGetReport;
use Sabre\DAV\Exception as DavException;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\INode;
use Sabre\DAV\PropFind;
use Sabre\DAV\Server;
use Sabre\DAVACL\IACL;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;

Expand All @@ -33,38 +39,27 @@ public function __construct() {
$this->allowUnauthenticatedAccess = false;
}

#[\Override]
public function initialize(Server $server) {
parent::initialize($server);
// Before the CalDAV and CardDAV plugins resolve the hrefs
$server->on('report', [$this, 'beforeReport'], 50);
}

#[\Override]
public function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) {
$access = parent::checkPrivileges($uri, $privileges, $recursion, false);
if ($access === false && $throwExceptions) {
/** @var INode $node */
$node = $this->server->tree->getNodeForPath($uri);

switch (get_class($node)) {
case AddressBook::class:
$type = 'Addressbook';
break;
case Calendar::class:
case CachedSubscription::class:
$type = 'Calendar';
break;
default:
$type = 'Node';
break;
}

if ($this->getCurrentUserPrincipal() === $node->getOwner()) {
if ($node instanceof IACL && $this->getCurrentUserPrincipal() === $node->getOwner()) {
throw new Forbidden('Access denied');
} else {
throw new NotFound(
sprintf(
"%s with name '%s' could not be found",
$type,
$node->getName()
)
);
}

if (!$this->hidesUnreadablePaths($uri)) {
throw new NotFound($this->getNotFoundMessage($uri));
}
$hiddenPath = $this->getTopmostUnreadablePath($uri);
throw new NotFound($this->getHiddenNotFoundMessage($uri, $hiddenPath, $this->server->tree->getNodeForPath($hiddenPath)));
}

return $access;
Expand Down Expand Up @@ -96,14 +91,21 @@ public function propFind(PropFind $propFind, INode $node) {
public function beforeMethod(RequestInterface $request, ResponseInterface $response) {
$path = $request->getPath();

$this->hideUnreadableIfConditions($request);
if ($request->getMethod() === 'COPY' || $request->getMethod() === 'MOVE') {
$this->hideUnreadableDestination($request);
}

// prevent the plugin from causing an unneeded overhead for file requests
if (str_starts_with($path, 'files/')) {
return;
}

$this->hideUnreadablePath($path);

parent::beforeMethod($request, $response);

if (!str_starts_with($path, 'addressbooks/') && !str_starts_with($path, 'calendars/')) {
if (!$this->hidesUnreadablePaths($path)) {
return;
}

Expand All @@ -116,4 +118,178 @@ public function beforeMethod(RequestInterface $request, ResponseInterface $respo
$this->checkPrivileges($parentName, '{DAV:}write');
}
}

/**
* Called for the request path and for every href that is expanded.
*
* @param string $path Sabre documents it as array, but passes the href
* @psalm-suppress ImplementedParamTypeMismatch
* @psalm-suppress InvalidArgument
* @throws NotFound
*/
#[\Override]
protected function expandProperties($path, array $requestedProperties, $depth) {
$this->hideUnreadablePath(trim($path, '/'));
return parent::expandProperties($path, $requestedProperties, $depth);
}

/**
* Answers requests below a collection the current user cannot read the same
* way, whether the requested node exists or not. Sabre only checks privileges
* on existing nodes.
*
* @throws NotFound
*/
private function hideUnreadablePath(string $path): void {
if (!$this->hidesUnreadablePaths($path)) {
return;
}

$principal = $this->getCurrentUserPrincipal();
if ($principal === null) {
return;
}

$existingPath = $path;
while ($existingPath !== '' && !$this->server->tree->nodeExists($existingPath)) {
[$existingPath] = \Sabre\Uri\split($existingPath);
}
if ($existingPath === '' || $this->checkPrivileges($existingPath, '{DAV:}read', self::R_PARENT, false)) {
return;
}

$hiddenPath = $this->getTopmostUnreadablePath($path);
$hiddenNode = $this->server->tree->getNodeForPath($hiddenPath);
if ($hiddenNode instanceof IACL && $hiddenNode->getOwner() === $principal) {
return;
}

throw new NotFound($this->getHiddenNotFoundMessage($path, $hiddenPath, $hiddenNode));
}

private function hidesUnreadablePaths(string $path): bool {
return str_starts_with($path, 'addressbooks/') || str_starts_with($path, 'calendars/');
}

/**
* Returns the topmost collection on $path the current user cannot read,
* or $path itself if all of them are readable.
*/
private function getTopmostUnreadablePath(string $path): string {
$hiddenPath = '';
foreach (explode('/', $path) as $segment) {
$hiddenPath = ltrim($hiddenPath . '/' . $segment, '/');
if (!$this->checkPrivileges($hiddenPath, '{DAV:}read', self::R_PARENT, false)) {
break;
}
}
return $hiddenPath;
}

/**
* Returns the not-found message for $path as if $hiddenPath did not exist.
* Homes exist for every user, so for them the child on the path is reported
* missing instead.
*/
private function getHiddenNotFoundMessage(string $path, string $hiddenPath, INode $hiddenNode): string {
if ($hiddenPath !== $path && ($hiddenNode instanceof CalendarHome || $hiddenNode instanceof AddressBookHome)) {
$child = explode('/', substr($path, strlen($hiddenPath) + 1))[0];
return $this->getNotFoundMessageForChild($hiddenNode, $child);
}
return $this->getNotFoundMessage($hiddenPath);
}

/**
* @throws NotFound
*/
public function beforeReport(string $reportName, mixed $report, string $path): void {
if (!($report instanceof CalendarMultiGetReport) && !($report instanceof AddressBookMultiGetReport)) {
return;
}

// Hrefs in an existing, readable collection are left to the tree
$readableParents = [];
foreach ($report->hrefs as $href) {
try {
$hrefPath = $this->server->calculateUri($href);
} catch (Forbidden $e) {
// hrefs outside of the base URI are rejected when the report is handled
continue;
}
if (!$this->hidesUnreadablePaths($hrefPath)) {
continue;
}

[$parent] = \Sabre\Uri\split($hrefPath);
$readableParents[$parent] ??= $this->server->tree->nodeExists($parent)
&& $this->checkPrivileges($parent, '{DAV:}read', self::R_PARENT, false);
if (!$readableParents[$parent]) {
$this->hideUnreadablePath($hrefPath);
}
}
}

/**
* @throws NotFound
*/
private function hideUnreadableIfConditions(RequestInterface $request): void {
if ($request->getHeader('If') === null) {
return;
}

try {
$conditions = $this->server->getIfConditions($request);
} catch (Forbidden $e) {
// URIs outside of the base URI are rejected when the conditions are checked
return;
}

foreach ($conditions as $condition) {
if ($condition['uri'] !== $request->getPath()) {
$this->hideUnreadablePath($condition['uri']);
}
}
}

/**
* @throws NotFound
*/
private function hideUnreadableDestination(RequestInterface $request): void {
$destination = $request->getHeader('Destination');
if ($destination === null) {
return;
}

try {
$destinationPath = $this->server->calculateUri($destination);
} catch (DavException $e) {
// Invalid destinations are rejected when the method is handled
return;
}

$this->hideUnreadablePath($destinationPath);
}

/**
* Returns the message of the exception the parent collection throws
* when the node at $uri does not exist.
*/
private function getNotFoundMessage(string $uri): string {
[$parentUri, $name] = \Sabre\Uri\split($uri);
$parent = $this->server->tree->getNodeForPath((string)$parentUri);
return $this->getNotFoundMessageForChild($parent, $name);
}

private function getNotFoundMessageForChild(INode $parent, string $name): string {
if ($parent instanceof Calendar) {
return 'Calendar object not found';
}
if ($parent instanceof AddressBook) {
return 'Card not found';
}
if ($parent instanceof AddressBookHome) {
return sprintf("Addressbook with name '%s' could not be found", $name);
}
return sprintf("Node with name '%s' could not be found", $name);
}
}
87 changes: 42 additions & 45 deletions apps/dav/lib/Connector/Sabre/Principal.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,25 +250,25 @@ protected function searchUserPrincipals(array $searchProperties, $test = 'allof'
$ignoreSecondDisplayName = $this->shareManager->ignoreSecondDisplayName();
$matchEmail = $this->shareManager->matchEmail();

// If sharing is restricted to group members only,
// return only members that have groups in common
$restrictGroups = false;
$currentUser = $this->userSession->getUser();
if ($this->shareManager->shareWithGroupMembersOnly()) {
if (!$currentUser instanceof IUser) {
return [];
}

$restrictGroups = $this->groupManager->getUserGroupIds($currentUser);
$shareWithGroupMembersOnly = $this->shareManager->shareWithGroupMembersOnly();
if ($shareWithGroupMembersOnly && !$currentUser instanceof IUser) {
return [];
}

// Groups excluded from the group members only restriction do not count as common groups
$currentUserGroups = [];
if ($limitEnumerationGroup) {
if ($currentUser instanceof IUser) {
$currentUserGroups = $this->groupManager->getUserGroupIds($currentUser);
}
if (($shareWithGroupMembersOnly || $limitEnumerationGroup) && $currentUser instanceof IUser) {
$currentUserGroups = array_values(array_diff(
$this->groupManager->getUserGroupIds($currentUser),
$this->shareManager->shareWithGroupMembersOnlyExcludeGroupsList()
));
}

// If sharing is restricted to group members only,
// return only members that have groups in common
$restrictGroups = $shareWithGroupMembersOnly ? $currentUserGroups : false;

$searchLimit = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
if ($searchLimit <= 0) {
$searchLimit = null;
Expand All @@ -289,22 +289,7 @@ protected function searchUserPrincipals(array $searchProperties, $test = 'allof'
return true;
}

if ($limitEnumerationPhone
&& $currentUser instanceof IUser
&& $this->knownUserService->isKnownToUser($currentUser->getUID(), $user->getUID())) {
// Synced phonebook match
return true;
}

if (!$limitEnumerationGroup) {
// No limitation on enumeration, all allowed
return true;
}

return !empty($currentUserGroups) && !empty(array_intersect(
$this->groupManager->getUserGroupIds($user),
$currentUserGroups
));
return $this->canEnumerateUser($currentUser, $user, $limitEnumerationGroup, $limitEnumerationPhone, $currentUserGroups);
});
}

Expand Down Expand Up @@ -342,22 +327,7 @@ protected function searchUserPrincipals(array $searchProperties, $test = 'allof'
return true;
}

if ($limitEnumerationPhone
&& $currentUser instanceof IUser
&& $this->knownUserService->isKnownToUser($currentUser->getUID(), $user->getUID())) {
// Synced phonebook match
return true;
}

if (!$limitEnumerationGroup) {
// No limitation on enumeration, all allowed
return true;
}

return !empty($currentUserGroups) && !empty(array_intersect(
$this->groupManager->getUserGroupIds($user),
$currentUserGroups
));
return $this->canEnumerateUser($currentUser, $user, $limitEnumerationGroup, $limitEnumerationPhone, $currentUserGroups);
});
}

Expand Down Expand Up @@ -406,6 +376,33 @@ protected function searchUserPrincipals(array $searchProperties, $test = 'allof'
}
}

/**
* Whether the current user may find the given user by a partial search,
* following the enumeration restrictions to groups and phone book matches
*
* @param string[] $currentUserGroups
*/
private function canEnumerateUser(?IUser $currentUser, IUser $user, bool $limitEnumerationGroup, bool $limitEnumerationPhone, array $currentUserGroups): bool {
if (!$limitEnumerationGroup && !$limitEnumerationPhone) {
// No limitation on enumeration, all allowed
return true;
}

if ($limitEnumerationPhone
&& $currentUser instanceof IUser
&& $this->knownUserService->isKnownToUser($currentUser->getUID(), $user->getUID())) {
// Synced phonebook match
return true;
}

return $limitEnumerationGroup
&& !empty($currentUserGroups)
&& !empty(array_intersect(
$this->groupManager->getUserGroupIds($user),
$currentUserGroups
));
}

/**
* @param string $prefixPath
* @param array $searchProperties
Expand Down
Loading
Loading