Commit 16a725f4 authored by Waitman Gobble's avatar Waitman Gobble 🍓
Browse files

Initial commit

parents
<?php
class Crypto {
static public $openssl_algorithms = [
// zot6 nickname, opensslname, keylength, ivlength
[ 'aes256ctr', 'aes-256-ctr', 32, 16 ],
[ 'camellia256cfb', 'camellia-256-cfb', 32, 16 ],
[ 'cast5cfb', 'cast5-cfb', 16, 8 ]
];
static public function methods() {
$ret = [];
foreach(self::$openssl_algorithms as $ossl) {
$ret[] = $ossl[0] . '.oaep';
}
call_hooks('crypto_methods',$ret);
return $ret;
}
static public function signing_methods() {
$ret = [ 'sha256' ];
call_hooks('signing_methods',$ret);
return $ret;
}
static public function new_keypair($bits) {
$openssl_options = [
'digest_alg' => 'sha1',
'private_key_bits' => $bits,
'encrypt_key' => false
];
$conf = get_config('system','openssl_conf_file');
if ($conf) {
$openssl_options['config'] = $conf;
}
$result = openssl_pkey_new($openssl_options);
if (empty($result)) {
return false;
}
// Get private key
$response = [ 'prvkey' => '', 'pubkey' => '' ];
openssl_pkey_export($result, $response['prvkey']);
// Get public key
$pkey = openssl_pkey_get_details($result);
$response['pubkey'] = $pkey["key"];
return $response;
}
static public function sign($data,$key,$alg = 'sha256') {
if (! $key) {
return false;
}
$sig = '';
openssl_sign($data,$sig,$key,$alg);
return $sig;
}
static public function verify($data,$sig,$key,$alg = 'sha256') {
if (! $key) {
return false;
}
try {
$verify = openssl_verify($data,$sig,$key,$alg);
}
catch (Exception $e) {
$verify = (-1);
}
if ($verify === (-1)) {
while ($msg = openssl_error_string()) {
logger('openssl_verify: ' . $msg,LOGGER_NORMAL,LOG_ERR);
}
btlogger('openssl_verify: key: ' . $key, LOGGER_DEBUG, LOG_ERR);
}
return (($verify > 0) ? true : false);
}
static public function encapsulate($data,$pubkey,$alg) {
if (! ($alg && $pubkey)) {
return $data;
}
$alg_base = $alg;
$padding = OPENSSL_PKCS1_PADDING;
$exts = explode('.',$alg);
if (count($exts) > 1) {
switch ($exts[1]) {
case 'oaep':
$padding = OPENSSL_PKCS1_OAEP_PADDING;
break;
default:
break;
}
$alg_base = $exts[0];
}
$method = null;
foreach (self::$openssl_algorithms as $ossl) {
if ($ossl[0] === $alg_base) {
$method = $ossl;
break;
}
}
if ($method) {
$result = [ 'encrypted' => true ];
$key = openssl_random_pseudo_bytes(256);
$iv = openssl_random_pseudo_bytes(256);
$key1 = substr($key, 0, $method[2]);
$iv1 = substr($iv, 0, $method[3]);
$result['data'] = base64url_encode(openssl_encrypt($data,$method[1],$key1,OPENSSL_RAW_DATA,$iv1),true);
openssl_public_encrypt($key, $k, $pubkey, $padding);
openssl_public_encrypt($iv, $i, $pubkey, $padding);
$result['alg'] = $alg;
$result['key'] = base64url_encode($k,true);
$result['iv'] = base64url_encode($i,true);
return $result;
}
else {
$x = [ 'data' => $data, 'pubkey' => $pubkey, 'alg' => $alg, 'result' => $data ];
call_hooks('crypto_encapsulate', $x);
return $x['result'];
}
}
static public function unencapsulate($data,$prvkey) {
if (! (is_array($data) && array_key_exists('encrypted',$data) && array_key_exists('alg',$data) && $data['alg'])) {
logger('not encrypted');
return $data;
}
$alg_base = $data['alg'];
$padding = OPENSSL_PKCS1_PADDING;
$exts = explode('.',$data['alg']);
if (count($exts) > 1) {
switch ($exts[1]) {
case 'oaep':
$padding = OPENSSL_PKCS1_OAEP_PADDING;
break;
default:
break;
}
$alg_base = $exts[0];
}
$method = null;
foreach (self::$openssl_algorithms as $ossl) {
if ($ossl[0] === $alg_base) {
$method = $ossl;
break;
}
}
if ($method) {
openssl_private_decrypt(base64url_decode($data['key']),$k,$prvkey,$padding);
openssl_private_decrypt(base64url_decode($data['iv']), $i,$prvkey,$padding);
return openssl_decrypt(base64url_decode($data['data']),$method[1],substr($k,0,$method[2]),OPENSSL_RAW_DATA,substr($i,0,$method[3]));
}
else {
$x = [ 'data' => $data, 'prvkey' => $prvkey, 'alg' => $data['alg'], 'result' => $data ];
call_hooks('crypto_unencapsulate',$x);
return $x['result'];
}
}
}
<?php
include('Crypto.php');
include('functions.php');
/**
* @brief Implements HTTP Signatures per draft-cavage-http-signatures-10.
*
* @see https://tools.ietf.org/html/draft-cavage-http-signatures-10
*/
class HTTPSig {
/**
* @brief RFC5843
*
* @see https://tools.ietf.org/html/rfc5843
*
* @param string $body The value to create the digest for
* @param string $alg hash algorithm (one of 'sha256','sha512')
* @return string The generated digest header string for $body
*/
static function generate_digest_header($body,$alg = 'sha256') {
$digest = base64_encode(hash($alg, $body, true));
switch ($alg) {
case 'sha512':
return 'SHA-512=' . $digest;
case 'sha256':
default:
return 'SHA-256=' . $digest;
break;
}
}
static function find_headers($data,&$body) {
// decide if $data arrived via controller submission or curl
// changes $body for the caller
if (is_array($data) && array_key_exists('header',$data)) {
if (! $data['success']) {
$body = EMPTY_STR;
return [];
}
if (! $data['header']) {
$body = EMPTY_STR;
return [];
}
$h = new HTTPHeaders($data['header']);
$headers = $h->fetcharr();
$body = $data['body'];
$headers['(request-target)'] = $data['request_target'];
}
else {
$headers = [];
$headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']) . ' ' . $_SERVER['REQUEST_URI'];
$headers['content-type'] = $_SERVER['CONTENT_TYPE'];
$headers['content-length'] = $_SERVER['CONTENT_LENGTH'];
foreach ($_SERVER as $k => $v) {
if (strpos($k,'HTTP_') === 0) {
$field = str_replace('_','-',strtolower(substr($k,5)));
$headers[$field] = $v;
}
}
}
//logger('SERVER: ' . print_r($_SERVER,true), LOGGER_ALL);
//logger('headers: ' . print_r($headers,true), LOGGER_ALL);
return $headers;
}
// See draft-cavage-http-signatures-10
static function verify($data,$key = '') {
$body = $data;
$headers = null;
$result = [
'signer' => '',
'portable_id' => '',
'header_signed' => false,
'header_valid' => false,
'content_signed' => false,
'content_valid' => false
];
$headers = self::find_headers($data,$body);
if (! $headers) {
return $result;
}
if (is_array($body)) {
btlogger('body is array!' . print_r($body,true));
}
$sig_block = null;
if (array_key_exists('signature',$headers)) {
$sig_block = self::parse_sigheader($headers['signature']);
}
elseif (array_key_exists('authorization',$headers)) {
$sig_block = self::parse_sigheader($headers['authorization']);
}
if (! $sig_block) {
logger('no signature provided.', LOGGER_DEBUG);
return $result;
}
// Warning: This log statement includes binary data
// logger('sig_block: ' . print_r($sig_block,true), LOGGER_DATA);
$result['header_signed'] = true;
$signed_headers = $sig_block['headers'];
if (! $signed_headers) {
$signed_headers = [ 'date' ];
}
$signed_data = '';
foreach ($signed_headers as $h) {
if (array_key_exists($h,$headers)) {
$signed_data .= $h . ': ' . $headers[$h] . "\n";
}
if ($h === 'date') {
$d = new \DateTime($headers[$h]);
$d->setTimeZone(new \DateTimeZone('UTC'));
$dplus = datetime_convert('UTC','UTC','now + 1 day');
$dminus = datetime_convert('UTC','UTC','now - 1 day');
$c = $d->format('Y-m-d H:i:s');
if ($c > $dplus || $c < $dminus) {
logger('bad time: ' . $c);
return $result;
}
}
}
$signed_data = rtrim($signed_data,"\n");
$algorithm = null;
if ($sig_block['algorithm'] === 'rsa-sha256') {
$algorithm = 'sha256';
}
if ($sig_block['algorithm'] === 'rsa-sha512') {
$algorithm = 'sha512';
}
if (! array_key_exists('keyId',$sig_block)) {
return $result;
}
$result['signer'] = $sig_block['keyId'];
$fkey = self::get_key($key,$result['signer']);
if (! ($fkey && $fkey['public_key'])) {
return $result;
}
$x = Crypto::verify($signed_data,$sig_block['signature'],$fkey['public_key'],$algorithm);
logger('verified: ' . $x, LOGGER_DEBUG);
if (! $x) {
// try again, ignoring the local actor (xchan) cache and refetching the key
// from its source
$fkey = self::get_key($key,$result['signer'],true);
if ($fkey && $fkey['public_key']) {
$y = Crypto::verify($signed_data,$sig_block['signature'],$fkey['public_key'],$algorithm);
logger('verified: (cache reload) ' . $x, LOGGER_DEBUG);
}
if (! $y) {
logger('verify failed for ' . $result['signer'] . ' alg=' . $algorithm . (($fkey['public_key']) ? '' : ' no key'));
$sig_block['signature'] = base64_encode($sig_block['signature']);
logger('affected sigblock: ' . print_r($sig_block,true));
logger('headers: ' . print_r($headers,true));
logger('server: ' . print_r($_SERVER,true));
return $result;
}
}
$result['portable_id'] = $fkey['portable_id'];
$result['header_valid'] = true;
if (in_array('digest',$signed_headers)) {
$result['content_signed'] = true;
$digest = explode('=', $headers['digest'], 2);
if ($digest[0] === 'SHA-256') {
$hashalg = 'sha256';
}
if ($digest[0] === 'SHA-512') {
$hashalg = 'sha512';
}
if (base64_encode(hash($hashalg,$body,true)) === $digest[1]) {
$result['content_valid'] = true;
}
logger('Content_Valid: ' . (($result['content_valid']) ? 'true' : 'false'));
if (! $result['content_valid']) {
logger('invalid content signature: data ' . print_r($data,true));
logger('invalid content signature: headers ' . print_r($headers,true));
logger('invalid content signature: body ' . print_r($body,true));
}
}
return $result;
}
static function get_key($key,$id,$force = false) {
if ($key) {
if (function_exists($key)) {
return $key($id);
}
return [ 'public_key' => $key ];
}
if (strpos($id,'#') === false) {
$key = self::get_webfinger_key($id,$force);
}
if (! $key) {
$key = self::get_activitystreams_key($id,$force);
}
return $key;
}
function convertKey($key) {
if (strstr($key,'RSA ')) {
return Keyutils::rsatopem($key);
}
elseif (substr($key,0,5) === 'data:') {
return Keyutils::convert_salmon_key($key);
}
else {
return $key;
}
}
/**
* @brief
*
* @param string $id
* @return boolean|string
* false if no pub key found, otherwise return the pub key
*/
function get_activitystreams_key($id,$force = false) {
// remove fragment
$url = ((strpos($id,'#')) ? substr($id,0,strpos($id,'#')) : $id);
if (! $force) {
$x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s' ",
dbesc(str_replace('acct:','',$url)),
dbesc($url)
);
}
if ($x) {
$best = Libzot::zot_record_preferred($x);
}
if ($best && $best['xchan_pubkey']) {
return [ 'portable_id' => $best['xchan_hash'], 'public_key' => $best['xchan_pubkey'] , 'hubloc' => $best ];
}
$r = Activity::fetch($id);
if ($r) {
if (array_key_exists('publicKey',$r) && array_key_exists('publicKeyPem',$r['publicKey']) && array_key_exists('id',$r['publicKey'])) {
if ($r['publicKey']['id'] === $id || $r['id'] === $id) {
$portable_id = ((array_key_exists('owner',$r['publicKey'])) ? $r['publicKey']['owner'] : EMPTY_STR);
return [ 'public_key' => self::convertKey($r['publicKey']['publicKeyPem']), 'portable_id' => $portable_id, 'hubloc' => [] ];
}
}
}
return false;
}
function get_webfinger_key($id,$force = false) {
if (! $force) {
$x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s' ",
dbesc(str_replace('acct:','',$id)),
dbesc($id)
);
}
if ($x) {
$best = Libzot::zot_record_preferred($x);
}
if ($best && $best['xchan_pubkey']) {
return [ 'portable_id' => $best['xchan_hash'], 'public_key' => $best['xchan_pubkey'] , 'hubloc' => $best ];
}
$wf = Webfinger::exec($id);
$key = [ 'portable_id' => '', 'public_key' => '', 'hubloc' => [] ];
if ($wf) {
if (array_key_exists('properties',$wf) && array_key_exists('https://w3id.org/security/v1#publicKeyPem',$wf['properties'])) {
$key['public_key'] = self::convertKey($wf['properties']['https://w3id.org/security/v1#publicKeyPem']);
}
if (array_key_exists('links', $wf) && is_array($wf['links'])) {
foreach ($wf['links'] as $l) {
if (! (is_array($l) && array_key_exists('rel',$l))) {
continue;
}
if ($l['rel'] === 'magic-public-key' && array_key_exists('href',$l) && $key['public_key'] === EMPTY_STR) {
$key['public_key'] = self::convertKey($l['href']);
}
}
}
}
return (($key['public_key']) ? $key : false);
}
function get_zotfinger_key($id,$force = false) {
if (! $force) {
$x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s' ",
dbesc(str_replace('acct:','',$id)),
dbesc($id)
);
}
if ($x) {
$best = Libzot::zot_record_preferred($x);
}
if ($best && $best['xchan_pubkey']) {
return [ 'portable_id' => $best['xchan_hash'], 'public_key' => $best['xchan_pubkey'] , 'hubloc' => $best ];
}
$wf = Webfinger::exec($id);
$key = [ 'portable_id' => '', 'public_key' => '', 'hubloc' => [] ];
if ($wf) {
if (array_key_exists('properties',$wf) && array_key_exists('https://w3id.org/security/v1#publicKeyPem',$wf['properties'])) {
$key['public_key'] = self::convertKey($wf['properties']['https://w3id.org/security/v1#publicKeyPem']);
}
if (array_key_exists('links', $wf) && is_array($wf['links'])) {
foreach ($wf['links'] as $l) {
if (! (is_array($l) && array_key_exists('rel',$l))) {
continue;
}
if ($l['rel'] === 'http://purl.org/zot/protocol/6.0' && array_key_exists('href',$l) && $l['href'] !== EMPTY_STR) {
$z = Zotfinger::exec($l['href']);
if ($z) {
$i = Libzot::import_xchan($z['data']);
if ($i['success']) {
$key['portable_id'] = $i['hash'];
$x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_id_url = '%s' limit 1",
dbesc($l['href'])
);
if ($x) {
$key['hubloc'] = $x[0];
}
}
}
}
if ($l['rel'] === 'magic-public-key' && array_key_exists('href',$l) && $key['public_key'] === EMPTY_STR) {
$key['public_key'] = self::convertKey($l['href']);
}
}
}
}
return (($key['public_key']) ? $key : false);
}
/**
* @brief
*
* @param array $head
* @param string $prvkey
* @param string $keyid (optional, default '')
* @param boolean $auth (optional, default false)
* @param string $alg (optional, default 'sha256')
* @param array $encryption [ 'key', 'algorithm' ] or false
* @return array
*/
static function create_sig($head, $prvkey, $keyid = EMPTY_STR, $auth = false, $alg = 'sha256', $encryption = false ) {
$return_headers = [];