]> git.mxchange.org Git - friendica.git/blob - src/Module/Magic.php
Merge pull request #13599 from Raroun/Fix_for_Pull_Request_#13596_missing_a_hidden...
[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\GServer;
33 use Friendica\Model\User;
34 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
35 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 use Friendica\Util\HTTPSignature;
37 use Friendica\Util\Profiler;
38 use Friendica\Util\Strings;
39 use GuzzleHttp\Psr7\Uri;
40 use Psr\Log\LoggerInterface;
41
42 /**
43  * Magic Auth (remote authentication) module.
44  *
45  * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Magic.php
46  */
47 class Magic extends BaseModule
48 {
49         /** @var App */
50         protected $app;
51         /** @var Database */
52         protected $dba;
53         /** @var ICanSendHttpRequests */
54         protected $httpClient;
55         /** @var IHandleUserSessions */
56         protected $userSession;
57
58         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 = [])
59         {
60                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
61
62                 $this->app         = $app;
63                 $this->dba         = $dba;
64                 $this->httpClient  = $httpClient;
65                 $this->userSession = $userSession;
66         }
67
68         protected function rawContent(array $request = [])
69         {
70                 if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
71                         $this->logger->debug('Got a HEAD request');
72                         System::exit();
73                 }
74
75                 $this->logger->debug('Invoked', ['request' => $request]);
76
77                 $addr  = $request['addr'] ?? '';
78                 $dest  = $request['dest'] ?? '';
79                 $bdest = $request['bdest'] ?? '';
80                 $owa   = intval($request['owa'] ?? 0);
81
82                 // bdest is preferred as it is hex-encoded and can survive url rewrite and argument parsing
83                 if (!empty($bdest)) {
84                         $dest = hex2bin($bdest);
85                         $this->logger->debug('bdest detected', ['dest' => $dest]);
86                 }
87
88                 $target = $dest ?: $addr;
89
90                 if ($addr ?: $dest) {
91                         $contact = Contact::getByURL($addr ?: $dest);
92                 }
93
94                 if (empty($contact)) {
95                         if (!$owa) {
96                                 $this->logger->info('No contact record found, no oWA, redirecting to destination.', ['request' => $request, 'server' => $_SERVER, 'dest' => $dest]);
97                                 $this->app->redirect($dest);
98                         }
99                 } else {
100                         // Redirect if the contact is already authenticated on this site.
101                         if ($this->app->getContactId() && strpos($contact['nurl'], Strings::normaliseLink($this->baseUrl)) !== false) {
102                                 $this->logger->info('Contact is already authenticated, redirecting to destination.', ['dest' => $dest]);
103                                 System::externalRedirect($dest);
104                         }
105
106                         $this->logger->debug('Contact found', ['url' => $contact['url']]);
107                 }
108
109                 if (!$this->userSession->getLocalUserId() || !$owa) {
110                         $this->logger->notice('Not logged in or not OWA, redirecting to destination.', ['uid' => $this->userSession->getLocalUserId(), 'owa' => $owa, 'dest' => $dest]);
111                         $this->app->redirect($dest);
112                 }
113
114                 // OpenWebAuth
115                 $owner = User::getOwnerDataById($this->userSession->getLocalUserId());
116
117                 if (!empty($contact['gsid'])) {
118                         $gserver = $this->dba->selectFirst('gserver', ['url'], ['id' => $contact['gsid']]);
119                         if (empty($gserver)) {
120                                 $this->logger->notice('Server not found, redirecting to destination.', ['gsid' => $contact['gsid'], 'dest' => $dest]);
121                                 System::externalRedirect($dest);
122                         }
123
124                         $basepath = $gserver['url'];
125                 } elseif (GServer::check($target)) {
126                         $basepath = (string)GServer::cleanUri(new Uri($target));
127                 } else {
128                         $this->logger->notice('The target is not a server path, redirecting to destination.', ['target' => $target]);
129                         System::externalRedirect($dest);
130                 }
131
132                 $header = [
133                         'Accept'          => 'application/x-dfrn+json, application/x-zot+json',
134                         'X-Open-Web-Auth' => Strings::getRandomHex()
135                 ];
136
137                 // Create a header that is signed with the local users private key.
138                 $header = HTTPSignature::createSig(
139                         $header,
140                         $owner['prvkey'],
141                         'acct:' . $owner['addr']
142                 );
143
144                 $this->logger->info('Fetch from remote system', ['basepath' => $basepath, 'headers' => $header]);
145
146                 // Try to get an authentication token from the other instance.
147                 try {
148                         $curlResult = $this->httpClient->request('get', $basepath . '/owa', [HttpClientOptions::HEADERS => $header]);
149                 } catch (Exception $exception) {
150                         $this->logger->notice('URL is invalid, redirecting to destination.', ['url' => $basepath, 'error' => $exception, 'dest' => $dest]);
151                         System::externalRedirect($dest);
152                 }
153                 if (!$curlResult->isSuccess()) {
154                         $this->logger->notice('OWA request failed, redirecting to destination.', ['returncode' => $curlResult->getReturnCode(), 'dest' => $dest]);
155                         System::externalRedirect($dest);
156                 }
157
158                 $j = json_decode($curlResult->getBody(), true);
159                 if (empty($j) || !$j['success']) {
160                         $this->logger->notice('Invalid JSON, redirecting to destination.', ['json' => $j, 'dest' => $dest]);
161                         $this->app->redirect($dest);
162                 }
163
164                 if ($j['encrypted_token']) {
165                         // The token is encrypted. If the local user is really the one the other instance
166                         // thinks they is, the token can be decrypted with the local users public key.
167                         $token = '';
168                         openssl_private_decrypt(Strings::base64UrlDecode($j['encrypted_token']), $token, $owner['prvkey']);
169                 } else {
170                         $token = $j['token'];
171                 }
172                 $args = (strpbrk($dest, '?&') ? '&' : '?') . 'owt=' . $token;
173
174                 $this->logger->debug('Redirecting', ['path' => $dest . $args]);
175                 System::externalRedirect($dest . $args);
176         }
177 }