]> git.mxchange.org Git - friendica.git/blob - src/Module/OStatus/Salmon.php
The query condition for active users are unified
[friendica.git] / src / Module / OStatus / Salmon.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\OStatus;
23
24 use Friendica\App;
25 use Friendica\Core\L10n;
26 use Friendica\Core\Protocol;
27 use Friendica\Database\Database;
28 use Friendica\Model\GServer;
29 use Friendica\Model\Post;
30 use Friendica\Module\Response;
31 use Friendica\Protocol\ActivityNamespace;
32 use Friendica\Protocol\OStatus;
33 use Friendica\Util\Crypto;
34 use Friendica\Util\Network;
35 use Friendica\Network\HTTPException;
36 use Friendica\Protocol\Salmon as SalmonProtocol;
37 use Friendica\Util\Profiler;
38 use Friendica\Util\Strings;
39 use Psr\Log\LoggerInterface;
40
41 /**
42  * Technical endpoint for the Salmon protocol
43  */
44 class Salmon extends \Friendica\BaseModule
45 {
46         /** @var Database */
47         private $database;
48
49         public function __construct(Database $database, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
50         {
51                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
52
53                 $this->database = $database;
54         }
55
56         /**
57          * @param array $request
58          * @return void
59          * @throws HTTPException\AcceptedException
60          * @throws HTTPException\BadRequestException
61          * @throws HTTPException\InternalServerErrorException
62          * @throws HTTPException\OKException
63          * @throws \ImagickException
64          */
65         protected function post(array $request = [])
66         {
67                 $xml = Network::postdata();
68                 $this->logger->debug('Got request data.', ['request' => $request]);
69
70                 $nickname = $this->parameters['nickname'] ?? '';
71                 if (empty($nickname)) {
72                         throw new HTTPException\BadRequestException('nickname parameter is mandatory');
73                 }
74
75                 $this->logger->debug('New Salmon', ['nickname' => $nickname, 'xml' => $xml]);
76
77                 $importer = $this->database->selectFirst('user', [], ['nickname' => $nickname, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
78                 if (!$this->database->isResult($importer)) {
79                         throw new HTTPException\InternalServerErrorException();
80                 }
81
82                 // parse the xml
83                 $dom = simplexml_load_string($xml, 'SimpleXMLElement', 0, ActivityNamespace::SALMON_ME);
84
85                 $base = null;
86
87                 // figure out where in the DOM tree our data is hiding
88                 if (!empty($dom->provenance->data)) {
89                         $base = $dom->provenance;
90                 } elseif (!empty($dom->env->data)) {
91                         $base = $dom->env;
92                 } elseif (!empty($dom->data)) {
93                         $base = $dom;
94                 }
95
96                 if (empty($base)) {
97                         $this->logger->notice('unable to locate salmon data in xml');
98                         throw new HTTPException\BadRequestException();
99                 }
100
101                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
102                 $signature = Strings::base64UrlDecode($base->sig);
103
104                 // unpack the  data
105
106                 // strip whitespace so our data element will return to one big base64 blob
107                 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
108
109                 // stash away some other stuff for later
110
111                 $type     = $base->data[0]->attributes()->type[0];
112                 $keyhash  = $base->sig[0]->attributes()->keyhash[0] ?? '';
113                 $encoding = $base->encoding;
114                 $alg      = $base->alg;
115
116                 // Salmon magic signatures have evolved and there is no way of knowing ahead of time which
117                 // flavour we have. We'll try and verify it regardless.
118
119                 $stnet_signed_data = $data;
120
121                 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
122
123                 $compliant_format = str_replace('=', '', $signed_data);
124
125
126                 // decode the data
127                 $data = Strings::base64UrlDecode($data);
128
129                 $author      = OStatus::salmonAuthor($data, $importer);
130                 $author_link = $author["author-link"];
131                 if (!$author_link) {
132                         $this->logger->notice('Could not retrieve author URI.');
133                         throw new HTTPException\BadRequestException();
134                 }
135
136                 // Once we have the author URI, go to the web and try to find their public key
137
138                 $this->logger->notice('Fetching key for ' . $author_link);
139
140                 $key = SalmonProtocol::getKey($author_link, $keyhash);
141
142                 if (!$key) {
143                         $this->logger->notice('Could not retrieve author key.');
144                         throw new HTTPException\BadRequestException();
145                 }
146
147                 $this->logger->info('Key details', ['info' => $key]);
148
149                 $pubkey = SalmonProtocol::magicKeyToPem($key);
150
151                 // We should have everything we need now. Let's see if it verifies.
152
153                 // Try GNU Social format
154                 $verify = Crypto::rsaVerify($signed_data, $signature, $pubkey);
155                 $mode   = 1;
156
157                 if (!$verify) {
158                         $this->logger->notice('Message did not verify using protocol. Trying compliant format.');
159                         $verify = Crypto::rsaVerify($compliant_format, $signature, $pubkey);
160                         $mode   = 2;
161                 }
162
163                 if (!$verify) {
164                         $this->logger->notice('Message did not verify using padding. Trying old statusnet format.');
165                         $verify = Crypto::rsaVerify($stnet_signed_data, $signature, $pubkey);
166                         $mode   = 3;
167                 }
168
169                 if (!$verify) {
170                         $this->logger->notice('Message did not verify. Discarding.');
171                         throw new HTTPException\BadRequestException();
172                 }
173
174                 $this->logger->notice('Message verified with mode ' . $mode);
175
176
177                 /*
178                 *
179                 * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
180                 *
181                 */
182
183                 $contact = $this->database->selectFirst(
184                         'contact',
185                         [],
186                         [
187                                 "`network` IN (?, ?)
188                         AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)
189                         AND `uid` = ?",
190                                 Protocol::OSTATUS, Protocol::DFRN,
191                                 Strings::normaliseLink($author_link), $author_link, Strings::normaliseLink($author_link),
192                                 $importer['uid']
193                         ]
194                 );
195
196                 if (!empty($contact['gsid'])) {
197                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::OSTATUS);
198                 }
199
200                 // Have we ignored the person?
201                 // If so we can not accept this post.
202
203                 if (!empty($contact['blocked'])) {
204                         $this->logger->notice('Ignoring this author.');
205                         throw new HTTPException\AcceptedException();
206                 }
207
208                 // Placeholder for hub discovery.
209                 $hub = '';
210
211                 $contact = $contact ?: [];
212
213                 OStatus::import($data, $importer, $contact, $hub);
214
215                 throw new HTTPException\OKException();
216         }
217 }