1
0

SystemAddressbook.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\DAV\CardDAV;
  8. use OCA\DAV\Exception\UnsupportedLimitOnInitialSyncException;
  9. use OCA\Federation\TrustedServers;
  10. use OCP\Accounts\IAccountManager;
  11. use OCP\IConfig;
  12. use OCP\IGroupManager;
  13. use OCP\IL10N;
  14. use OCP\IRequest;
  15. use OCP\IUserSession;
  16. use Sabre\CardDAV\Backend\BackendInterface;
  17. use Sabre\CardDAV\Backend\SyncSupport;
  18. use Sabre\CardDAV\Card;
  19. use Sabre\DAV\Exception\Forbidden;
  20. use Sabre\DAV\Exception\NotFound;
  21. use Sabre\VObject\Component\VCard;
  22. use Sabre\VObject\Reader;
  23. use function array_filter;
  24. use function array_intersect;
  25. use function array_unique;
  26. use function in_array;
  27. class SystemAddressbook extends AddressBook {
  28. public const URI_SHARED = 'z-server-generated--system';
  29. public function __construct(
  30. BackendInterface $carddavBackend,
  31. array $addressBookInfo,
  32. IL10N $l10n,
  33. private IConfig $config,
  34. private IUserSession $userSession,
  35. private ?IRequest $request = null,
  36. private ?TrustedServers $trustedServers = null,
  37. private ?IGroupManager $groupManager = null,
  38. ) {
  39. parent::__construct($carddavBackend, $addressBookInfo, $l10n);
  40. $this->addressBookInfo['{DAV:}displayname'] = $l10n->t('Accounts');
  41. $this->addressBookInfo['{' . Plugin::NS_CARDDAV . '}addressbook-description'] = $l10n->t('System address book which holds all accounts');
  42. }
  43. /**
  44. * No checkbox checked -> Show only the same user
  45. * 'Allow username autocompletion in share dialog' -> show everyone
  46. * 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users within the same groups' -> show only users in intersecting groups
  47. * 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users based on phone number integration' -> show only the same user
  48. * 'Allow username autocompletion in share dialog' + 'Allow username autocompletion to users within the same groups' + 'Allow username autocompletion to users based on phone number integration' -> show only users in intersecting groups
  49. */
  50. public function getChildren() {
  51. $shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  52. $shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  53. $shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  54. $user = $this->userSession->getUser();
  55. if (!$user) {
  56. // Should never happen because we don't allow anonymous access
  57. return [];
  58. }
  59. if ($user->getBackendClassName() === 'Guests' || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
  60. $name = SyncService::getCardUri($user);
  61. try {
  62. return [parent::getChild($name)];
  63. } catch (NotFound $e) {
  64. return [];
  65. }
  66. }
  67. if ($shareEnumerationGroup) {
  68. if ($this->groupManager === null) {
  69. // Group manager is not available, so we can't determine which data is safe
  70. return [];
  71. }
  72. $groups = $this->groupManager->getUserGroups($user);
  73. $names = [];
  74. foreach ($groups as $group) {
  75. $users = $group->getUsers();
  76. foreach ($users as $groupUser) {
  77. if ($groupUser->getBackendClassName() === 'Guests') {
  78. continue;
  79. }
  80. $names[] = SyncService::getCardUri($groupUser);
  81. }
  82. }
  83. return parent::getMultipleChildren(array_unique($names));
  84. }
  85. $children = parent::getChildren();
  86. return array_filter($children, function (Card $child) {
  87. // check only for URIs that begin with Guests:
  88. return !str_starts_with($child->getName(), 'Guests:');
  89. });
  90. }
  91. /**
  92. * @param array $paths
  93. * @return Card[]
  94. * @throws NotFound
  95. */
  96. public function getMultipleChildren($paths): array {
  97. $shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  98. $shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  99. $shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  100. $user = $this->userSession->getUser();
  101. if (($user !== null && $user->getBackendClassName() === 'Guests') || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
  102. // No user or cards with no access
  103. if ($user === null || !in_array(SyncService::getCardUri($user), $paths, true)) {
  104. return [];
  105. }
  106. // Only return the own card
  107. try {
  108. return [parent::getChild(SyncService::getCardUri($user))];
  109. } catch (NotFound $e) {
  110. return [];
  111. }
  112. }
  113. if ($shareEnumerationGroup) {
  114. if ($this->groupManager === null || $user === null) {
  115. // Group manager or user is not available, so we can't determine which data is safe
  116. return [];
  117. }
  118. $groups = $this->groupManager->getUserGroups($user);
  119. $allowedNames = [];
  120. foreach ($groups as $group) {
  121. $users = $group->getUsers();
  122. foreach ($users as $groupUser) {
  123. if ($groupUser->getBackendClassName() === 'Guests') {
  124. continue;
  125. }
  126. $allowedNames[] = SyncService::getCardUri($groupUser);
  127. }
  128. }
  129. return parent::getMultipleChildren(array_intersect($paths, $allowedNames));
  130. }
  131. if (!$this->isFederation()) {
  132. return parent::getMultipleChildren($paths);
  133. }
  134. $objs = $this->carddavBackend->getMultipleCards($this->addressBookInfo['id'], $paths);
  135. $children = [];
  136. /** @var array $obj */
  137. foreach ($objs as $obj) {
  138. if (empty($obj)) {
  139. continue;
  140. }
  141. $carddata = $this->extractCarddata($obj);
  142. if (empty($carddata)) {
  143. continue;
  144. } else {
  145. $obj['carddata'] = $carddata;
  146. }
  147. $children[] = new Card($this->carddavBackend, $this->addressBookInfo, $obj);
  148. }
  149. return $children;
  150. }
  151. /**
  152. * @param string $name
  153. * @return Card
  154. * @throws NotFound
  155. * @throws Forbidden
  156. */
  157. public function getChild($name): Card {
  158. $user = $this->userSession->getUser();
  159. $shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  160. $shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  161. $shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  162. if (($user !== null && $user->getBackendClassName() === 'Guests') || !$shareEnumeration || (!$shareEnumerationGroup && $shareEnumerationPhone)) {
  163. $ownName = $user !== null ? SyncService::getCardUri($user) : null;
  164. if ($ownName === $name) {
  165. return parent::getChild($name);
  166. }
  167. throw new Forbidden();
  168. }
  169. if ($shareEnumerationGroup) {
  170. if ($user === null || $this->groupManager === null) {
  171. // Group manager is not available, so we can't determine which data is safe
  172. throw new Forbidden();
  173. }
  174. $groups = $this->groupManager->getUserGroups($user);
  175. foreach ($groups as $group) {
  176. foreach ($group->getUsers() as $groupUser) {
  177. if ($groupUser->getBackendClassName() === 'Guests') {
  178. continue;
  179. }
  180. $otherName = SyncService::getCardUri($groupUser);
  181. if ($otherName === $name) {
  182. return parent::getChild($name);
  183. }
  184. }
  185. }
  186. throw new Forbidden();
  187. }
  188. if (!$this->isFederation()) {
  189. return parent::getChild($name);
  190. }
  191. $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'], $name);
  192. if (!$obj) {
  193. throw new NotFound('Card not found');
  194. }
  195. $carddata = $this->extractCarddata($obj);
  196. if (empty($carddata)) {
  197. throw new Forbidden();
  198. } else {
  199. $obj['carddata'] = $carddata;
  200. }
  201. return new Card($this->carddavBackend, $this->addressBookInfo, $obj);
  202. }
  203. /**
  204. * @throws UnsupportedLimitOnInitialSyncException
  205. */
  206. public function getChanges($syncToken, $syncLevel, $limit = null) {
  207. if (!$syncToken && $limit) {
  208. throw new UnsupportedLimitOnInitialSyncException();
  209. }
  210. if (!$this->carddavBackend instanceof SyncSupport) {
  211. return null;
  212. }
  213. if (!$this->isFederation()) {
  214. return parent::getChanges($syncToken, $syncLevel, $limit);
  215. }
  216. $changed = $this->carddavBackend->getChangesForAddressBook(
  217. $this->addressBookInfo['id'],
  218. $syncToken,
  219. $syncLevel,
  220. $limit
  221. );
  222. if (empty($changed)) {
  223. return $changed;
  224. }
  225. $added = $modified = $deleted = [];
  226. foreach ($changed['added'] as $uri) {
  227. try {
  228. $this->getChild($uri);
  229. $added[] = $uri;
  230. } catch (NotFound|Forbidden $e) {
  231. $deleted[] = $uri;
  232. }
  233. }
  234. foreach ($changed['modified'] as $uri) {
  235. try {
  236. $this->getChild($uri);
  237. $modified[] = $uri;
  238. } catch (NotFound|Forbidden $e) {
  239. $deleted[] = $uri;
  240. }
  241. }
  242. $changed['added'] = $added;
  243. $changed['modified'] = $modified;
  244. $changed['deleted'] = $deleted;
  245. return $changed;
  246. }
  247. private function isFederation(): bool {
  248. if ($this->trustedServers === null || $this->request === null) {
  249. return false;
  250. }
  251. /** @psalm-suppress NoInterfaceProperties */
  252. $server = $this->request->server;
  253. if (!isset($server['PHP_AUTH_USER']) || $server['PHP_AUTH_USER'] !== 'system') {
  254. return false;
  255. }
  256. /** @psalm-suppress NoInterfaceProperties */
  257. $sharedSecret = $server['PHP_AUTH_PW'] ?? null;
  258. if ($sharedSecret === null) {
  259. return false;
  260. }
  261. $servers = $this->trustedServers->getServers();
  262. $trusted = array_filter($servers, function ($trustedServer) use ($sharedSecret) {
  263. return $trustedServer['shared_secret'] === $sharedSecret;
  264. });
  265. // Authentication is fine, but it's not for a federated share
  266. if (empty($trusted)) {
  267. return false;
  268. }
  269. return true;
  270. }
  271. /**
  272. * If the validation doesn't work the card is "not found" so we
  273. * return empty carddata even if the carddata might exist in the local backend.
  274. * This can happen when a user sets the required properties
  275. * FN, N to a local scope only but the request is from
  276. * a federated share.
  277. *
  278. * @see https://github.com/nextcloud/server/issues/38042
  279. *
  280. * @param array $obj
  281. * @return string|null
  282. */
  283. private function extractCarddata(array $obj): ?string {
  284. $obj['acl'] = $this->getChildACL();
  285. $cardData = $obj['carddata'];
  286. /** @var VCard $vCard */
  287. $vCard = Reader::read($cardData);
  288. foreach ($vCard->children() as $child) {
  289. $scope = $child->offsetGet('X-NC-SCOPE');
  290. if ($scope !== null && $scope->getValue() === IAccountManager::SCOPE_LOCAL) {
  291. $vCard->remove($child);
  292. }
  293. }
  294. $messages = $vCard->validate();
  295. if (!empty($messages)) {
  296. return null;
  297. }
  298. return $vCard->serialize();
  299. }
  300. /**
  301. * @return mixed
  302. * @throws Forbidden
  303. */
  304. public function delete() {
  305. if ($this->isFederation()) {
  306. parent::delete();
  307. }
  308. throw new Forbidden();
  309. }
  310. public function getACL() {
  311. return array_filter(parent::getACL(), function ($acl) {
  312. if (in_array($acl['privilege'], ['{DAV:}write', '{DAV:}all'], true)) {
  313. return false;
  314. }
  315. return true;
  316. });
  317. }
  318. }