4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\Core\Config;
9 use Friendica\Database\DBA;
10 use Friendica\Database\DBM;
13 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
15 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
17 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
25 * Disabled until Friendica's ActivityPub implementation
28 * @see https://tools.ietf.org/html/rfc5843
30 * @param string $body The value to create the digest for
31 * @param boolean $set (optional, default true)
32 * If set send a Digest HTTP header
34 * @return string The generated digest of $body
36 // public static function generateDigest($body, $set = true)
38 // $digest = base64_encode(hash('sha256', $body, true));
41 // header('Digest: SHA-256=' . $digest);
46 // See draft-cavage-http-signatures-08
47 public static function verify($data, $key = '')
54 'header_signed' => false,
55 'header_valid' => false,
56 'content_signed' => false,
57 'content_valid' => false
60 // Decide if $data arrived via controller submission or curl.
61 if (is_array($data) && $data['header']) {
62 if (!$data['success']) {
66 $h = new HTTPHeaders($data['header']);
67 $headers = $h->fetch();
68 $body = $data['body'];
71 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
73 foreach ($_SERVER as $k => $v) {
74 if (strpos($k, 'HTTP_') === 0) {
75 $field = str_replace('_', '-', strtolower(substr($k, 5)));
76 $headers[$field] = $v;
83 if (array_key_exists('signature', $headers)) {
84 $sig_block = self::parseSigheader($headers['signature']);
85 } elseif (array_key_exists('authorization', $headers)) {
86 $sig_block = self::parseSigheader($headers['authorization']);
90 logger('no signature provided.');
94 // Warning: This log statement includes binary data
95 // logger('sig_block: ' . print_r($sig_block,true), LOGGER_DATA);
97 $result['header_signed'] = true;
99 $signed_headers = $sig_block['headers'];
100 if (!$signed_headers) {
101 $signed_headers = ['date'];
105 foreach ($signed_headers as $h) {
106 if (array_key_exists($h, $headers)) {
107 $signed_data .= $h . ': ' . $headers[$h] . "\n";
109 if (strpos($h, '.')) {
114 $signed_data = rtrim($signed_data, "\n");
117 if ($sig_block['algorithm'] === 'rsa-sha256') {
118 $algorithm = 'sha256';
120 if ($sig_block['algorithm'] === 'rsa-sha512') {
121 $algorithm = 'sha512';
124 if ($key && function_exists($key)) {
125 $result['signer'] = $sig_block['keyId'];
126 $key = $key($sig_block['keyId']);
129 // We don't use Activity Pub at the moment.
131 // $result['signer'] = $sig_block['keyId'];
132 // $key = self::getActivitypubKey($sig_block['keyId']);
139 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
141 logger('verified: ' . $x, LOGGER_DEBUG);
148 $result['header_valid'] = true;
151 if (in_array('digest', $signed_headers)) {
152 $result['content_signed'] = true;
153 $digest = explode('=', $headers['digest']);
155 if ($digest[0] === 'SHA-256') {
158 if ($digest[0] === 'SHA-512') {
162 // The explode operation will have stripped the '=' padding, so compare against unpadded base64.
163 if (rtrim(base64_encode(hash($hashalg, $body, true)), '=') === $digest[1]) {
164 $result['content_valid'] = true;
168 logger('Content_Valid: ' . $result['content_valid']);
174 * Fetch the public key for Activity Pub contact.
176 * @param string|int The identifier (contact addr or contact ID).
177 * @return string|boolean The public key or false on failure.
179 private static function getActivitypubKey($id)
181 if (strpos($id, 'acct:') === 0) {
182 $contact = DBA::selectFirst('contact', ['pubkey'], ['uid' => 0, 'addr' => str_replace('acct:', '', $id)]);
184 $contact = DBA::selectFirst('contact', ['pubkey'], ['id' => $id, 'network' => 'activitypub']);
187 if (DBM::is_result($contact)) {
188 return $contact['pubkey'];
191 if(function_exists('as_fetch')) {
196 $j = json_decode($r, true);
198 if (array_key_exists('publicKey', $j) && array_key_exists('publicKeyPem', $j['publicKey'])) {
199 if ((array_key_exists('id', $j['publicKey']) && $j['publicKey']['id'] !== $id) && $j['id'] !== $id) {
203 return $j['publicKey']['publicKeyPem'];
213 * @param string $request
215 * @param string $prvkey
216 * @param string $keyid (optional, default 'Key')
217 * @param boolean $send_headers (optional, default false)
218 * If set send a HTTP header
219 * @param boolean $auth (optional, default false)
220 * @param string $alg (optional, default 'sha256')
221 * @param string $crypt_key (optional, default null)
222 * @param string $crypt_algo (optional, default 'aes256ctr')
226 public static function createSig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false, $alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr')
228 $return_headers = [];
230 if ($alg === 'sha256') {
231 $algorithm = 'rsa-sha256';
234 if ($alg === 'sha512') {
235 $algorithm = 'rsa-sha512';
238 $x = self::sign($request, $head, $prvkey, $alg);
240 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
241 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
244 $x = Crypto::encapsulate($headerval, $crypt_key, $crypt_algo);
245 $headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
249 $sighead = 'Authorization: Signature ' . $headerval;
251 $sighead = 'Signature: ' . $headerval;
255 foreach ($head as $k => $v) {
257 // This is for ActivityPub implementation.
258 // Since the Activity Pub implementation isn't
259 // ready at the moment, we comment it out.
260 // header($k . ': ' . $v);
262 $return_headers[] = $k . ': ' . $v;
268 // This is for ActivityPub implementation.
269 // Since the Activity Pub implementation isn't
270 // ready at the moment, we comment it out.
273 $return_headers[] = $sighead;
276 return $return_headers;
282 * @param string $request
284 * @param string $prvkey
285 * @param string $alg (optional) default 'sha256'
289 private static function sign($request, $head, $prvkey, $alg = 'sha256')
296 $headers = '(request-target)' . ': ' . trim($request) . "\n";
297 $fields = '(request-target)';
301 foreach ($head as $k => $v) {
302 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
306 $fields .= strtolower($k);
308 // strip the trailing linefeed
309 $headers = rtrim($headers, "\n");
312 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
314 $ret['headers'] = $fields;
315 $ret['signature'] = $sig;
323 * @param string $header
324 * @return array associate array with
325 * - \e string \b keyID
326 * - \e string \b algorithm
327 * - \e array \b headers
328 * - \e string \b signature
330 public static function parseSigheader($header)
335 // if the header is encrypted, decrypt with (default) site private key and continue
336 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
337 $header = self::decryptSigheader($header);
340 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
341 $ret['keyId'] = $matches[1];
344 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
345 $ret['algorithm'] = $matches[1];
348 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
349 $ret['headers'] = explode(' ', $matches[1]);
352 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
353 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
356 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
357 $ret['headers'] = ['date'];
366 * @param string $header
367 * @param string $prvkey (optional), if not set use site private key
369 * @return array|string associative array, empty string if failue
373 * - \e string \b data
375 private static function decryptSigheader($header, $prvkey = null)
377 $iv = $key = $alg = $data = null;
380 $prvkey = Config::get('system', 'prvkey');
385 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
389 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
393 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
397 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
401 if ($iv && $key && $alg && $data) {
402 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);