aboutsummaryrefslogtreecommitdiffstats
path: root/Zotlabs/Zot6
diff options
context:
space:
mode:
Diffstat (limited to 'Zotlabs/Zot6')
-rw-r--r--Zotlabs/Zot6/Finger.php146
-rw-r--r--Zotlabs/Zot6/HTTPSig.php507
-rw-r--r--Zotlabs/Zot6/IHandler.php18
-rw-r--r--Zotlabs/Zot6/Receiver.php220
-rw-r--r--Zotlabs/Zot6/Zot6Handler.php266
5 files changed, 1157 insertions, 0 deletions
diff --git a/Zotlabs/Zot6/Finger.php b/Zotlabs/Zot6/Finger.php
new file mode 100644
index 000000000..f1fe41352
--- /dev/null
+++ b/Zotlabs/Zot6/Finger.php
@@ -0,0 +1,146 @@
+<?php
+
+namespace Zotlabs\Zot6;
+
+/**
+ * @brief Finger
+ *
+ */
+class Finger {
+
+ static private $token;
+
+ /**
+ * @brief Look up information about channel.
+ *
+ * @param string $webbie
+ * does not have to be host qualified e.g. 'foo' is treated as 'foo\@thishub'
+ * @param array $channel
+ * (optional), if supplied permissions will be enumerated specifically for $channel
+ * @param boolean $autofallback
+ * fallback/failover to http if https connection cannot be established. Default is true.
+ *
+ * @return zotinfo array (with 'success' => true) or array('success' => false);
+ */
+
+ static public function run($webbie, $channel = null, $autofallback = true) {
+
+ $ret = array('success' => false);
+
+ self::$token = random_string();
+
+ if (strpos($webbie, '@') === false) {
+ $address = $webbie;
+ $host = \App::get_hostname();
+ } else {
+ $address = substr($webbie,0,strpos($webbie,'@'));
+ $host = substr($webbie,strpos($webbie,'@')+1);
+ if(strpos($host,'/'))
+ $host = substr($host,0,strpos($host,'/'));
+ }
+
+ $xchan_addr = $address . '@' . $host;
+
+ if ((! $address) || (! $xchan_addr)) {
+ logger('zot_finger: no address :' . $webbie);
+
+ return $ret;
+ }
+
+ logger('using xchan_addr: ' . $xchan_addr, LOGGER_DATA, LOG_DEBUG);
+
+ // potential issue here; the xchan_addr points to the primary hub.
+ // The webbie we were called with may not, so it might not be found
+ // unless we query for hubloc_addr instead of xchan_addr
+
+ $r = q("select xchan.*, hubloc.* from xchan
+ left join hubloc on xchan_hash = hubloc_hash
+ where xchan_addr = '%s' and hubloc_primary = 1 limit 1",
+ dbesc($xchan_addr)
+ );
+
+ if($r) {
+ $url = $r[0]['hubloc_url'];
+
+ if($r[0]['hubloc_network'] && $r[0]['hubloc_network'] !== 'zot') {
+ logger('zot_finger: alternate network: ' . $webbie);
+ logger('url: ' . $url . ', net: ' . var_export($r[0]['hubloc_network'],true), LOGGER_DATA, LOG_DEBUG);
+ return $ret;
+ }
+ } else {
+ $url = 'https://' . $host;
+ }
+
+ $rhs = '/.well-known/zot-info';
+ $https = ((strpos($url,'https://') === 0) ? true : false);
+
+ logger('zot_finger: ' . $address . ' at ' . $url, LOGGER_DEBUG);
+
+ if ($channel) {
+ $postvars = array(
+ 'address' => $address,
+ 'target' => $channel['channel_guid'],
+ 'target_sig' => $channel['channel_guid_sig'],
+ 'key' => $channel['channel_pubkey'],
+ 'token' => self::$token
+ );
+
+ $headers = [];
+ $headers['X-Zot-Channel'] = $channel['channel_address'] . '@' . \App::get_hostname();
+ $headers['X-Zot-Nonce'] = random_string();
+ $xhead = \Zotlabs\Web\HTTPSig::create_sig('',$headers,$channel['channel_prvkey'],
+ 'acct:' . $channel['channel_address'] . '@' . \App::get_hostname(),false);
+
+ $retries = 0;
+
+ $result = z_post_url($url . $rhs,$postvars,$retries, [ 'headers' => $xhead ]);
+
+ if ((! $result['success']) && ($autofallback)) {
+ if ($https) {
+ logger('zot_finger: https failed. falling back to http');
+ $result = z_post_url('http://' . $host . $rhs,$postvars, $retries, [ 'headers' => $xhead ]);
+ }
+ }
+ }
+ else {
+ $rhs .= '?f=&address=' . urlencode($address) . '&token=' . self::$token;
+
+ $result = z_fetch_url($url . $rhs);
+ if((! $result['success']) && ($autofallback)) {
+ if($https) {
+ logger('zot_finger: https failed. falling back to http');
+ $result = z_fetch_url('http://' . $host . $rhs);
+ }
+ }
+ }
+
+ if(! $result['success']) {
+ logger('zot_finger: no results');
+
+ return $ret;
+ }
+
+ $x = json_decode($result['body'], true);
+
+ $verify = \Zotlabs\Web\HTTPSig::verify($result,(($x) ? $x['key'] : ''));
+
+ if($x && (! $verify['header_valid'])) {
+ $signed_token = ((is_array($x) && array_key_exists('signed_token', $x)) ? $x['signed_token'] : null);
+ if($signed_token) {
+ $valid = zot_verify('token.' . self::$token, base64url_decode($signed_token), $x['key']);
+ if(! $valid) {
+ logger('invalid signed token: ' . $url . $rhs, LOGGER_NORMAL, LOG_ERR);
+
+ return $ret;
+ }
+ }
+ else {
+ logger('No signed token from ' . $url . $rhs, LOGGER_NORMAL, LOG_WARNING);
+ return $ret;
+ }
+ }
+
+ return $x;
+ }
+
+}
diff --git a/Zotlabs/Zot6/HTTPSig.php b/Zotlabs/Zot6/HTTPSig.php
new file mode 100644
index 000000000..a0f0d3500
--- /dev/null
+++ b/Zotlabs/Zot6/HTTPSig.php
@@ -0,0 +1,507 @@
+<?php
+
+namespace Zotlabs\Zot6;
+
+use Zotlabs\Lib\ActivityStreams;
+use Zotlabs\Lib\Webfinger;
+use Zotlabs\Web\HTTPHeaders;
+
+/**
+ * @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
+
+ if(is_array($data) && $data['header']) {
+ if(! $data['success'])
+ return [];
+
+ $h = new HTTPHeaders($data['header']);
+ $headers = $h->fetcharr();
+ $body = $data['body'];
+ }
+
+ else {
+ $headers = [];
+ $headers['(request-target)'] = strtolower($_SERVER['REQUEST_METHOD']) . ' ' . $_SERVER['REQUEST_URI'];
+ $headers['content-type'] = $_SERVER['CONTENT_TYPE'];
+
+ 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;
+
+ $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";
+ }
+ }
+ $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'];
+
+ $key = self::get_key($key,$result['signer']);
+
+ if(! ($key && $key['public_key'])) {
+ return $result;
+ }
+
+ $x = rsa_verify($signed_data,$sig_block['signature'],$key['public_key'],$algorithm);
+
+ logger('verified: ' . $x, LOGGER_DEBUG);
+
+ if(! $x)
+ return $result;
+
+ $result['portable_id'] = $key['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'));
+ }
+
+ return $result;
+ }
+
+ static function get_key($key,$id) {
+
+ if($key) {
+ if(function_exists($key)) {
+ return $key($id);
+ }
+ return [ 'public_key' => $key ];
+ }
+
+ $key = self::get_webfinger_key($id);
+
+ if(! $key) {
+ $key = self::get_activitystreams_key($id);
+ }
+
+ return $key;
+
+ }
+
+
+ function convertKey($key) {
+
+ if(strstr($key,'RSA ')) {
+ return rsatopem($key);
+ }
+ elseif(substr($key,0,5) === 'data:') {
+ return 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) {
+
+ $x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s' limit 1",
+ dbesc(str_replace('acct:','',$id)),
+ dbesc($id)
+ );
+
+ if($x && $x[0]['xchan_pubkey']) {
+ return [ 'portable_id' => $x[0]['xchan_hash'], 'public_key' => $x[0]['xchan_pubkey'] , 'hubloc' => $x[0] ];
+ }
+
+ $r = ActivityStreams::fetch_property($id);
+
+ if($r) {
+ if(array_key_exists('publicKey',$j) && array_key_exists('publicKeyPem',$j['publicKey']) && array_key_exists('id',$j['publicKey'])) {
+ if($j['publicKey']['id'] === $id || $j['id'] === $id) {
+ return [ 'public_key' => self::convertKey($j['publicKey']['publicKeyPem']), 'portable_id' => '', 'hubloc' => [] ];
+ }
+ }
+ }
+
+ return false;
+ }
+
+
+ function get_webfinger_key($id) {
+
+ $x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s' limit 1",
+ dbesc(str_replace('acct:','',$id)),
+ dbesc($id)
+ );
+
+ if($x && $x[0]['xchan_pubkey']) {
+ return [ 'portable_id' => $x[0]['xchan_hash'], 'public_key' => $x[0]['xchan_pubkey'] , 'hubloc' => $x[0] ];
+ }
+
+ $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) {
+
+ $x = q("select * from xchan left join hubloc on xchan_hash = hubloc_hash where hubloc_addr = '%s' or hubloc_id_url = '%s' limit 1",
+ dbesc(str_replace('acct:','',$id)),
+ dbesc($id)
+ );
+ if($x && $x[0]['xchan_pubkey']) {
+ return [ 'portable_id' => $x[0]['xchan_hash'], 'public_key' => $x[0]['xchan_pubkey'] , 'hubloc' => $x[0] ];
+ }
+
+ $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 = \Zotlabs\Lib\Zotfinger::exec($l['href']);
+ if($z) {
+ $i = Zotlabs\Lib\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 = [];
+
+ if($alg === 'sha256') {
+ $algorithm = 'rsa-sha256';
+ }
+ if($alg === 'sha512') {
+ $algorithm = 'rsa-sha512';
+ }
+
+ $x = self::sign($head,$prvkey,$alg);
+
+ $headerval = 'keyId="' . $keyid . '",algorithm="' . $algorithm . '",headers="' . $x['headers'] . '",signature="' . $x['signature'] . '"';
+
+ if($encryption) {
+ $x = crypto_encapsulate($headerval,$encryption['key'],$encryption['algorithm']);
+ if(is_array($x)) {
+ $headerval = 'iv="' . $x['iv'] . '",key="' . $x['key'] . '",alg="' . $x['alg'] . '",data="' . $x['data'] . '"';
+ }
+ }
+
+ if($auth) {
+ $sighead = 'Authorization: Signature ' . $headerval;
+ }
+ else {
+ $sighead = 'Signature: ' . $headerval;
+ }
+
+ if($head) {
+ foreach($head as $k => $v) {
+ // strip the request-target virtual header from the output headers
+ if($k === '(request-target)') {
+ continue;
+ }
+ $return_headers[] = $k . ': ' . $v;
+ }
+ }
+ $return_headers[] = $sighead;
+
+ return $return_headers;
+ }
+
+ /**
+ * @brief set headers
+ *
+ * @param array $headers
+ * @return void
+ */
+
+
+ static function set_headers($headers) {
+ if($headers && is_array($headers)) {
+ foreach($headers as $h) {
+ header($h);
+ }
+ }
+ }
+
+
+ /**
+ * @brief
+ *
+ * @param array $head
+ * @param string $prvkey
+ * @param string $alg (optional) default 'sha256'
+ * @return array
+ */
+
+ static function sign($head, $prvkey, $alg = 'sha256') {
+
+ $ret = [];
+
+ $headers = '';
+ $fields = '';
+
+ if($head) {
+ foreach($head as $k => $v) {
+ $headers .= strtolower($k) . ': ' . trim($v) . "\n";
+ if($fields)
+ $fields .= ' ';
+
+ $fields .= strtolower($k);
+ }
+ // strip the trailing linefeed
+ $headers = rtrim($headers,"\n");
+ }
+
+ $sig = base64_encode(rsa_sign($headers,$prvkey,$alg));
+
+ $ret['headers'] = $fields;
+ $ret['signature'] = $sig;
+
+ return $ret;
+ }
+
+ /**
+ * @brief
+ *
+ * @param string $header
+ * @return array associate array with
+ * - \e string \b keyID
+ * - \e string \b algorithm
+ * - \e array \b headers
+ * - \e string \b signature
+ */
+
+ static function parse_sigheader($header) {
+
+ $ret = [];
+ $matches = [];
+
+ // if the header is encrypted, decrypt with (default) site private key and continue
+
+ if(preg_match('/iv="(.*?)"/ism',$header,$matches))
+ $header = self::decrypt_sigheader($header);
+
+ if(preg_match('/keyId="(.*?)"/ism',$header,$matches))
+ $ret['keyId'] = $matches[1];
+ if(preg_match('/algorithm="(.*?)"/ism',$header,$matches))
+ $ret['algorithm'] = $matches[1];
+ if(preg_match('/headers="(.*?)"/ism',$header,$matches))
+ $ret['headers'] = explode(' ', $matches[1]);
+ if(preg_match('/signature="(.*?)"/ism',$header,$matches))
+ $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
+
+ if(($ret['signature']) && ($ret['algorithm']) && (! $ret['headers']))
+ $ret['headers'] = [ 'date' ];
+
+ return $ret;
+ }
+
+
+ /**
+ * @brief
+ *
+ * @param string $header
+ * @param string $prvkey (optional), if not set use site private key
+ * @return array|string associative array, empty string if failue
+ * - \e string \b iv
+ * - \e string \b key
+ * - \e string \b alg
+ * - \e string \b data
+ */
+
+ static function decrypt_sigheader($header, $prvkey = null) {
+
+ $iv = $key = $alg = $data = null;
+
+ if(! $prvkey) {
+ $prvkey = get_config('system', 'prvkey');
+ }
+
+ $matches = [];
+
+ if(preg_match('/iv="(.*?)"/ism',$header,$matches))
+ $iv = $matches[1];
+ if(preg_match('/key="(.*?)"/ism',$header,$matches))
+ $key = $matches[1];
+ if(preg_match('/alg="(.*?)"/ism',$header,$matches))
+ $alg = $matches[1];
+ if(preg_match('/data="(.*?)"/ism',$header,$matches))
+ $data = $matches[1];
+
+ if($iv && $key && $alg && $data) {
+ return crypto_unencapsulate([ 'encrypted' => true, 'iv' => $iv, 'key' => $key, 'alg' => $alg, 'data' => $data ] , $prvkey);
+ }
+
+ return '';
+ }
+
+}
diff --git a/Zotlabs/Zot6/IHandler.php b/Zotlabs/Zot6/IHandler.php
new file mode 100644
index 000000000..53b6caa89
--- /dev/null
+++ b/Zotlabs/Zot6/IHandler.php
@@ -0,0 +1,18 @@
+<?php
+
+namespace Zotlabs\Zot6;
+
+interface IHandler {
+
+ function Notify($data,$hub);
+
+ function Request($data,$hub);
+
+ function Rekey($sender,$data,$hub);
+
+ function Refresh($sender,$recipients,$hub);
+
+ function Purge($sender,$recipients,$hub);
+
+}
+
diff --git a/Zotlabs/Zot6/Receiver.php b/Zotlabs/Zot6/Receiver.php
new file mode 100644
index 000000000..4f26e2b0c
--- /dev/null
+++ b/Zotlabs/Zot6/Receiver.php
@@ -0,0 +1,220 @@
+<?php
+
+namespace Zotlabs\Zot6;
+
+use Zotlabs\Lib\Config;
+use Zotlabs\Lib\Libzot;
+use Zotlabs\Web\HTTPSig;
+
+class Receiver {
+
+ protected $data;
+ protected $encrypted;
+ protected $error;
+ protected $messagetype;
+ protected $sender;
+ protected $site_id;
+ protected $validated;
+ protected $recipients;
+ protected $response;
+ protected $handler;
+ protected $prvkey;
+ protected $rawdata;
+ protected $sigdata;
+
+ function __construct($handler, $localdata = null) {
+
+ $this->error = false;
+ $this->validated = false;
+ $this->messagetype = '';
+ $this->response = [ 'success' => false ];
+ $this->handler = $handler;
+ $this->data = null;
+ $this->rawdata = null;
+ $this->site_id = null;
+ $this->prvkey = Config::get('system','prvkey');
+
+ if($localdata) {
+ $this->rawdata = $localdata;
+ }
+ else {
+ $this->rawdata = file_get_contents('php://input');
+
+ // All access to the zot endpoint must use http signatures
+
+ if (! $this->Valid_Httpsig()) {
+ logger('signature failed');
+ $this->error = true;
+ $this->response['message'] = 'signature invalid';
+ return;
+ }
+ }
+
+ logger('received raw: ' . print_r($this->rawdata,true), LOGGER_DATA);
+
+
+ if ($this->rawdata) {
+ $this->data = json_decode($this->rawdata,true);
+ }
+ else {
+ $this->error = true;
+ $this->response['message'] = 'no data';
+ }
+
+ logger('received_json: ' . json_encode($this->data,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES), LOGGER_DATA);
+
+ logger('received: ' . print_r($this->data,true), LOGGER_DATA);
+
+ if ($this->data && is_array($this->data)) {
+ $this->encrypted = ((array_key_exists('encrypted',$this->data) && intval($this->data['encrypted'])) ? true : false);
+
+ if ($this->encrypted && $this->prvkey) {
+ $uncrypted = crypto_unencapsulate($this->data,$this->prvkey);
+ if ($uncrypted) {
+ $this->data = json_decode($uncrypted,true);
+ }
+ else {
+ $this->error = true;
+ $this->response['message'] = 'no data';
+ }
+ }
+ }
+ }
+
+
+ function run() {
+
+ if ($this->error) {
+ // make timing attacks on the decryption engine a bit more difficult
+ usleep(mt_rand(10000,100000));
+ return($this->response);
+ }
+
+ if ($this->data) {
+ if (array_key_exists('type',$this->data)) {
+ $this->messagetype = $this->data['type'];
+ }
+
+ if (! $this->messagetype) {
+ $this->error = true;
+ $this->response['message'] = 'no datatype';
+ return $this->response;
+ }
+
+ $this->sender = ((array_key_exists('sender',$this->data)) ? $this->data['sender'] : null);
+ $this->recipients = ((array_key_exists('recipients',$this->data)) ? $this->data['recipients'] : null);
+ $this->site_id = ((array_key_exists('site_id',$this->data)) ? $this->data['site_id'] : null);
+ }
+
+ if ($this->sender) {
+ $result = $this->ValidateSender();
+ if (! $result) {
+ $this->error = true;
+ return $this->response;
+ }
+ }
+
+ return $this->Dispatch();
+ }
+
+ function ValidateSender() {
+
+ $hub = Libzot::valid_hub($this->sender,$this->site_id);
+
+ if (! $hub) {
+ $x = Libzot::register_hub($this->sigdata['signer']);
+ if($x['success']) {
+ $hub = Libzot::valid_hub($this->sender,$this->site_id);
+ }
+ if(! $hub) {
+ $this->response['message'] = 'sender unknown';
+ return false;
+ }
+ }
+
+ if (! check_siteallowed($hub['hubloc_url'])) {
+ $this->response['message'] = 'forbidden';
+ return false;
+ }
+
+ if (! check_channelallowed($this->sender)) {
+ $this->response['message'] = 'forbidden';
+ return false;
+ }
+
+ Libzot::update_hub_connected($hub,$this->site_id);
+
+ $this->validated = true;
+ $this->hub = $hub;
+ return true;
+ }
+
+
+ function Valid_Httpsig() {
+
+ $result = false;
+
+ $this->sigdata = HTTPSig::verify($this->rawdata);
+
+ if ($this->sigdata && $this->sigdata['header_signed'] && $this->sigdata['header_valid']) {
+ $result = true;
+
+ // It is OK to not have signed content - not all messages provide content.
+ // But if it is signed, it has to be valid
+
+ if (($this->sigdata['content_signed']) && (! $this->sigdata['content_valid'])) {
+ $result = false;
+ }
+ }
+ return $result;
+ }
+
+ function Dispatch() {
+
+ switch ($this->messagetype) {
+
+ case 'request':
+ $this->response = $this->handler->Request($this->data,$this->hub);
+ break;
+
+ case 'purge':
+ $this->response = $this->handler->Purge($this->sender,$this->recipients,$this->hub);
+ break;
+
+ case 'refresh':
+ $this->response = $this->handler->Refresh($this->sender,$this->recipients,$this->hub);
+ break;
+
+ case 'rekey':
+ $this->response = $this->handler->Rekey($this->sender, $this->data,$this->hub);
+ break;
+
+ case 'activity':
+ case 'response': // upstream message
+ case 'sync':
+ default:
+ $this->response = $this->handler->Notify($this->data,$this->hub);
+ break;
+
+ }
+
+ logger('response_to_return: ' . print_r($this->response,true),LOGGER_DATA);
+
+ if ($this->encrypted) {
+ $this->EncryptResponse();
+ }
+
+ return($this->response);
+ }
+
+ function EncryptResponse() {
+ $algorithm = Libzot::best_algorithm($this->hub['site_crypto']);
+ if ($algorithm) {
+ $this->response = crypto_encapsulate(json_encode($this->response),$this->hub['hubloc_sitekey'], $algorithm);
+ }
+ }
+
+}
+
+
+
diff --git a/Zotlabs/Zot6/Zot6Handler.php b/Zotlabs/Zot6/Zot6Handler.php
new file mode 100644
index 000000000..5597921cc
--- /dev/null
+++ b/Zotlabs/Zot6/Zot6Handler.php
@@ -0,0 +1,266 @@
+<?php
+
+namespace Zotlabs\Zot6;
+
+use Zotlabs\Lib\Libzot;
+use Zotlabs\Lib\Queue;
+
+class Zot6Handler implements IHandler {
+
+ function Notify($data,$hub) {
+ return self::reply_notify($data,$hub);
+ }
+
+ function Request($data,$hub) {
+ return self::reply_message_request($data,$hub);
+ }
+
+ function Rekey($sender,$data,$hub) {
+ return self::reply_rekey_request($sender,$data,$hub);
+ }
+
+ function Refresh($sender,$recipients,$hub) {
+ return self::reply_refresh($sender,$recipients,$hub);
+ }
+
+ function Purge($sender,$recipients,$hub) {
+ return self::reply_purge($sender,$recipients,$hub);
+ }
+
+
+ // Implementation of specific methods follows;
+ // These generally do a small amout of validation and call Libzot
+ // to do any heavy lifting
+
+ static function reply_notify($data,$hub) {
+
+ $ret = [ 'success' => false ];
+
+ logger('notify received from ' . $hub['hubloc_url']);
+
+ $x = Libzot::fetch($data);
+ $ret['delivery_report'] = $x;
+
+
+ $ret['success'] = true;
+ return $ret;
+ }
+
+
+
+ /**
+ * @brief Remote channel info (such as permissions or photo or something)
+ * has been updated. Grab a fresh copy and sync it.
+ *
+ * The difference between refresh and force_refresh is that force_refresh
+ * unconditionally creates a directory update record, even if no changes were
+ * detected upon processing.
+ *
+ * @param array $sender
+ * @param array $recipients
+ *
+ * @return json_return_and_die()
+ */
+
+ static function reply_refresh($sender, $recipients,$hub) {
+ $ret = array('success' => false);
+
+ if($recipients) {
+
+ // This would be a permissions update, typically for one connection
+
+ foreach ($recipients as $recip) {
+ $r = q("select channel.*,xchan.* from channel
+ left join xchan on channel_hash = xchan_hash
+ where channel_hash ='%s' limit 1",
+ dbesc($recip)
+ );
+
+ $x = Libzot::refresh( [ 'hubloc_id_url' => $hub['hubloc_id_url'] ], $r[0], (($msgtype === 'force_refresh') ? true : false));
+ }
+ }
+ else {
+ // system wide refresh
+
+ $x = Libzot::refresh( [ 'hubloc_id_url' => $hub['hubloc_id_url'] ], null, (($msgtype === 'force_refresh') ? true : false));
+ }
+
+ $ret['success'] = true;
+ return $ret;
+ }
+
+
+
+ /**
+ * @brief Process a message request.
+ *
+ * If a site receives a comment to a post but finds they have no parent to attach it with, they
+ * may send a 'request' packet containing the message_id of the missing parent. This is the handler
+ * for that packet. We will create a message_list array of the entire conversation starting with
+ * the missing parent and invoke delivery to the sender of the packet.
+ *
+ * Zotlabs/Daemon/Deliver.php (for local delivery) and
+ * mod/post.php???? @fixme (for web delivery) detect the existence of
+ * this 'message_list' at the destination and split it into individual messages which are
+ * processed/delivered in order.
+ *
+ *
+ * @param array $data
+ * @return array
+ */
+
+ static function reply_message_request($data,$hub) {
+ $ret = [ 'success' => false ];
+
+ $message_id = EMPTY_STR;
+
+ if(array_key_exists('data',$data))
+ $ptr = $data['data'];
+ if(is_array($ptr) && array_key_exists(0,$ptr)) {
+ $ptr = $ptr[0];
+ }
+ if(is_string($ptr)) {
+ $message_id = $ptr;
+ }
+ if(is_array($ptr) && array_key_exists('id',$ptr)) {
+ $message_id = $ptr['id'];
+ }
+
+ if (! $message_id) {
+ $ret['message'] = 'no message_id';
+ logger('no message_id');
+ return $ret;
+ }
+
+ $sender = $hub['hubloc_hash'];
+
+ /*
+ * Find the local channel in charge of this post (the first and only recipient of the request packet)
+ */
+
+ $arr = $data['recipients'][0];
+
+ $c = q("select * from channel left join xchan on channel_hash = xchan_hash where channel_hash = '%s' limit 1",
+ dbesc($arr['portable_id'])
+ );
+ if (! $c) {
+ logger('recipient channel not found.');
+ $ret['message'] .= 'recipient not found.' . EOL;
+ return $ret;
+ }
+
+ /*
+ * fetch the requested conversation
+ */
+
+ $messages = zot_feed($c[0]['channel_id'],$sender_hash, [ 'message_id' => $data['message_id'], 'encoding' => 'activitystreams' ]);
+
+ return (($messages) ? : [] );
+
+ }
+
+ static function rekey_request($sender,$data,$hub) {
+
+ $ret = array('success' => false);
+
+ // newsig is newkey signed with oldkey
+
+ // The original xchan will remain. In Zot/Receiver we will have imported the new xchan and hubloc to verify
+ // the packet authenticity. What we will do now is verify that the keychange operation was signed by the
+ // oldkey, and if so change all the abook, abconfig, group, and permission elements which reference the
+ // old xchan_hash.
+
+ if((! $data['old_key']) && (! $data['new_key']) && (! $data['new_sig']))
+ return $ret;
+
+
+ $old = null;
+
+ if(Libzot::verify($data['old_guid'],$data['old_guid_sig'],$data['old_key'])) {
+ $oldhash = make_xchan_hash($data['old_guid'],$data['old_key']);
+ $old = q("select * from xchan where xchan_hash = '%s' limit 1",
+ dbesc($oldhash)
+ );
+ }
+ else
+ return $ret;
+
+
+ if(! $old) {
+ return $ret;
+ }
+
+ $xchan = $old[0];
+
+ if(! Libzot::verify($data['new_key'],$data['new_sig'],$xchan['xchan_pubkey'])) {
+ return $ret;
+ }
+
+ $r = q("select * from xchan where xchan_hash = '%s' limit 1",
+ dbesc($sender)
+ );
+
+ $newxchan = $r[0];
+
+ // @todo
+ // if ! $update create a linked identity
+
+
+ xchan_change_key($xchan,$newxchan,$data);
+
+ $ret['success'] = true;
+ return $ret;
+ }
+
+
+ /**
+ * @brief
+ *
+ * @param array $sender
+ * @param array $recipients
+ *
+ * return json_return_and_die()
+ */
+
+ static function reply_purge($sender, $recipients, $hub) {
+
+ $ret = array('success' => false);
+
+ if ($recipients) {
+ // basically this means "unfriend"
+ foreach ($recipients as $recip) {
+ $r = q("select channel.*,xchan.* from channel
+ left join xchan on channel_hash = xchan_hash
+ where channel_hash = '%s' and channel_guid_sig = '%s' limit 1",
+ dbesc($recip)
+ );
+ if ($r) {
+ $r = q("select abook_id from abook where uid = %d and abook_xchan = '%s' limit 1",
+ intval($r[0]['channel_id']),
+ dbesc($sender)
+ );
+ if ($r) {
+ contact_remove($r[0]['channel_id'],$r[0]['abook_id']);
+ }
+ }
+ }
+ $ret['success'] = true;
+ }
+ else {
+
+ // Unfriend everybody - basically this means the channel has committed suicide
+
+ remove_all_xchan_resources($sender);
+
+ $ret['success'] = true;
+ }
+
+ return $ret;
+ }
+
+
+
+
+
+
+}