3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Module;
26 use Friendica\BaseModule;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Session\Capability\IHandleUserSessions;
29 use Friendica\Core\System;
30 use Friendica\Database\Database;
31 use Friendica\Model\Contact;
32 use Friendica\Model\User;
33 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
34 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
35 use Friendica\Util\HTTPSignature;
36 use Friendica\Util\Profiler;
37 use Friendica\Util\Strings;
38 use Psr\Log\LoggerInterface;
41 * Magic Auth (remote authentication) module.
43 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Magic.php
45 class Magic extends BaseModule
51 /** @var ICanSendHttpRequests */
52 protected $httpClient;
53 /** @var IHandleUserSessions */
54 protected $userSession;
56 public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, Database $dba, ICanSendHttpRequests $httpClient, IHandleUserSessions $userSession, $server, array $parameters = [])
58 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
62 $this->httpClient = $httpClient;
63 $this->userSession = $userSession;
66 protected function rawContent(array $request = [])
68 if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
69 $this->logger->debug('Got a HEAD request');
73 $this->logger->debug('Invoked', ['request' => $request]);
75 $addr = $request['addr'] ?? '';
76 $dest = $request['dest'] ?? '';
77 $bdest = $request['bdest'] ?? '';
78 $owa = intval($request['owa'] ?? 0);
80 // bdest is preferred as it is hex-encoded and can survive url rewrite and argument parsing
82 $dest = hex2bin($bdest);
83 $this->logger->debug('bdest detected', ['dest' => $dest]);
87 $contact = Contact::getByURL($addr ?: $dest);
90 if (empty($contact)) {
92 $this->logger->info('No contact record found, no oWA, redirecting to destination.', ['request' => $request, 'server' => $_SERVER, 'dest' => $dest]);
93 $this->app->redirect($dest);
96 // Redirect if the contact is already authenticated on this site.
97 if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl)) !== false) {
98 $this->logger->info('Contact is already authenticated, redirecting to destination.', ['dest' => $dest]);
99 System::externalRedirect($dest);
102 $this->logger->debug('Contact found', ['url' => $contact['url']]);
105 if (!$this->userSession->getLocalUserId() || !$owa) {
106 $this->logger->notice('Not logged in or not OWA, redirecting to destination.', ['uid' => $this->userSession->getLocalUserId(), 'owa' => $owa, 'dest' => $dest]);
107 $this->app->redirect($dest);
111 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
113 $gserver = $this->dba->selectFirst('gserver', ['url'], ['id' => $contact['gsid']]);
114 if (empty($gserver)) {
115 $this->logger->notice('Server not found, redirecting to destination.', ['gsid' => $contact['gsid'], 'dest' => $dest]);
116 System::externalRedirect($dest);
119 $basepath = $gserver['url'];
122 'Accept' => ['application/x-dfrn+json', 'application/x-zot+json'],
123 'X-Open-Web-Auth' => [Strings::getRandomHex()],
126 // Create a header that is signed with the local users private key.
127 $header = HTTPSignature::createSig(
130 'acct:' . $owner['addr']
133 $this->logger->info('Fetch from remote system', ['basepath' => $basepath, 'headers' => $header]);
135 // Try to get an authentication token from the other instance.
137 $curlResult = $this->httpClient->request('get', $basepath . '/owa', [HttpClientOptions::HEADERS => $header]);
138 } catch (Exception $exception) {
139 $this->logger->notice('URL is invalid, redirecting to destination.', ['url' => $basepath, 'error' => $exception, 'dest' => $dest]);
140 System::externalRedirect($dest);
142 if (!$curlResult->isSuccess()) {
143 $this->logger->notice('OWA request failed, redirecting to destination.', ['returncode' => $curlResult->getReturnCode(), 'dest' => $dest]);
144 System::externalRedirect($dest);
147 $j = json_decode($curlResult->getBody(), true);
148 if (empty($j) || !$j['success']) {
149 $this->logger->notice('Invalid JSON, redirecting to destination.', ['json' => $j, 'dest' => $dest]);
150 $this->app->redirect($dest);
153 if ($j['encrypted_token']) {
154 // The token is encrypted. If the local user is really the one the other instance
155 // thinks they is, the token can be decrypted with the local users public key.
157 openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $owner['prvkey']);
159 $token = $j['token'];
161 $args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
163 $this->logger->debug('Redirecting', ['path' => $dest . $args]);
164 System::externalRedirect($dest . $args);