]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Salmon.php
12d05f9b3d029db2c5334a1e6047c312789b30f4
[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\HttpClient;
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 mixed
44          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
45          */
46         public static function getKey($uri, $keyhash)
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], 0, HttpClient::ACCEPT_DEFAULT);
77                                 }
78                         }
79                 }
80
81
82                 Logger::notice('Key located', ['ret' => $ret]);
83
84                 if (count($ret) == 1) {
85                         // We only found one one key so we don't care if the hash matches.
86                         // If it's the wrong key we'll find out soon enough because
87                         // message verification will fail. This also covers some older
88                         // software which don't supply a keyhash. As long as they only
89                         // have one key we'll be right.
90
91                         return $ret[0];
92                 } else {
93                         foreach ($ret as $a) {
94                                 $hash = Strings::base64UrlEncode(hash('sha256', $a));
95                                 if ($hash == $keyhash) {
96                                         return $a;
97                                 }
98                         }
99                 }
100
101                 return '';
102         }
103
104         /**
105          * @param array  $owner owner
106          * @param string $url   url
107          * @param string $slap  slap
108          * @return integer
109          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110          */
111         public static function slapper($owner, $url, $slap)
112         {
113                 // does contact have a salmon endpoint?
114
115                 if (!strlen($url)) {
116                         return;
117                 }
118
119                 if (!$owner['sprvkey']) {
120                         Logger::notice(sprintf("user '%s' (%d) does not have a salmon private key. Send failed.",
121                         $owner['name'], $owner['uid']));
122                         return;
123                 }
124
125                 Logger::info('slapper called for '.$url.'. Data: ' . $slap);
126
127                 // create a magic envelope
128
129                 $data      = Strings::base64UrlEncode($slap);
130                 $data_type = 'application/atom+xml';
131                 $encoding  = 'base64url';
132                 $algorithm = 'RSA-SHA256';
133                 $keyhash   = Strings::base64UrlEncode(hash('sha256', self::salmonKey($owner['spubkey'])), true);
134
135                 $precomputed = '.' . Strings::base64UrlEncode($data_type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($algorithm);
136
137                 // GNU Social format
138                 $signature   = Strings::base64UrlEncode(Crypto::rsaSign($data . $precomputed, $owner['sprvkey']));
139
140                 // Compliant format
141                 $signature2  = Strings::base64UrlEncode(Crypto::rsaSign(str_replace('=', '', $data . $precomputed), $owner['sprvkey']));
142
143                 // Old Status.net format
144                 $signature3  = Strings::base64UrlEncode(Crypto::rsaSign($data, $owner['sprvkey']));
145
146                 // At first try the non compliant method that works for GNU Social
147                 $xmldata = ["me:env" => ["me:data" => $data,
148                                 "@attributes" => ["type" => $data_type],
149                                 "me:encoding" => $encoding,
150                                 "me:alg" => $algorithm,
151                                 "me:sig" => $signature,
152                                 "@attributes2" => ["key_id" => $keyhash]]];
153
154                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
155
156                 $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
157
158                 // slap them
159                 $postResult = DI::httpClient()->post($url, $salmon, [
160                         'Content-type' => 'application/magic-envelope+xml',
161                         'Content-length' => strlen($salmon),
162                 ]);
163
164                 $return_code = $postResult->getReturnCode();
165
166                 // check for success, e.g. 2xx
167
168                 if ($return_code > 299) {
169                         Logger::notice('GNU Social salmon failed. Falling back to compliant mode');
170
171                         // Now try the compliant mode that normally isn't used for GNU Social
172                         $xmldata = ["me:env" => ["me:data" => $data,
173                                         "@attributes" => ["type" => $data_type],
174                                         "me:encoding" => $encoding,
175                                         "me:alg" => $algorithm,
176                                         "me:sig" => $signature2,
177                                         "@attributes2" => ["key_id" => $keyhash]]];
178
179                         $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
180
181                         $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
182
183                         // slap them
184                         $postResult = DI::httpClient()->post($url, $salmon, [
185                                 'Content-type' => 'application/magic-envelope+xml',
186                                 'Content-length' => strlen($salmon),
187                         ]);
188                         $return_code = $postResult->getReturnCode();
189                 }
190
191                 if ($return_code > 299) {
192                         Logger::notice('compliant salmon failed. Falling back to old status.net');
193
194                         // Last try. This will most likely fail as well.
195                         $xmldata = ["me:env" => ["me:data" => $data,
196                                         "@attributes" => ["type" => $data_type],
197                                         "me:encoding" => $encoding,
198                                         "me:alg" => $algorithm,
199                                         "me:sig" => $signature3,
200                                         "@attributes2" => ["key_id" => $keyhash]]];
201
202                         $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
203
204                         $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
205
206                         // slap them
207                         $postResult = DI::httpClient()->post($url, $salmon, [
208                                 'Content-type' => 'application/magic-envelope+xml',
209                                 'Content-length' => strlen($salmon)]);
210                         $return_code = $postResult->getReturnCode();
211                 }
212
213                 Logger::info('slapper for '.$url.' returned ' . $return_code);
214
215                 if (! $return_code) {
216                         return -1;
217                 }
218
219                 if (($return_code == 503) && $postResult->inHeader('retry-after')) {
220                         return -1;
221                 }
222
223                 return (($return_code >= 200) && ($return_code < 300)) ? 0 : 1;
224         }
225
226         /**
227          * @param string $pubkey public key
228          * @return string
229          * @throws \Exception
230          */
231         public static function salmonKey($pubkey)
232         {
233                 Crypto::pemToMe($pubkey, $modulus, $exponent);
234                 return 'RSA' . '.' . Strings::base64UrlEncode($modulus, true) . '.' . Strings::base64UrlEncode($exponent, true);
235         }
236 }