]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Salmon.php
Move ACCEPT constants to own "enum" class
[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 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, 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 $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($owner, $url, $slap)
113         {
114                 // does contact have a salmon endpoint?
115
116                 if (!strlen($url)) {
117                         return;
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;
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 = ["me:env" => ["me:data" => $data,
149                                 "@attributes" => ["type" => $data_type],
150                                 "me:encoding" => $encoding,
151                                 "me:alg" => $algorithm,
152                                 "me:sig" => $signature,
153                                 "@attributes2" => ["key_id" => $keyhash]]];
154
155                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
156
157                 $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
158
159                 // slap them
160                 $postResult = DI::httpClient()->post($url, $salmon, [
161                         'Content-type' => 'application/magic-envelope+xml',
162                         'Content-length' => strlen($salmon),
163                 ]);
164
165                 $return_code = $postResult->getReturnCode();
166
167                 // check for success, e.g. 2xx
168
169                 if ($return_code > 299) {
170                         Logger::notice('GNU Social salmon failed. Falling back to compliant mode');
171
172                         // Now try the compliant mode that normally isn't used for GNU Social
173                         $xmldata = ["me:env" => ["me:data" => $data,
174                                         "@attributes" => ["type" => $data_type],
175                                         "me:encoding" => $encoding,
176                                         "me:alg" => $algorithm,
177                                         "me:sig" => $signature2,
178                                         "@attributes2" => ["key_id" => $keyhash]]];
179
180                         $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
181
182                         $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
183
184                         // slap them
185                         $postResult = DI::httpClient()->post($url, $salmon, [
186                                 'Content-type' => 'application/magic-envelope+xml',
187                                 'Content-length' => strlen($salmon),
188                         ]);
189                         $return_code = $postResult->getReturnCode();
190                 }
191
192                 if ($return_code > 299) {
193                         Logger::notice('compliant salmon failed. Falling back to old status.net');
194
195                         // Last try. This will most likely fail as well.
196                         $xmldata = ["me:env" => ["me:data" => $data,
197                                         "@attributes" => ["type" => $data_type],
198                                         "me:encoding" => $encoding,
199                                         "me:alg" => $algorithm,
200                                         "me:sig" => $signature3,
201                                         "@attributes2" => ["key_id" => $keyhash]]];
202
203                         $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
204
205                         $salmon = XML::fromArray($xmldata, $xml, false, $namespaces);
206
207                         // slap them
208                         $postResult = DI::httpClient()->post($url, $salmon, [
209                                 'Content-type' => 'application/magic-envelope+xml',
210                                 'Content-length' => strlen($salmon)]);
211                         $return_code = $postResult->getReturnCode();
212                 }
213
214                 Logger::info('slapper for '.$url.' returned ' . $return_code);
215
216                 if (! $return_code) {
217                         return -1;
218                 }
219
220                 if (($return_code == 503) && $postResult->inHeader('retry-after')) {
221                         return -1;
222                 }
223
224                 return (($return_code >= 200) && ($return_code < 300)) ? 0 : 1;
225         }
226
227         /**
228          * @param string $pubkey public key
229          * @return string
230          * @throws \Exception
231          */
232         public static function salmonKey($pubkey)
233         {
234                 Crypto::pemToMe($pubkey, $modulus, $exponent);
235                 return 'RSA' . '.' . Strings::base64UrlEncode($modulus, true) . '.' . Strings::base64UrlEncode($exponent, true);
236         }
237 }