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