3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Protocol;
24 use Friendica\Core\Logger;
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;
35 * Salmon Protocol class
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.
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
48 public static function getKey(string $uri, string $keyhash): string
52 Logger::info('Fetching salmon key for '.$uri);
54 $arr = Probe::lrdd($uri);
57 foreach ($arr as $a) {
58 if ($a['@attributes']['rel'] === 'magic-public-key') {
59 $ret[] = $a['@attributes']['href'];
66 // We have found at least one key URL
67 // If it's inline, parse it - otherwise get the key
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);
75 $ret[$x] = substr($ret[$x], 5);
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]]);
85 Logger::notice('Key located', ['ret' => $ret]);
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.
94 return (string) $ret[0];
96 foreach ($ret as $a) {
97 $hash = Strings::base64UrlEncode(hash('sha256', $a));
98 if ($hash == $keyhash) {
108 * @param array $owner owner
109 * @param string $url url
110 * @param string $slap slap
112 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
114 public static function slapper(array $owner, string $url, string $slap): int
116 // does contact have a salmon endpoint?
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']));
128 Logger::info('slapper called for '.$url.'. Data: ' . $slap);
130 // create a magic envelope
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);
138 $precomputed = '.' . Strings::base64UrlEncode($data_type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($algorithm);
141 $signature = Strings::base64UrlEncode(Crypto::rsaSign($data . $precomputed, $owner['sprvkey']));
144 $signature2 = Strings::base64UrlEncode(Crypto::rsaSign(str_replace('=', '', $data . $precomputed), $owner['sprvkey']));
146 // Old Status.net format
147 $signature3 = Strings::base64UrlEncode(Crypto::rsaSign($data, $owner['sprvkey']));
149 // At first try the non compliant method that works for GNU Social
153 '@attributes' => ['type' => $data_type],
154 'me:encoding' => $encoding,
155 'me:alg' => $algorithm,
156 'me:sig' => $signature,
157 '@attributes2' => ['key_id' => $keyhash],
161 $namespaces = ['me' => ActivityNamespace::SALMON_ME];
163 $salmon = XML::fromArray($xmldata, $dummy, false, $namespaces);
166 $postResult = DI::httpClient()->post($url, $salmon, [
167 'Content-type' => 'application/magic-envelope+xml',
168 'Content-length' => strlen($salmon),
171 $return_code = $postResult->getReturnCode();
173 // check for success, e.g. 2xx
175 if ($return_code > 299) {
176 Logger::notice('GNU Social salmon failed. Falling back to compliant mode');
178 // Now try the compliant mode that normally isn't used for GNU Social
182 '@attributes' => ['type' => $data_type],
183 'me:encoding' => $encoding,
184 'me:alg' => $algorithm,
185 'me:sig' => $signature2,
186 '@attributes2' => ['key_id' => $keyhash]
190 $salmon = XML::fromArray($xmldata, $dummy, false, $namespaces);
193 $postResult = DI::httpClient()->post($url, $salmon, [
194 'Content-type' => 'application/magic-envelope+xml',
195 'Content-length' => strlen($salmon),
197 $return_code = $postResult->getReturnCode();
200 if ($return_code > 299) {
201 Logger::notice('compliant salmon failed. Falling back to old status.net');
203 // Last try. This will most likely fail as well.
207 '@attributes' => ['type' => $data_type],
208 'me:encoding' => $encoding,
209 'me:alg' => $algorithm,
210 'me:sig' => $signature3,
211 '@attributes2' => ['key_id' => $keyhash],
215 $salmon = XML::fromArray($xmldata, $dummy, false, $namespaces);
218 $postResult = DI::httpClient()->post($url, $salmon, [
219 'Content-type' => 'application/magic-envelope+xml',
220 'Content-length' => strlen($salmon)]);
221 $return_code = $postResult->getReturnCode();
224 Logger::info('slapper for '.$url.' returned ' . $return_code);
226 if (! $return_code) {
230 if (($return_code == 503) && $postResult->inHeader('retry-after')) {
234 return (($return_code >= 200) && ($return_code < 300)) ? 0 : 1;
238 * @param string $pubkey public key
242 public static function salmonKey(string $pubkey): string
244 \phpseclib3\Crypt\RSA::addFileFormat(Magic::class);
246 return PublicKeyLoader::load($pubkey)->toString('Magic');
250 * @param string $magic Magic key format starting with "RSA."
253 public static function magicKeyToPem(string $magic): string
255 \phpseclib3\Crypt\RSA::addFileFormat(Magic::class);
257 return (string) PublicKeyLoader::load($magic);