4 * @file src/Util/HTTPSig.php
6 namespace Friendica\Util;
8 use Friendica\Core\Config;
9 use Friendica\Database\DBM;
10 use Friendica\Util\Crypto;
11 use Friendica\Util\HTTPHeaders;
15 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
17 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
19 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
27 * Disabled until Friendica's ActivityPub implementation
30 * @see https://tools.ietf.org/html/rfc5843
32 * @param string $body The value to create the digest for
33 * @param boolean $set (optional, default true)
34 * If set send a Digest HTTP header
36 * @return string The generated digest of $body
38 // public static function generateDigest($body, $set = true)
40 // $digest = base64_encode(hash('sha256', $body, true));
43 // header('Digest: SHA-256=' . $digest);
48 // See draft-cavage-http-signatures-08
49 public static function verify($data, $key = '')
56 'header_signed' => false,
57 'header_valid' => false,
58 'content_signed' => false,
59 'content_valid' => false
62 // Decide if $data arrived via controller submission or curl.
63 if (is_array($data) && $data['header']) {
64 if (!$data['success']) {
68 $h = new HTTPHeaders($data['header']);
69 $headers = $h->fetch();
70 $body = $data['body'];
73 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
75 foreach ($_SERVER as $k => $v) {
76 if (strpos($k, 'HTTP_') === 0) {
77 $field = str_replace('_', '-', strtolower(substr($k, 5)));
78 $headers[$field] = $v;
85 if (array_key_exists('signature', $headers)) {
86 $sig_block = self::parseSigheader($headers['signature']);
87 } elseif (array_key_exists('authorization', $headers)) {
88 $sig_block = self::parseSigheader($headers['authorization']);
92 logger('no signature provided.');
96 // Warning: This log statement includes binary data
97 // logger('sig_block: ' . print_r($sig_block,true), LOGGER_DATA);
99 $result['header_signed'] = true;
101 $signed_headers = $sig_block['headers'];
102 if (!$signed_headers) {
103 $signed_headers = ['date'];
107 foreach ($signed_headers as $h) {
108 if (array_key_exists($h, $headers)) {
109 $signed_data .= $h . ': ' . $headers[$h] . "\n";
111 if (strpos($h, '.')) {
116 $signed_data = rtrim($signed_data, "\n");
119 if ($sig_block['algorithm'] === 'rsa-sha256') {
120 $algorithm = 'sha256';
122 if ($sig_block['algorithm'] === 'rsa-sha512') {
123 $algorithm = 'sha512';
126 if ($key && function_exists($key)) {
127 $result['signer'] = $sig_block['keyId'];
128 $key = $key($sig_block['keyId']);
131 // We don't use Activity Pub at the moment.
133 // $result['signer'] = $sig_block['keyId'];
134 // $key = self::getActivitypubKey($sig_block['keyId']);
141 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
143 logger('verified: ' . $x, LOGGER_DEBUG);
150 $result['header_valid'] = true;
153 if (in_array('digest', $signed_headers)) {
154 $result['content_signed'] = true;
155 $digest = explode('=', $headers['digest']);
157 if ($digest[0] === 'SHA-256') {
160 if ($digest[0] === 'SHA-512') {
164 // The explode operation will have stripped the '=' padding, so compare against unpadded base64.
165 if (rtrim(base64_encode(hash($hashalg, $body, true)), '=') === $digest[1]) {
166 $result['content_valid'] = true;
170 logger('Content_Valid: ' . $result['content_valid']);
176 * Fetch the public key for Activity Pub contact.
178 * @param string|int The identifier (contact addr or contact ID).
179 * @return string|boolean The public key or false on failure.
181 private static function getActivitypubKey($id)
183 if (strpos($id, 'acct:') === 0) {
184 $contact = dba::selectFirst('contact', ['pubkey'], ['uid' => 0, 'addr' => str_replace('acct:', '', $id)]);
186 $contact = dba::selectFirst('contact', ['pubkey'], ['id' => $id, 'network' => 'activitypub']);
189 if (DBM::is_result($contact)) {
190 return $contact['pubkey'];
193 if(function_exists('as_fetch')) {
198 $j = json_decode($r, true);
200 if (array_key_exists('publicKey', $j) && array_key_exists('publicKeyPem', $j['publicKey'])) {
201 if ((array_key_exists('id', $j['publicKey']) && $j['publicKey']['id'] !== $id) && $j['id'] !== $id) {
205 return $j['publicKey']['publicKeyPem'];
215 * @param string $request
217 * @param string $prvkey
218 * @param string $keyid (optional, default 'Key')
219 * @param boolean $send_headers (optional, default false)
220 * If set send a HTTP header
221 * @param boolean $auth (optional, default false)
222 * @param string $alg (optional, default 'sha256')
223 * @param string $crypt_key (optional, default null)
224 * @param string $crypt_algo (optional, default 'aes256ctr')
228 public static function createSig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false, $alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr')
230 $return_headers = [];
232 if ($alg === 'sha256') {
233 $algorithm = 'rsa-sha256';
236 if ($alg === 'sha512') {
237 $algorithm = 'rsa-sha512';
240 $x = self::sign($request, $head, $prvkey, $alg);
242 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
243 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
246 $x = Crypto::encapsulate($headerval, $crypt_key, $crypt_algo);
247 $headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
251 $sighead = 'Authorization: Signature ' . $headerval;
253 $sighead = 'Signature: ' . $headerval;
257 foreach ($head as $k => $v) {
259 // This is for ActivityPub implementation.
260 // Since the Activity Pub implementation isn't
261 // ready at the moment, we comment it out.
262 // header($k . ': ' . $v);
264 $return_headers[] = $k . ': ' . $v;
270 // This is for ActivityPub implementation.
271 // Since the Activity Pub implementation isn't
272 // ready at the moment, we comment it out.
275 $return_headers[] = $sighead;
278 return $return_headers;
284 * @param string $request
286 * @param string $prvkey
287 * @param string $alg (optional) default 'sha256'
291 private static function sign($request, $head, $prvkey, $alg = 'sha256')
298 $headers = '(request-target)' . ': ' . trim($request) . "\n";
299 $fields = '(request-target)';
303 foreach ($head as $k => $v) {
304 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
308 $fields .= strtolower($k);
310 // strip the trailing linefeed
311 $headers = rtrim($headers, "\n");
314 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
316 $ret['headers'] = $fields;
317 $ret['signature'] = $sig;
325 * @param string $header
326 * @return array associate array with
327 * - \e string \b keyID
328 * - \e string \b algorithm
329 * - \e array \b headers
330 * - \e string \b signature
332 public static function parseSigheader($header)
337 // if the header is encrypted, decrypt with (default) site private key and continue
338 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
339 $header = self::decryptSigheader($header);
342 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
343 $ret['keyId'] = $matches[1];
346 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
347 $ret['algorithm'] = $matches[1];
350 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
351 $ret['headers'] = explode(' ', $matches[1]);
354 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
355 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
358 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
359 $ret['headers'] = ['date'];
368 * @param string $header
369 * @param string $prvkey (optional), if not set use site private key
371 * @return array|string associative array, empty string if failue
375 * - \e string \b data
377 private static function decryptSigheader($header, $prvkey = null)
379 $iv = $key = $alg = $data = null;
382 $prvkey = Config::get('system', 'prvkey');
387 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
391 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
395 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
399 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
403 if ($iv && $key && $alg && $data) {
404 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);