]> git.mxchange.org Git - friendica.git/blob - src/Module/Magic.php
Merge pull request #13176 from MrPetovan/bug/warnings
[friendica.git] / src / Module / Magic.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Module;
23
24 use Exception;
25 use Friendica\App;
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;
39
40 /**
41  * Magic Auth (remote authentication) module.
42  *
43  * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Magic.php
44  */
45 class Magic extends BaseModule
46 {
47         /** @var App */
48         protected $app;
49         /** @var Database */
50         protected $dba;
51         /** @var ICanSendHttpRequests */
52         protected $httpClient;
53         /** @var IHandleUserSessions */
54         protected $userSession;
55
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 = [])
57         {
58                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
59
60                 $this->app         = $app;
61                 $this->dba         = $dba;
62                 $this->httpClient  = $httpClient;
63                 $this->userSession = $userSession;
64         }
65
66         protected function rawContent(array $request = [])
67         {
68                 if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
69                         $this->logger->debug('Got a HEAD request');
70                         System::exit();
71                 }
72
73                 $this->logger->debug('Invoked', ['request' => $request]);
74
75                 $addr  = $request['addr'] ?? '';
76                 $dest  = $request['dest'] ?? '';
77                 $bdest = $request['bdest'] ?? '';
78                 $owa   = intval($request['owa'] ?? 0);
79
80                 // bdest is preferred as it is hex-encoded and can survive url rewrite and argument parsing
81                 if (!empty($bdest)) {
82                         $dest = hex2bin($bdest);
83                         $this->logger->debug('bdest detected', ['dest' => $dest]);
84                 }
85
86                 if ($addr ?: $dest) {
87                         $contact = Contact::getByURL($addr ?: $dest);
88                 }
89
90                 if (empty($contact)) {
91                         if (!$owa) {
92                                 $this->logger->info('No contact record found, no oWA, redirecting to destination.', ['request' => $request, 'server' => $_SERVER, 'dest' => $dest]);
93                                 $this->app->redirect($dest);
94                         }
95                 } else {
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);
100                         }
101
102                         $this->logger->debug('Contact found', ['url' => $contact['url']]);
103                 }
104
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);
108                 }
109
110                 // OpenWebAuth
111                 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
112
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);
117                 }
118
119                 $basepath = $gserver['url'];
120
121                 $header = [
122                         'Accept'          => ['application/x-dfrn+json', 'application/x-zot+json'],
123                         'X-Open-Web-Auth' => [Strings::getRandomHex()],
124                 ];
125
126                 // Create a header that is signed with the local users private key.
127                 $header = HTTPSignature::createSig(
128                         $header,
129                         $owner['prvkey'],
130                         'acct:' . $owner['addr']
131                 );
132
133                 $this->logger->info('Fetch from remote system', ['basepath' => $basepath, 'headers' => $header]);
134
135                 // Try to get an authentication token from the other instance.
136                 try {
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);
141                 }
142                 if (!$curlResult->isSuccess()) {
143                         $this->logger->notice('OWA request failed, redirecting to destination.', ['returncode' => $curlResult->getReturnCode(), 'dest' => $dest]);
144                         System::externalRedirect($dest);
145                 }
146
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);
151                 }
152
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.
156                         $token = '';
157                         openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $owner['prvkey']);
158                 } else {
159                         $token = $j['token'];
160                 }
161                 $args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
162
163                 $this->logger->debug('Redirecting', ['path' => $dest . $args]);
164                 System::externalRedirect($dest . $args);
165         }
166 }