Merge pull request #9724 from MrPetovan/bug/notices
[friendica.git/.git] / mod / salmon.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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 use Friendica\App;
23 use Friendica\Core\Logger;
24 use Friendica\Core\Protocol;
25 use Friendica\Database\DBA;
26 use Friendica\DI;
27 use Friendica\Model\Contact;
28 use Friendica\Protocol\ActivityNamespace;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Protocol\Salmon;
31 use Friendica\Util\Crypto;
32 use Friendica\Util\Network;
33 use Friendica\Util\Strings;
34
35 function salmon_post(App $a, $xml = '') {
36
37         if (empty($xml)) {
38                 $xml = Network::postdata();
39         }
40
41         Logger::log('new salmon ' . $xml, Logger::DATA);
42
43         $nick       = (($a->argc > 1) ? Strings::escapeTags(trim($a->argv[1])) : '');
44
45         $importer = DBA::selectFirst('user', [], ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]);
46         if (! DBA::isResult($importer)) {
47                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
48         }
49
50         // parse the xml
51
52         $dom = simplexml_load_string($xml,'SimpleXMLElement',0, ActivityNamespace::SALMON_ME);
53
54         $base = null;
55
56         // figure out where in the DOM tree our data is hiding
57         if (!empty($dom->provenance->data))
58                 $base = $dom->provenance;
59         elseif (!empty($dom->env->data))
60                 $base = $dom->env;
61         elseif (!empty($dom->data))
62                 $base = $dom;
63
64         if (empty($base)) {
65                 Logger::log('unable to locate salmon data in xml ');
66                 throw new \Friendica\Network\HTTPException\BadRequestException();
67         }
68
69         // Stash the signature away for now. We have to find their key or it won't be good for anything.
70
71
72         $signature = Strings::base64UrlDecode($base->sig);
73
74         // unpack the  data
75
76         // strip whitespace so our data element will return to one big base64 blob
77         $data = str_replace([" ","\t","\r","\n"],["","","",""],$base->data);
78
79         // stash away some other stuff for later
80
81         $type = $base->data[0]->attributes()->type[0];
82         $keyhash = $base->sig[0]->attributes()->keyhash[0] ?? '';
83         $encoding = $base->encoding;
84         $alg = $base->alg;
85
86         // Salmon magic signatures have evolved and there is no way of knowing ahead of time which
87         // flavour we have. We'll try and verify it regardless.
88
89         $stnet_signed_data = $data;
90
91         $signed_data = $data  . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
92
93         $compliant_format = str_replace('=', '', $signed_data);
94
95
96         // decode the data
97         $data = Strings::base64UrlDecode($data);
98
99         $author = OStatus::salmonAuthor($data, $importer);
100         $author_link = $author["author-link"];
101
102         if(! $author_link) {
103                 Logger::log('Could not retrieve author URI.');
104                 throw new \Friendica\Network\HTTPException\BadRequestException();
105         }
106
107         // Once we have the author URI, go to the web and try to find their public key
108
109         Logger::log('Fetching key for ' . $author_link);
110
111         $key = Salmon::getKey($author_link, $keyhash);
112
113         if(! $key) {
114                 Logger::log('Could not retrieve author key.');
115                 throw new \Friendica\Network\HTTPException\BadRequestException();
116         }
117
118         $key_info = explode('.',$key);
119
120         $m = Strings::base64UrlDecode($key_info[1]);
121         $e = Strings::base64UrlDecode($key_info[2]);
122
123         Logger::info('key details', ['info' => $key_info]);
124
125         $pubkey = Crypto::meToPem($m, $e);
126
127         // We should have everything we need now. Let's see if it verifies.
128
129         // Try GNU Social format
130         $verify = Crypto::rsaVerify($signed_data, $signature, $pubkey);
131         $mode = 1;
132
133         if (! $verify) {
134                 Logger::log('message did not verify using protocol. Trying compliant format.');
135                 $verify = Crypto::rsaVerify($compliant_format, $signature, $pubkey);
136                 $mode = 2;
137         }
138
139         if (! $verify) {
140                 Logger::log('message did not verify using padding. Trying old statusnet format.');
141                 $verify = Crypto::rsaVerify($stnet_signed_data, $signature, $pubkey);
142                 $mode = 3;
143         }
144
145         if (! $verify) {
146                 Logger::log('Message did not verify. Discarding.');
147                 throw new \Friendica\Network\HTTPException\BadRequestException();
148         }
149
150         Logger::log('Message verified with mode '.$mode);
151
152
153         /*
154         *
155         * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
156         *
157         */
158
159         $r = q("SELECT * FROM `contact` WHERE `network` IN ('%s', '%s')
160                                                 AND (`nurl` = '%s' OR `alias` = '%s' OR `alias` = '%s')
161                                                 AND `uid` = %d LIMIT 1",
162                 DBA::escape(Protocol::OSTATUS),
163                 DBA::escape(Protocol::DFRN),
164                 DBA::escape(Strings::normaliseLink($author_link)),
165                 DBA::escape($author_link),
166                 DBA::escape(Strings::normaliseLink($author_link)),
167                 intval($importer['uid'])
168         );
169
170         if (!DBA::isResult($r)) {
171                 Logger::log('Author ' . $author_link . ' unknown to user ' . $importer['uid'] . '.');
172
173                 if (DI::pConfig()->get($importer['uid'], 'system', 'ostatus_autofriend')) {
174                         $result = Contact::createFromProbe($importer, $author_link);
175
176                         if ($result['success']) {
177                                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND ( `url` = '%s' OR `alias` = '%s')
178                                         AND `uid` = %d LIMIT 1",
179                                         DBA::escape(Protocol::OSTATUS),
180                                         DBA::escape($author_link),
181                                         DBA::escape($author_link),
182                                         intval($importer['uid'])
183                                 );
184                         }
185                 }
186         }
187
188         // Have we ignored the person?
189         // If so we can not accept this post.
190
191         //if((DBA::isResult($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == Contact::FOLLOWER) || ($r[0]['blocked']))) {
192         if (DBA::isResult($r) && $r[0]['blocked']) {
193                 Logger::log('Ignoring this author.');
194                 throw new \Friendica\Network\HTTPException\AcceptedException();
195         }
196
197         // Placeholder for hub discovery.
198         $hub = '';
199
200         $contact_rec = ((DBA::isResult($r)) ? $r[0] : []);
201
202         OStatus::import($data, $importer, $contact_rec, $hub);
203
204         throw new \Friendica\Network\HTTPException\OKException();
205 }