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