]> git.mxchange.org Git - friendica.git/blob - src/Module/OStatus/Salmon.php
Add new OStatus\Salmon module class
[friendica.git] / src / Module / OStatus / Salmon.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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 rawContent(array $request = [])
66         {
67                 $xml = Network::postdata();
68
69                 $this->logger->debug('New Salmon', ['nickname' => $this->parameters['nickname'], 'xml' => $xml]);
70
71                 // Despite having a route with a mandatory nickname parameter, this method can also be called from
72                 // \Friendica\Module\DFRN\Notify->post where the same parameter is optional 🤷‍
73                 $nickname = $this->parameters['nickname'] ?? '';
74
75                 $importer = $this->database->selectFirst('user', [], ['nickname' => $nickname, 'account_expired' => false, 'account_removed' => false]);
76                 if (!$this->database->isResult($importer)) {
77                         throw new HTTPException\InternalServerErrorException();
78                 }
79
80                 // parse the xml
81                 $dom = simplexml_load_string($xml, 'SimpleXMLElement', 0, ActivityNamespace::SALMON_ME);
82
83                 $base = null;
84
85                 // figure out where in the DOM tree our data is hiding
86                 if (!empty($dom->provenance->data)) {
87                         $base = $dom->provenance;
88                 } elseif (!empty($dom->env->data)) {
89                         $base = $dom->env;
90                 } elseif (!empty($dom->data)) {
91                         $base = $dom;
92                 }
93
94                 if (empty($base)) {
95                         $this->logger->notice('unable to locate salmon data in xml');
96                         throw new HTTPException\BadRequestException();
97                 }
98
99                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
100                 $signature = Strings::base64UrlDecode($base->sig);
101
102                 // unpack the  data
103
104                 // strip whitespace so our data element will return to one big base64 blob
105                 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
106
107                 // stash away some other stuff for later
108
109                 $type     = $base->data[0]->attributes()->type[0];
110                 $keyhash  = $base->sig[0]->attributes()->keyhash[0] ?? '';
111                 $encoding = $base->encoding;
112                 $alg      = $base->alg;
113
114                 // Salmon magic signatures have evolved and there is no way of knowing ahead of time which
115                 // flavour we have. We'll try and verify it regardless.
116
117                 $stnet_signed_data = $data;
118
119                 $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
120
121                 $compliant_format = str_replace('=', '', $signed_data);
122
123
124                 // decode the data
125                 $data = Strings::base64UrlDecode($data);
126
127                 $author      = OStatus::salmonAuthor($data, $importer);
128                 $author_link = $author["author-link"];
129                 if (!$author_link) {
130                         $this->logger->notice('Could not retrieve author URI.');
131                         throw new HTTPException\BadRequestException();
132                 }
133
134                 // Once we have the author URI, go to the web and try to find their public key
135
136                 $this->logger->notice('Fetching key for ' . $author_link);
137
138                 $key = SalmonProtocol::getKey($author_link, $keyhash);
139
140                 if (!$key) {
141                         $this->logger->notice('Could not retrieve author key.');
142                         throw new HTTPException\BadRequestException();
143                 }
144
145                 $key_info = explode('.', $key);
146
147                 $m = Strings::base64UrlDecode($key_info[1]);
148                 $e = Strings::base64UrlDecode($key_info[2]);
149
150                 $this->logger->info('Key details', ['info' => $key_info]);
151
152                 $pubkey = Crypto::meToPem($m, $e);
153
154                 // We should have everything we need now. Let's see if it verifies.
155
156                 // Try GNU Social format
157                 $verify = Crypto::rsaVerify($signed_data, $signature, $pubkey);
158                 $mode   = 1;
159
160                 if (!$verify) {
161                         $this->logger->notice('Message did not verify using protocol. Trying compliant format.');
162                         $verify = Crypto::rsaVerify($compliant_format, $signature, $pubkey);
163                         $mode   = 2;
164                 }
165
166                 if (!$verify) {
167                         $this->logger->notice('Message did not verify using padding. Trying old statusnet format.');
168                         $verify = Crypto::rsaVerify($stnet_signed_data, $signature, $pubkey);
169                         $mode   = 3;
170                 }
171
172                 if (!$verify) {
173                         $this->logger->notice('Message did not verify. Discarding.');
174                         throw new HTTPException\BadRequestException();
175                 }
176
177                 $this->logger->notice('Message verified with mode ' . $mode);
178
179
180                 /*
181                 *
182                 * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
183                 *
184                 */
185
186                 $contact = $this->database->selectFirst(
187                         'contact',
188                         [],
189                         [
190                                 "`network` IN (?, ?)
191                         AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)
192                         AND `uid` = ?",
193                 Protocol::OSTATUS, Protocol::DFRN,
194                                 Strings::normaliseLink($author_link), $author_link, Strings::normaliseLink($author_link),
195                                 $importer['uid']
196                         ]
197                 );
198
199                 if (!empty($contact['gsid'])) {
200                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::OSTATUS);
201                 }
202
203                 // Have we ignored the person?
204                 // If so we can not accept this post.
205
206                 if (!empty($contact['blocked'])) {
207                         $this->logger->notice('Ignoring this author.');
208                         throw new HTTPException\AcceptedException();
209                 }
210
211                 // Placeholder for hub discovery.
212                 $hub = '';
213
214                 $contact = $contact ?: [];
215
216                 OStatus::import($data, $importer, $contact, $hub);
217
218                 throw new HTTPException\OKException();
219         }
220 }