4 * @file src/Util/HTTPSignature.php
6 namespace Friendica\Util;
8 use Friendica\Core\Config;
9 use Friendica\Database\DBA;
12 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
14 * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php
16 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
21 // See draft-cavage-http-signatures-08
22 public static function verify($data, $key = '')
29 'header_signed' => false,
30 'header_valid' => false,
31 'content_signed' => false,
32 'content_valid' => false
35 // Decide if $data arrived via controller submission or curl.
36 if (is_array($data) && $data['header']) {
37 if (!$data['success']) {
41 $h = new HTTPHeaders($data['header']);
42 $headers = $h->fetch();
43 $body = $data['body'];
46 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
48 foreach ($_SERVER as $k => $v) {
49 if (strpos($k, 'HTTP_') === 0) {
50 $field = str_replace('_', '-', strtolower(substr($k, 5)));
51 $headers[$field] = $v;
58 if (array_key_exists('signature', $headers)) {
59 $sig_block = self::parseSigheader($headers['signature']);
60 } elseif (array_key_exists('authorization', $headers)) {
61 $sig_block = self::parseSigheader($headers['authorization']);
65 logger('no signature provided.');
69 // Warning: This log statement includes binary data
70 // logger('sig_block: ' . print_r($sig_block,true), LOGGER_DATA);
72 $result['header_signed'] = true;
74 $signed_headers = $sig_block['headers'];
75 if (!$signed_headers) {
76 $signed_headers = ['date'];
80 foreach ($signed_headers as $h) {
81 if (array_key_exists($h, $headers)) {
82 $signed_data .= $h . ': ' . $headers[$h] . "\n";
84 if (strpos($h, '.')) {
89 $signed_data = rtrim($signed_data, "\n");
92 if ($sig_block['algorithm'] === 'rsa-sha256') {
93 $algorithm = 'sha256';
95 if ($sig_block['algorithm'] === 'rsa-sha512') {
96 $algorithm = 'sha512';
99 if ($key && function_exists($key)) {
100 $result['signer'] = $sig_block['keyId'];
101 $key = $key($sig_block['keyId']);
104 logger('Got keyID ' . $sig_block['keyId']);
110 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
112 logger('verified: ' . $x, LOGGER_DEBUG);
119 $result['header_valid'] = true;
122 if (in_array('digest', $signed_headers)) {
123 $result['content_signed'] = true;
124 $digest = explode('=', $headers['digest']);
126 if ($digest[0] === 'SHA-256') {
129 if ($digest[0] === 'SHA-512') {
133 // The explode operation will have stripped the '=' padding, so compare against unpadded base64.
134 if (rtrim(base64_encode(hash($hashalg, $body, true)), '=') === $digest[1]) {
135 $result['content_valid'] = true;
139 logger('Content_Valid: ' . $result['content_valid']);
147 * @param string $request
149 * @param string $prvkey
150 * @param string $keyid (optional, default 'Key')
151 * @param boolean $send_headers (optional, default false)
152 * If set send a HTTP header
153 * @param boolean $auth (optional, default false)
154 * @param string $alg (optional, default 'sha256')
155 * @param string $crypt_key (optional, default null)
156 * @param string $crypt_algo (optional, default 'aes256ctr')
160 public static function createSig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false, $alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr')
162 $return_headers = [];
164 if ($alg === 'sha256') {
165 $algorithm = 'rsa-sha256';
168 if ($alg === 'sha512') {
169 $algorithm = 'rsa-sha512';
172 $x = self::sign($request, $head, $prvkey, $alg);
174 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
175 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
178 $x = Crypto::encapsulate($headerval, $crypt_key, $crypt_algo);
179 $headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
183 $sighead = 'Authorization: Signature ' . $headerval;
185 $sighead = 'Signature: ' . $headerval;
189 foreach ($head as $k => $v) {
191 // This is for ActivityPub implementation.
192 // Since the Activity Pub implementation isn't
193 // ready at the moment, we comment it out.
194 // header($k . ': ' . $v);
196 $return_headers[] = $k . ': ' . $v;
202 // This is for ActivityPub implementation.
203 // Since the Activity Pub implementation isn't
204 // ready at the moment, we comment it out.
207 $return_headers[] = $sighead;
210 return $return_headers;
216 * @param string $request
218 * @param string $prvkey
219 * @param string $alg (optional) default 'sha256'
223 private static function sign($request, $head, $prvkey, $alg = 'sha256')
230 $headers = '(request-target)' . ': ' . trim($request) . "\n";
231 $fields = '(request-target)';
235 foreach ($head as $k => $v) {
236 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
240 $fields .= strtolower($k);
242 // strip the trailing linefeed
243 $headers = rtrim($headers, "\n");
246 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
248 $ret['headers'] = $fields;
249 $ret['signature'] = $sig;
257 * @param string $header
258 * @return array associate array with
259 * - \e string \b keyID
260 * - \e string \b algorithm
261 * - \e array \b headers
262 * - \e string \b signature
264 public static function parseSigheader($header)
269 // if the header is encrypted, decrypt with (default) site private key and continue
270 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
271 $header = self::decryptSigheader($header);
274 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
275 $ret['keyId'] = $matches[1];
278 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
279 $ret['algorithm'] = $matches[1];
282 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
283 $ret['headers'] = explode(' ', $matches[1]);
286 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
287 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
290 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
291 $ret['headers'] = ['date'];
300 * @param string $header
301 * @param string $prvkey (optional), if not set use site private key
303 * @return array|string associative array, empty string if failue
307 * - \e string \b data
309 private static function decryptSigheader($header, $prvkey = null)
311 $iv = $key = $alg = $data = null;
314 $prvkey = Config::get('system', 'prvkey');
319 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
323 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
327 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
331 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
335 if ($iv && $key && $alg && $data) {
336 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);