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