TrustedServers.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\Federation;
  29. use OCA\Federation\BackgroundJob\RequestSharedSecret;
  30. use OCP\AppFramework\Http;
  31. use OCP\AppFramework\Utility\ITimeFactory;
  32. use OCP\BackgroundJob\IJobList;
  33. use OCP\DB\Exception;
  34. use OCP\EventDispatcher\IEventDispatcher;
  35. use OCP\Federation\Events\TrustedServerRemovedEvent;
  36. use OCP\HintException;
  37. use OCP\Http\Client\IClientService;
  38. use OCP\IConfig;
  39. use OCP\Security\ISecureRandom;
  40. use Psr\Log\LoggerInterface;
  41. class TrustedServers {
  42. /** after a user list was exchanged at least once successfully */
  43. public const STATUS_OK = 1;
  44. /** waiting for shared secret or initial user list exchange */
  45. public const STATUS_PENDING = 2;
  46. /** something went wrong, misconfigured server, software bug,... user interaction needed */
  47. public const STATUS_FAILURE = 3;
  48. /** remote server revoked access */
  49. public const STATUS_ACCESS_REVOKED = 4;
  50. private DbHandler $dbHandler;
  51. private IClientService $httpClientService;
  52. private LoggerInterface $logger;
  53. private IJobList $jobList;
  54. private ISecureRandom $secureRandom;
  55. private IConfig $config;
  56. private IEventDispatcher $dispatcher;
  57. private ITimeFactory $timeFactory;
  58. /** @var list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>|null */
  59. private ?array $trustedServersCache = null;
  60. public function __construct(
  61. DbHandler $dbHandler,
  62. IClientService $httpClientService,
  63. LoggerInterface $logger,
  64. IJobList $jobList,
  65. ISecureRandom $secureRandom,
  66. IConfig $config,
  67. IEventDispatcher $dispatcher,
  68. ITimeFactory $timeFactory
  69. ) {
  70. $this->dbHandler = $dbHandler;
  71. $this->httpClientService = $httpClientService;
  72. $this->logger = $logger;
  73. $this->jobList = $jobList;
  74. $this->secureRandom = $secureRandom;
  75. $this->config = $config;
  76. $this->dispatcher = $dispatcher;
  77. $this->timeFactory = $timeFactory;
  78. }
  79. /**
  80. * Add server to the list of trusted servers
  81. */
  82. public function addServer(string $url): int {
  83. $url = $this->updateProtocol($url);
  84. $result = $this->dbHandler->addServer($url);
  85. if ($result) {
  86. $token = $this->secureRandom->generate(16);
  87. $this->dbHandler->addToken($url, $token);
  88. $this->jobList->add(
  89. RequestSharedSecret::class,
  90. [
  91. 'url' => $url,
  92. 'token' => $token,
  93. 'created' => $this->timeFactory->getTime()
  94. ]
  95. );
  96. }
  97. return $result;
  98. }
  99. /**
  100. * Get shared secret for the given server
  101. */
  102. public function getSharedSecret(string $url): string {
  103. return $this->dbHandler->getSharedSecret($url);
  104. }
  105. /**
  106. * Add shared secret for the given server
  107. */
  108. public function addSharedSecret(string $url, string $sharedSecret): void {
  109. $this->dbHandler->addSharedSecret($url, $sharedSecret);
  110. }
  111. /**
  112. * Remove server from the list of trusted servers
  113. */
  114. public function removeServer(int $id): void {
  115. $server = $this->dbHandler->getServerById($id);
  116. $this->dbHandler->removeServer($id);
  117. $this->dispatcher->dispatchTyped(new TrustedServerRemovedEvent($server['url_hash']));
  118. }
  119. /**
  120. * Get all trusted servers
  121. *
  122. * @return list<array{id: int, url: string, url_hash: string, shared_secret: ?string, status: int, sync_token: ?string}>
  123. * @throws Exception
  124. */
  125. public function getServers() {
  126. if ($this->trustedServersCache === null) {
  127. $this->trustedServersCache = $this->dbHandler->getAllServer();
  128. }
  129. return $this->trustedServersCache;
  130. }
  131. /**
  132. * Check if given server is a trusted Nextcloud server
  133. */
  134. public function isTrustedServer(string $url): bool {
  135. return $this->dbHandler->serverExists($url);
  136. }
  137. /**
  138. * Set server status
  139. */
  140. public function setServerStatus(string $url, int $status): void {
  141. $this->dbHandler->setServerStatus($url, $status);
  142. }
  143. /**
  144. * Get server status
  145. */
  146. public function getServerStatus(string $url): int {
  147. return $this->dbHandler->getServerStatus($url);
  148. }
  149. /**
  150. * Check if URL point to a ownCloud/Nextcloud server
  151. */
  152. public function isNextcloudServer(string $url): bool {
  153. $isValidNextcloud = false;
  154. $client = $this->httpClientService->newClient();
  155. try {
  156. $result = $client->get(
  157. $url . '/status.php',
  158. [
  159. 'timeout' => 3,
  160. 'connect_timeout' => 3,
  161. ]
  162. );
  163. if ($result->getStatusCode() === Http::STATUS_OK) {
  164. $body = $result->getBody();
  165. if (is_resource($body)) {
  166. $body = stream_get_contents($body) ?: '';
  167. }
  168. $isValidNextcloud = $this->checkNextcloudVersion($body);
  169. }
  170. } catch (\Exception $e) {
  171. $this->logger->error('No Nextcloud server.', [
  172. 'app' => 'federation',
  173. 'exception' => $e,
  174. ]);
  175. return false;
  176. }
  177. return $isValidNextcloud;
  178. }
  179. /**
  180. * Check if ownCloud/Nextcloud version is >= 9.0
  181. * @throws HintException
  182. */
  183. protected function checkNextcloudVersion(string $status): bool {
  184. $decoded = json_decode($status, true);
  185. if (!empty($decoded) && isset($decoded['version'])) {
  186. if (!version_compare($decoded['version'], '9.0.0', '>=')) {
  187. throw new HintException('Remote server version is too low. 9.0 is required.');
  188. }
  189. return true;
  190. }
  191. return false;
  192. }
  193. /**
  194. * Check if the URL contain a protocol, if not add https
  195. */
  196. protected function updateProtocol(string $url): string {
  197. if (
  198. strpos($url, 'https://') === 0
  199. || strpos($url, 'http://') === 0
  200. ) {
  201. return $url;
  202. }
  203. return 'https://' . $url;
  204. }
  205. }