4 * @file src/Util/HTTPSig.php
6 namespace Friendica\Util;
8 use Friendica\Core\Config;
9 use Friendica\Util\Crypto;
10 use Friendica\Util\HTTPHeaders;
13 * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07.
15 * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07
23 * @see https://tools.ietf.org/html/rfc5843
25 * @param string $body The value to create the digest for
26 * @param boolean $set (optional, default true)
27 * If set send a Digest HTTP header
28 * @return string The generated digest of $body
30 public static function generateDigest($body, $set = true)
32 $digest = base64_encode(hash('sha256', $body, true));
35 header('Digest: SHA-256=' . $digest);
40 // See draft-cavage-http-signatures-08
41 public static function verify($data, $key = '')
48 'header_signed' => false,
49 'header_valid' => false,
50 'content_signed' => false,
51 'content_valid' => false
54 // Decide if $data arrived via controller submission or curl.
55 if (is_array($data) && $data['header']) {
56 if (!$data['success']) {
60 $h = new HTTPHeaders($data['header']);
61 $headers = $h->fetcharr();
62 $body = $data['body'];
65 $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']).' '.$_SERVER['REQUEST_URI'];
67 foreach ($_SERVER as $k => $v) {
68 if (strpos($k, 'HTTP_') === 0) {
69 $field = str_replace('_', '-', strtolower(substr($k, 5)));
70 $headers[$field] = $v;
77 if (array_key_exists('signature', $headers)) {
78 $sig_block = self::parseSigheader($headers['signature']);
79 } elseif (array_key_exists('authorization', $headers)) {
80 $sig_block = self::parseSigheader($headers['authorization']);
84 logger('no signature provided.');
88 // Warning: This log statement includes binary data
89 // logger('sig_block: ' . print_r($sig_block,true), LOGGER_DATA);
91 $result['header_signed'] = true;
93 $signed_headers = $sig_block['headers'];
94 if (!$signed_headers) {
95 $signed_headers = ['date'];
99 foreach ($signed_headers as $h) {
100 if (array_key_exists($h, $headers)) {
101 $signed_data .= $h . ': ' . $headers[$h] . "\n";
103 if (strpos($h, '.')) {
108 $signed_data = rtrim($signed_data, "\n");
111 if ($sig_block['algorithm'] === 'rsa-sha256') {
112 $algorithm = 'sha256';
114 if ($sig_block['algorithm'] === 'rsa-sha512') {
115 $algorithm = 'sha512';
118 if ($key && function_exists($key)) { /// @todo What function do we check for - maybe we check now for a method !!!
119 $result['signer'] = $sig_block['keyId'];
120 $key = $key($sig_block['keyId']);
127 $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
129 logger('verified: ' . $x, LOGGER_DEBUG);
136 $result['header_valid'] = true;
139 if (in_array('digest', $signed_headers)) {
140 $result['content_signed'] = true;
141 $digest = explode('=', $headers['digest']);
143 if ($digest[0] === 'SHA-256') {
146 if ($digest[0] === 'SHA-512') {
150 // The explode operation will have stripped the '=' padding, so compare against unpadded base64.
151 if (rtrim(base64_encode(hash($hashalg, $body, true)), '=') === $digest[1]) {
152 $result['content_valid'] = true;
156 logger('Content_Valid: ' . $result['content_valid']);
164 * @param string $request
166 * @param string $prvkey
167 * @param string $keyid (optional, default 'Key')
168 * @param boolean $send_headers (optional, default false)
169 * If set send a HTTP header
170 * @param boolean $auth (optional, default false)
171 * @param string $alg (optional, default 'sha256')
172 * @param string $crypt_key (optional, default null)
173 * @param string $crypt_algo (optional, default 'aes256ctr')
177 public static function createSig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false, $alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr')
179 $return_headers = [];
181 if ($alg === 'sha256') {
182 $algorithm = 'rsa-sha256';
185 if ($alg === 'sha512') {
186 $algorithm = 'rsa-sha512';
189 $x = self::sign($request, $head, $prvkey, $alg);
191 $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm
192 . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
195 $x = Crypto::encapsulate($headerval, $crypt_key, $crypt_algo);
196 $headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
200 $sighead = 'Authorization: Signature ' . $headerval;
202 $sighead = 'Signature: ' . $headerval;
206 foreach ($head as $k => $v) {
208 header($k . ': ' . $v);
210 $return_headers[] = $k . ': ' . $v;
218 $return_headers[] = $sighead;
221 return $return_headers;
227 * @param string $request
229 * @param string $prvkey
230 * @param string $alg (optional) default 'sha256'
234 private static function sign($request, $head, $prvkey, $alg = 'sha256')
241 $headers = '(request-target)' . ': ' . trim($request) . "\n";
242 $fields = '(request-target)';
246 foreach ($head as $k => $v) {
247 $headers .= strtolower($k) . ': ' . trim($v) . "\n";
251 $fields .= strtolower($k);
253 // strip the trailing linefeed
254 $headers = rtrim($headers, "\n");
257 $sig = base64_encode(Crypto::rsaSign($headers, $prvkey, $alg));
259 $ret['headers'] = $fields;
260 $ret['signature'] = $sig;
268 * @param string $header
269 * @return array associate array with
270 * - \e string \b keyID
271 * - \e string \b algorithm
272 * - \e array \b headers
273 * - \e string \b signature
275 public static function parseSigheader($header)
280 // if the header is encrypted, decrypt with (default) site private key and continue
281 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
282 $header = self::decryptSigheader($header);
285 if (preg_match('/keyId="(.*?)"/ism', $header, $matches)) {
286 $ret['keyId'] = $matches[1];
289 if (preg_match('/algorithm="(.*?)"/ism', $header, $matches)) {
290 $ret['algorithm'] = $matches[1];
293 if (preg_match('/headers="(.*?)"/ism', $header, $matches)) {
294 $ret['headers'] = explode(' ', $matches[1]);
297 if (preg_match('/signature="(.*?)"/ism', $header, $matches)) {
298 $ret['signature'] = base64_decode(preg_replace('/\s+/', '', $matches[1]));
301 if (($ret['signature']) && ($ret['algorithm']) && (!$ret['headers'])) {
302 $ret['headers'] = ['date'];
311 * @param string $header
312 * @param string $prvkey (optional), if not set use site private key
314 * @return array|string associative array, empty string if failue
318 * - \e string \b data
320 private static function decryptSigheader($header, $prvkey = null)
322 $iv = $key = $alg = $data = null;
325 $prvkey = Config::get('system', 'prvkey');
330 if (preg_match('/iv="(.*?)"/ism', $header, $matches)) {
334 if (preg_match('/key="(.*?)"/ism', $header, $matches)) {
338 if (preg_match('/alg="(.*?)"/ism', $header, $matches)) {
342 if (preg_match('/data="(.*?)"/ism', $header, $matches)) {
346 if ($iv && $key && $alg && $data) {
347 return Crypto::unencapsulate(['iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data], $prvkey);