123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440 |
- <?php
- class MagicEnvelope
- {
- const ENCODING = 'base64url';
- const NS = 'http://salmon-protocol.org/ns/magic-env';
- protected $actor = null;
- protected $data = null;
- protected $data_type = null;
- protected $encoding = null;
- protected $alg = null;
- protected $sig = null;
-
- public function __construct($xml=null, Profile $actor=null) {
- if (!empty($xml)) {
- $dom = new DOMDocument();
- if (!$dom->loadXML($xml)) {
- throw new ServerException('Tried to load malformed XML as DOM');
- } elseif (!$this->fromDom($dom)) {
- throw new ServerException('Could not load MagicEnvelope from DOM');
- }
- } elseif ($actor instanceof Profile) {
-
-
-
-
-
-
-
- $this->setActor($actor);
- }
- }
-
- public function getKeyPair(Profile $profile, $discovery=false) {
- if (!$profile->isLocal()) common_debug('Getting magic-public-key for non-local profile id=='.$profile->getID());
- $magicsig = Magicsig::getKV('user_id', $profile->getID());
- if ($discovery && !$magicsig instanceof Magicsig) {
- if (!$profile->isLocal()) common_debug('magic-public-key not found, will do discovery for profile id=='.$profile->getID());
-
- $keypair = $this->discoverKeyPair($profile);
- $magicsig = new Magicsig();
- $magicsig->user_id = $profile->getID();
- $magicsig->importKeys($keypair);
-
-
-
- $magicsig->insert();
- } elseif (!$magicsig instanceof Magicsig) {
- throw new ServerException(sprintf('No public key found for profile (id==%d)', $profile->id));
- }
- assert($magicsig->publicKey instanceof \phpseclib\Crypt\RSA);
- return $magicsig;
- }
-
- public function discoverKeyPair(Profile $profile)
- {
- $signer_uri = $profile->getUri();
- if (empty($signer_uri)) {
- throw new ServerException(sprintf('Profile missing URI (id==%d)', $profile->getID()));
- }
- $disco = new Discovery();
-
- try {
- $xrd = $disco->lookup($signer_uri);
- } catch (Exception $e) {
-
- $xrd = $disco->lookup($profile->getAcctUri());
- }
- common_debug('Will try to find magic-public-key from XRD of profile id=='.$profile->getID());
- $pubkey = null;
- if (Event::handle('MagicsigPublicKeyFromXRD', array($xrd, &$pubkey))) {
- $link = $xrd->get(Magicsig::PUBLICKEYREL);
- if (is_null($link)) {
-
- throw new Exception(_m('Unable to locate signer public key.'));
- }
- $pubkey = $link->href;
- }
- if (empty($pubkey)) {
- throw new ServerException('Empty Magicsig public key. A bug?');
- }
-
- $keypair = false;
- $parts = explode(',', $pubkey);
- if (count($parts) == 2) {
- $keypair = $parts[1];
- } else {
-
- $parts = explode(';', $pubkey);
- if (count($parts) == 2) {
- $keypair = $parts[1];
- }
- }
- if ($keypair === false) {
-
-
- throw new Exception(_m('Incorrectly formatted public key element.'));
- }
- return $keypair;
- }
-
- public function signingText() {
- return implode('.', array($this->data,
- Magicsig::base64_url_encode($this->data_type),
- Magicsig::base64_url_encode($this->encoding),
- Magicsig::base64_url_encode($this->alg)));
- }
-
- public function signMessage($text, $mimetype)
- {
- if (!$this->actor instanceof Profile) {
- throw new ServerException('No profile to sign message with is set.');
- } elseif (!$this->actor->isLocal()) {
- throw new ServerException('Cannot sign magic envelopes with remote users since we have no private key.');
- }
-
- $magicsig = Magicsig::getKV('user_id', $this->actor->getID());
- if (!$magicsig instanceof Magicsig) {
-
- $magicsig = Magicsig::generate($this->actor->getUser());
- }
- assert($magicsig instanceof Magicsig);
- assert($magicsig->privateKey instanceof \phpseclib\Crypt\RSA);
-
- $this->data = Magicsig::base64_url_encode($text);
- $this->data_type = $mimetype;
- $this->encoding = self::ENCODING;
- $this->alg = $magicsig->getName();
-
- $this->sig = $magicsig->sign($this->signingText());
- }
-
- public function toXML(Profile $target=null, $flavour=null) {
- $xs = new XMLStringer();
- $xs->startXML();
- if (Event::handle('StartMagicEnvelopeToXML', array($this, $xs, $flavour, $target))) {
-
-
- $xs->elementStart('me:env', array('xmlns:me' => self::NS));
- $xs->element('me:data', array('type' => $this->data_type), $this->data);
- $xs->element('me:encoding', null, $this->encoding);
- $xs->element('me:alg', null, $this->alg);
- $xs->element('me:sig', null, $this->getSignature());
- $xs->elementEnd('me:env');
- Event::handle('EndMagicEnvelopeToXML', array($this, $xs, $flavour, $target));
- }
- return $xs->getString();
- }
-
- public function getPayload()
- {
- $dom = new DOMDocument();
- if (!$dom->loadXML(Magicsig::base64_url_decode($this->data))) {
- throw new ClientException('Malformed XML in Salmon payload');
- }
- switch ($this->data_type) {
- case 'application/atom+xml':
- if ($dom->documentElement->namespaceURI !== Activity::ATOM
- || $dom->documentElement->tagName !== 'entry') {
- throw new ServerException(_m('Salmon post must be an Atom entry.'));
- }
- $prov = $dom->createElementNS(self::NS, 'me:provenance');
- $prov->setAttribute('xmlns:me', self::NS);
- $data = $dom->createElementNS(self::NS, 'me:data', $this->data);
- $data->setAttribute('type', $this->data_type);
- $prov->appendChild($data);
- $enc = $dom->createElementNS(self::NS, 'me:encoding', $this->encoding);
- $prov->appendChild($enc);
- $alg = $dom->createElementNS(self::NS, 'me:alg', $this->alg);
- $prov->appendChild($alg);
- $sig = $dom->createElementNS(self::NS, 'me:sig', $this->getSignature());
- $prov->appendChild($sig);
- $dom->documentElement->appendChild($prov);
- break;
- default:
- throw new ClientException('Unknown Salmon payload data type');
- }
- return $dom;
- }
- public function getSignature()
- {
- if (empty($this->sig)) {
- throw new ServerException('You must first call signMessage before getSignature');
- }
- return $this->sig;
- }
- public function getSignatureAlgorithm()
- {
- return $this->alg;
- }
- public function getData()
- {
- return $this->data;
- }
- public function getDataType()
- {
- return $this->data_type;
- }
- public function getEncoding()
- {
- return $this->encoding;
- }
-
- public function getAuthorUri() {
- $doc = $this->getPayload();
- $authors = $doc->documentElement->getElementsByTagName('author');
- foreach ($authors as $author) {
- $uris = $author->getElementsByTagName('uri');
- foreach ($uris as $uri) {
- return $uri->nodeValue;
- }
- }
- throw new ServerException('No author URI found in Salmon payload data');
- }
-
- public function verify(Profile $profile)
- {
- if ($this->alg != 'RSA-SHA256') {
- common_log(LOG_DEBUG, 'Salmon error: bad algorithm: '._ve($this->alg));
- return false;
- }
- if ($this->encoding != self::ENCODING) {
- common_log(LOG_DEBUG, 'Salmon error: bad encoding: '._ve($this->encoding));
- return false;
- }
- try {
- $magicsig = $this->getKeyPair($profile, true);
- } catch (Exception $e) {
- common_log(LOG_DEBUG, "Salmon error: getKeyPair for profile id=={$profile->getID()}: "._ve($e->getMessage()));
- return false;
- }
- if (!$magicsig->verify($this->signingText(), $this->getSignature())) {
- common_log(LOG_INFO, 'Salmon signature verification failed for profile id=='.$profile->getID());
-
- throw new ClientException(_m('Salmon signature verification failed.'));
- }
- common_debug('Salmon signature verification successful for profile id=='.$profile->getID());
- $this->setActor($profile);
- return true;
- }
-
- protected function fromDom(DOMDocument $dom)
- {
- $env_element = $dom->getElementsByTagNameNS(self::NS, 'env')->item(0);
- if (!$env_element) {
- $env_element = $dom->getElementsByTagNameNS(self::NS, 'provenance')->item(0);
- }
- if (!$env_element) {
- return false;
- }
- $data_element = $env_element->getElementsByTagNameNS(self::NS, 'data')->item(0);
- $sig_element = $env_element->getElementsByTagNameNS(self::NS, 'sig')->item(0);
- $this->data = preg_replace('/\s/', '', $data_element->nodeValue);
- $this->data_type = $data_element->getAttribute('type');
- $this->encoding = $env_element->getElementsByTagNameNS(self::NS, 'encoding')->item(0)->nodeValue;
- $this->alg = $env_element->getElementsByTagNameNS(self::NS, 'alg')->item(0)->nodeValue;
- $this->sig = preg_replace('/\s/', '', $sig_element->nodeValue);
- return true;
- }
- public function setActor(Profile $actor)
- {
- if ($this->actor instanceof Profile) {
- throw new ServerException('Cannot set a new actor profile for MagicEnvelope object.');
- }
- $this->actor = $actor;
- }
- public function getActor()
- {
- if (!$this->actor instanceof Profile) {
- throw new ServerException('No actor set for this magic envelope.');
- }
- return $this->actor;
- }
-
- public static function signAsUser($text, User $user)
- {
- $magic_env = new MagicEnvelope(null, $user->getProfile());
- $magic_env->signMessage($text, 'application/atom+xml');
- return $magic_env;
- }
- }
|