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