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