]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Salmon.php
Don't transmit the shared attachments
[friendica.git] / src / Protocol / 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\Protocol;
23
24 use Friendica\Core\Logger;
25 use Friendica\DI;
26 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
27 use Friendica\Network\Probe;
28 use Friendica\Util\Crypto;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
31
32 /**
33  * Salmon Protocol class
34  *
35  * The Salmon Protocol is a message exchange protocol running over HTTP designed to decentralize commentary
36  * and annotations made against newsfeed articles such as blog posts.
37  */
38 class Salmon
39 {
40         /**
41          * @param string $uri     Uniform Resource Identifier
42          * @param string $keyhash encoded key
43          * @return string Key or empty string on any errors
44          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
45          */
46         public static function getKey(string $uri, string $keyhash): string
47         {
48                 $ret = [];
49
50                 Logger::info('Fetching salmon key for '.$uri);
51
52                 $arr = Probe::lrdd($uri);
53
54                 if (is_array($arr)) {
55                         foreach ($arr as $a) {
56                                 if ($a['@attributes']['rel'] === 'magic-public-key') {
57                                         $ret[] = $a['@attributes']['href'];
58                                 }
59                         }
60                 } else {
61                         return '';
62                 }
63
64                 // We have found at least one key URL
65                 // If it's inline, parse it - otherwise get the key
66
67                 if (count($ret) > 0) {
68                         for ($x = 0; $x < count($ret); $x ++) {
69                                 if (substr($ret[$x], 0, 5) === 'data:') {
70                                         if (strstr($ret[$x], ',')) {
71                                                 $ret[$x] = substr($ret[$x], strpos($ret[$x], ',') + 1);
72                                         } else {
73                                                 $ret[$x] = substr($ret[$x], 5);
74                                         }
75                                 } elseif (Strings::normaliseLink($ret[$x]) == 'http://') {
76                                         $ret[$x] = DI::httpClient()->fetch($ret[$x], HttpClientAccept::MAGIC_KEY);
77                                         Logger::debug('Fetched public key', ['url' => $ret[$x]]);
78                                 }
79                         }
80                 }
81
82
83                 Logger::notice('Key located', ['ret' => $ret]);
84
85                 if (count($ret) == 1) {
86                         /* We only found one one key so we don't care if the hash matches.
87                          * If it's the wrong key we'll find out soon enough because
88                          * message verification will fail. This also covers some older
89                          * software which don't supply a keyhash. As long as they only
90                          * have one key we'll be right.
91                          */
92                         return (string) $ret[0];
93                 } else {
94                         foreach ($ret as $a) {
95                                 $hash = Strings::base64UrlEncode(hash('sha256', $a));
96                                 if ($hash == $keyhash) {
97                                         return $a;
98                                 }
99                         }
100                 }
101
102                 return '';
103         }
104
105         /**
106          * @param array  $owner owner
107          * @param string $url   url
108          * @param string $slap  slap
109          * @return integer
110          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
111          */
112         public static function slapper(array $owner, string $url, string $slap): int
113         {
114                 // does contact have a salmon endpoint?
115
116                 if (!strlen($url)) {
117                         return -1;
118                 }
119
120                 if (!$owner['sprvkey']) {
121                         Logger::notice(sprintf("user '%s' (%d) does not have a salmon private key. Send failed.",
122                         $owner['name'], $owner['uid']));
123                         return -1;
124                 }
125
126                 Logger::info('slapper called for '.$url.'. Data: ' . $slap);
127
128                 // create a magic envelope
129
130                 $data      = Strings::base64UrlEncode($slap);
131                 $data_type = 'application/atom+xml';
132                 $encoding  = 'base64url';
133                 $algorithm = 'RSA-SHA256';
134                 $keyhash   = Strings::base64UrlEncode(hash('sha256', self::salmonKey($owner['spubkey'])), true);
135
136                 $precomputed = '.' . Strings::base64UrlEncode($data_type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($algorithm);
137
138                 // GNU Social format
139                 $signature   = Strings::base64UrlEncode(Crypto::rsaSign($data . $precomputed, $owner['sprvkey']));
140
141                 // Compliant format
142                 $signature2  = Strings::base64UrlEncode(Crypto::rsaSign(str_replace('=', '', $data . $precomputed), $owner['sprvkey']));
143
144                 // Old Status.net format
145                 $signature3  = Strings::base64UrlEncode(Crypto::rsaSign($data, $owner['sprvkey']));
146
147                 // At first try the non compliant method that works for GNU Social
148                 $xmldata = [
149                         'me:env' => [
150                                 'me:data' => $data,
151                                 '@attributes' => ['type' => $data_type],
152                                 'me:encoding' => $encoding,
153                                 'me:alg' => $algorithm,
154                                 'me:sig' => $signature,
155                                 '@attributes2' => ['key_id' => $keyhash],
156                         ]
157                 ];
158
159                 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
160
161                 $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
162
163                 // slap them
164                 $postResult = DI::httpClient()->post($url, $salmon, [
165                         'Content-type' => 'application/magic-envelope+xml',
166                         'Content-length' => strlen($salmon),
167                 ]);
168
169                 $return_code = $postResult->getReturnCode();
170
171                 // check for success, e.g. 2xx
172
173                 if ($return_code > 299) {
174                         Logger::notice('GNU Social salmon failed. Falling back to compliant mode');
175
176                         // Now try the compliant mode that normally isn't used for GNU Social
177                         $xmldata = [
178                                 'me:env' => [
179                                         'me:data' => $data,
180                                         '@attributes' => ['type' => $data_type],
181                                         'me:encoding' => $encoding,
182                                         'me:alg' => $algorithm,
183                                         'me:sig' => $signature2,
184                                         '@attributes2' => ['key_id' => $keyhash]
185                                 ]
186                         ];
187
188                         $namespaces = ['me' => ActivityNamespace::SALMON_ME];
189
190                         $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
191
192                         // slap them
193                         $postResult = DI::httpClient()->post($url, $salmon, [
194                                 'Content-type' => 'application/magic-envelope+xml',
195                                 'Content-length' => strlen($salmon),
196                         ]);
197                         $return_code = $postResult->getReturnCode();
198                 }
199
200                 if ($return_code > 299) {
201                         Logger::notice('compliant salmon failed. Falling back to old status.net');
202
203                         // Last try. This will most likely fail as well.
204                         $xmldata = [
205                                 'me:env' => [
206                                         'me:data' => $data,
207                                         '@attributes' => ['type' => $data_type],
208                                         'me:encoding' => $encoding,
209                                         'me:alg' => $algorithm,
210                                         'me:sig' => $signature3,
211                                         '@attributes2' => ['key_id' => $keyhash],
212                                 ]
213                         ];
214
215                         $namespaces = ['me' => ActivityNamespace::SALMON_ME];
216
217                         $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
218
219                         // slap them
220                         $postResult = DI::httpClient()->post($url, $salmon, [
221                                 'Content-type' => 'application/magic-envelope+xml',
222                                 'Content-length' => strlen($salmon)]);
223                         $return_code = $postResult->getReturnCode();
224                 }
225
226                 Logger::info('slapper for '.$url.' returned ' . $return_code);
227
228                 if (! $return_code) {
229                         return -1;
230                 }
231
232                 if (($return_code == 503) && $postResult->inHeader('retry-after')) {
233                         return -1;
234                 }
235
236                 return (($return_code >= 200) && ($return_code < 300)) ? 0 : 1;
237         }
238
239         /**
240          * @param string $pubkey public key
241          * @return string
242          * @throws \Exception
243          */
244         public static function salmonKey(string $pubkey): string
245         {
246                 Crypto::pemToMe($pubkey, $modulus, $exponent);
247                 return 'RSA' . '.' . Strings::base64UrlEncode($modulus, true) . '.' . Strings::base64UrlEncode($exponent, true);
248         }
249 }