You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GetSharedSecret.php 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Robin Appelman <robin@icewind.nl>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OCA\Federation\BackgroundJob;
  31. use GuzzleHttp\Exception\ClientException;
  32. use GuzzleHttp\Exception\RequestException;
  33. use OCA\Federation\TrustedServers;
  34. use OCP\AppFramework\Http;
  35. use OCP\AppFramework\Utility\ITimeFactory;
  36. use OCP\BackgroundJob\IJobList;
  37. use OCP\BackgroundJob\Job;
  38. use OCP\Http\Client\IClient;
  39. use OCP\Http\Client\IClientService;
  40. use OCP\Http\Client\IResponse;
  41. use OCP\ILogger;
  42. use OCP\IURLGenerator;
  43. use OCP\OCS\IDiscoveryService;
  44. /**
  45. * Class GetSharedSecret
  46. *
  47. * request shared secret from remote Nextcloud
  48. *
  49. * @package OCA\Federation\Backgroundjob
  50. */
  51. class GetSharedSecret extends Job {
  52. /** @var IClient */
  53. private $httpClient;
  54. /** @var IJobList */
  55. private $jobList;
  56. /** @var IURLGenerator */
  57. private $urlGenerator;
  58. /** @var TrustedServers */
  59. private $trustedServers;
  60. /** @var IDiscoveryService */
  61. private $ocsDiscoveryService;
  62. /** @var ILogger */
  63. private $logger;
  64. /** @var bool */
  65. protected $retainJob = false;
  66. private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
  67. /** @var int 30 day = 2592000sec */
  68. private $maxLifespan = 2592000;
  69. /**
  70. * RequestSharedSecret constructor.
  71. *
  72. * @param IClientService $httpClientService
  73. * @param IURLGenerator $urlGenerator
  74. * @param IJobList $jobList
  75. * @param TrustedServers $trustedServers
  76. * @param ILogger $logger
  77. * @param IDiscoveryService $ocsDiscoveryService
  78. * @param ITimeFactory $timeFactory
  79. */
  80. public function __construct(
  81. IClientService $httpClientService,
  82. IURLGenerator $urlGenerator,
  83. IJobList $jobList,
  84. TrustedServers $trustedServers,
  85. ILogger $logger,
  86. IDiscoveryService $ocsDiscoveryService,
  87. ITimeFactory $timeFactory
  88. ) {
  89. parent::__construct($timeFactory);
  90. $this->logger = $logger;
  91. $this->httpClient = $httpClientService->newClient();
  92. $this->jobList = $jobList;
  93. $this->urlGenerator = $urlGenerator;
  94. $this->ocsDiscoveryService = $ocsDiscoveryService;
  95. $this->trustedServers = $trustedServers;
  96. }
  97. /**
  98. * run the job, then remove it from the joblist
  99. *
  100. * @param IJobList $jobList
  101. * @param ILogger|null $logger
  102. */
  103. public function execute(IJobList $jobList, ILogger $logger = null) {
  104. $target = $this->argument['url'];
  105. // only execute if target is still in the list of trusted domains
  106. if ($this->trustedServers->isTrustedServer($target)) {
  107. $this->parentExecute($jobList, $logger);
  108. }
  109. $jobList->remove($this, $this->argument);
  110. if ($this->retainJob) {
  111. $this->reAddJob($this->argument);
  112. }
  113. }
  114. /**
  115. * call execute() method of parent
  116. *
  117. * @param IJobList $jobList
  118. * @param ILogger $logger
  119. */
  120. protected function parentExecute($jobList, $logger = null) {
  121. parent::execute($jobList, $logger);
  122. }
  123. protected function run($argument) {
  124. $target = $argument['url'];
  125. $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
  126. $currentTime = $this->time->getTime();
  127. $source = $this->urlGenerator->getAbsoluteURL('/');
  128. $source = rtrim($source, '/');
  129. $token = $argument['token'];
  130. // kill job after 30 days of trying
  131. $deadline = $currentTime - $this->maxLifespan;
  132. if ($created < $deadline) {
  133. $this->retainJob = false;
  134. $this->trustedServers->setServerStatus($target,TrustedServers::STATUS_FAILURE);
  135. return;
  136. }
  137. $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
  138. $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
  139. // make sure that we have a well formatted url
  140. $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
  141. $result = null;
  142. try {
  143. $result = $this->httpClient->get(
  144. $url,
  145. [
  146. 'query' =>
  147. [
  148. 'url' => $source,
  149. 'token' => $token,
  150. 'format' => 'json',
  151. ],
  152. 'timeout' => 3,
  153. 'connect_timeout' => 3,
  154. ]
  155. );
  156. $status = $result->getStatusCode();
  157. } catch (ClientException $e) {
  158. $status = $e->getCode();
  159. if ($status === Http::STATUS_FORBIDDEN) {
  160. $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
  161. } else {
  162. $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
  163. }
  164. } catch (RequestException $e) {
  165. $status = -1; // There is no status code if we could not connect
  166. $this->logger->logException($e, [
  167. 'message' => 'Could not connect to ' . $target,
  168. 'level' => ILogger::INFO,
  169. 'app' => 'federation',
  170. ]);
  171. } catch (\Throwable $e) {
  172. $status = Http::STATUS_INTERNAL_SERVER_ERROR;
  173. $this->logger->logException($e, ['app' => 'federation']);
  174. }
  175. // if we received a unexpected response we try again later
  176. if (
  177. $status !== Http::STATUS_OK
  178. && $status !== Http::STATUS_FORBIDDEN
  179. ) {
  180. $this->retainJob = true;
  181. }
  182. if ($status === Http::STATUS_OK && $result instanceof IResponse) {
  183. $body = $result->getBody();
  184. $result = json_decode($body, true);
  185. if (isset($result['ocs']['data']['sharedSecret'])) {
  186. $this->trustedServers->addSharedSecret(
  187. $target,
  188. $result['ocs']['data']['sharedSecret']
  189. );
  190. } else {
  191. $this->logger->error(
  192. 'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
  193. ['app' => 'federation']
  194. );
  195. $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
  196. }
  197. }
  198. }
  199. /**
  200. * re-add background job
  201. *
  202. * @param array $argument
  203. */
  204. protected function reAddJob(array $argument) {
  205. $url = $argument['url'];
  206. $created = isset($argument['created']) ? (int)$argument['created'] : $this->time->getTime();
  207. $token = $argument['token'];
  208. $this->jobList->add(
  209. GetSharedSecret::class,
  210. [
  211. 'url' => $url,
  212. 'token' => $token,
  213. 'created' => $created
  214. ]
  215. );
  216. }
  217. }