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 * @see https://tools.ietf.org/html/rfc5843
29 * @param string $body The value to create the digest for
30 * @param boolean $set (optional, default true)
31 * If set send a Digest HTTP header
33 * @return string The generated digest of $body
35 public static function generateDigest($body, $set = true)
37 $digest = base64_encode(hash('sha256', $body, true));
40 header('Digest: SHA-256=' . $digest);
45 // See draft-cavage-http-signatures-08
46 public static function verify($data, $key = '')
53 'header_signed' => false,
54 'header_valid' => false,
55 'content_signed' => false,
56 'content_valid' => false
59 // Decide if $data arrived via controller submission or curl.
60 if (is_array($data) && $data['header']) {
61 if (!$data['success']) {
65 $h = new HTTPHeaders($data['header']);
66 $headers = $h->fetch();
67 $body = $data['body'];
70 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
72 foreach ($_SERVER as $k => $v) {
73 if (strpos($k, 'HTTP_') === 0) {
74 $field = str_replace('_', '-', strtolower(substr($k, 5)));
75 $headers[$field] = $v;
82 if (array_key_exists('signature', $headers)) {
83 $sig_block = self::parseSigheader($headers['signature']);
84 } elseif (array_key_exists('authorization', $headers)) {
85 $sig_block = self::parseSigheader($headers['authorization']);
89 logger('no signature provided.');
93 // Warning: This log statement includes binary data
94 // logger('sig_block: ' . print_r($sig_block,true), LOGGER_DATA);
96 $result['header_signed'] = true;
98 $signed_headers = $sig_block['headers'];
99 if (!$signed_headers) {
100 $signed_headers = ['date'];
104 foreach ($signed_headers as $h) {
105 if (array_key_exists($h, $headers)) {
106 $signed_data .= $h . ': ' . $headers[$h] . "\n";
108 if (strpos($h, '.')) {
113 $signed_data = rtrim($signed_data, "\n");
116 if ($sig_block['algorithm'] === 'rsa-sha256') {
117 $algorithm = 'sha256';
119 if ($sig_block['algorithm'] === 'rsa-sha512') {
120 $algorithm = 'sha512';
123 if ($key && function_exists($key)) {
124 $result['signer'] = $sig_block['keyId'];
125 $key = $key($sig_block['keyId']);
128 // We don't use Activity Pub at the moment.
130 // $result['signer'] = $sig_block['keyId'];
131 // $key = self::getActivitypubKey($sig_block['keyId']);
138 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
140 logger('verified: ' . $x, LOGGER_DEBUG);
147 $result['header_valid'] = true;
150 if (in_array('digest', $signed_headers)) {
151 $result['content_signed'] = true;
152 $digest = explode('=', $headers['digest']);
154 if ($digest[0] === 'SHA-256') {
157 if ($digest[0] === 'SHA-512') {
161 // The explode operation will have stripped the '=' padding, so compare against unpadded base64.
162 if (rtrim(base64_encode(hash($hashalg, $body, true)), '=') === $digest[1]) {
163 $result['content_valid'] = true;
167 logger('Content_Valid: ' . $result['content_valid']);
173 * Fetch the public key for Activity Pub contact.
175 * @param string|int The identifier (contact addr or contact ID).
176 * @return string|boolean The public key or false on failure.
178 private static function getActivitypubKey($id)
180 if (strpos($id, 'acct:') === 0) {
181 $x = dba::selectFirst('contact', ['pubkey'], ['uid' => 0, 'addr' => str_replace('acct:', '', $id)]);
183 $x = dba::selectFirst('contact', ['pubkey'], ['id' => $id, 'network' => 'activitypub']);
186 if (DBM::is_result($x)) {
190 if(function_exists('as_fetch')) {
195 $j = json_decode($r, true);
197 if (array_key_exists('publicKey', $j) && array_key_exists('publicKeyPem', $j['publicKey'])) {
198 if ((array_key_exists('id', $j['publicKey']) && $j['publicKey']['id'] !== $id) && $j['id'] !== $id) {
202 return $j['publicKey']['publicKeyPem'];
212 * @param string $request
214 * @param string $prvkey
215 * @param string $keyid (optional, default 'Key')
216 * @param boolean $send_headers (optional, default false)
217 * If set send a HTTP header
218 * @param boolean $auth (optional, default false)
219 * @param string $alg (optional, default 'sha256')
220 * @param string $crypt_key (optional, default null)
221 * @param string $crypt_algo (optional, default 'aes256ctr')
225 public static function createSig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false, $alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr')
227 $return_headers = [];
229 if ($alg === 'sha256') {
230 $algorithm = 'rsa-sha256';
233 if ($alg === 'sha512') {
234 $algorithm = 'rsa-sha512';
237 $x = self::sign($request, $head, $prvkey, $alg);
239 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
240 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
243 $x = Crypto::encapsulate($headerval, $crypt_key, $crypt_algo);
244 $headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
248 $sighead = 'Authorization: Signature ' . $headerval;
250 $sighead = 'Signature: ' . $headerval;
254 foreach ($head as $k => $v) {
256 header($k . ': ' . $v);
258 $return_headers[] = $k . ': ' . $v;
266 $return_headers[] = $sighead;
269 return $return_headers;
275 * @param string $request
277 * @param string $prvkey
278 * @param string $alg (optional) default 'sha256'
282 private static function sign($request, $head, $prvkey, $alg = 'sha256')
289 $headers = '(request-target)' . ': ' . trim($request) . "\n";
290 $fields = '(request-target)';
294 foreach ($head as $k => $v) {
295 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
299 $fields .= strtolower($k);
301 // strip the trailing linefeed
302 $headers = rtrim($headers, "\n");
305 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
307 $ret['headers'] = $fields;
308 $ret['signature'] = $sig;
316 * @param string $header
317 * @return array associate array with
318 * - \e string \b keyID
319 * - \e string \b algorithm
320 * - \e array \b headers
321 * - \e string \b signature
323 public static function parseSigheader($header)
328 // if the header is encrypted, decrypt with (default) site private key and continue
329 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
330 $header = self::decryptSigheader($header);
333 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
334 $ret['keyId'] = $matches[1];
337 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
338 $ret['algorithm'] = $matches[1];
341 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
342 $ret['headers'] = explode(' ', $matches[1]);
345 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
346 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
349 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
350 $ret['headers'] = ['date'];
359 * @param string $header
360 * @param string $prvkey (optional), if not set use site private key
362 * @return array|string associative array, empty string if failue
366 * - \e string \b data
368 private static function decryptSigheader($header, $prvkey = null)
370 $iv = $key = $alg = $data = null;
373 $prvkey = Config::get('system', 'prvkey');
378 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
382 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
386 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
390 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
394 if ($iv && $key && $alg && $data) {
395 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);