}
/**
- * Get the Salmon keypair from a URI, uses XRD Discovery etc.
+ * Retrieve Salmon keypair first by checking local database, but
+ * if it's not found, attempt discovery if it has been requested.
*
- * @return Magicsig with loaded keypair
+ * @param Profile $profile The profile we're looking up keys for.
+ * @param boolean $discovery Network discovery if no local cache?
*/
- public function getKeyPair($signer_uri)
+ public function getKeyPair(Profile $profile, $discovery=false) {
+ $magicsig = Magicsig::getKV('user_id', $profile->id);
+
+ if ($discovery && !$magicsig instanceof Magicsig) {
+ // Throws exception on failure, but does not try to _load_ the keypair string.
+ $keypair = $this->discoverKeyPair($profile);
+
+ $magicsig = new Magicsig();
+ $magicsig->user_id = $profile->id;
+ $magicsig->importKeys($keypair);
+ // save the public key for this profile in our database.
+ // TODO: If the profile generates a new key remotely, we must be able to replace
+ // this (of course after callback-verification).
+ $magicsig->insert();
+ } elseif (!$magicsig instanceof Magicsig) { // No discovery request, so we'll give up.
+ throw new ServerException(sprintf('No public key found for profile (id==%d)', $profile->id));
+ }
+
+ assert($magicsig->publicKey instanceof Crypt_RSA);
+
+ return $magicsig;
+ }
+
+ /**
+ * Get the Salmon keypair from a URI, uses XRD Discovery etc. Reasonably
+ * you'll only get the public key ;)
+ *
+ * The string will (hopefully) be formatted as described in Magicsig specification:
+ * https://salmon-protocol.googlecode.com/svn/trunk/draft-panzer-magicsig-01.html#anchor13
+ *
+ * @return string formatted as Magicsig keypair
+ */
+ public function discoverKeyPair(Profile $profile)
{
+ $signer_uri = $profile->getUri();
+ if (empty($signer_uri)) {
+ throw new ServerException(sprintf('Profile missing URI (id==%d)', $profile->id));
+ }
+
$disco = new Discovery();
// Throws exception on lookup problems
throw new Exception(_m('Incorrectly formatted public key element.'));
}
- $magicsig = Magicsig::fromString($keypair);
- if (!$magicsig instanceof Magicsig) {
- common_debug('Salmon error: unable to parse keypair: '.var_export($keypair,true));
- // TRANS: Exception when public key was properly formatted but not parsable.
- throw new ServerException(_m('Retrieved Salmon keypair could not be parsed.'));
- }
-
- return $magicsig;
+ return $keypair;
}
/**
* @param <type> $text
* @param <type> $mimetype
* @param Magicsig $magicsig Magicsig with private key available.
+ *
* @return MagicEnvelope object with all properties set
+ *
+ * @throws Exception of various kinds on signing failure
*/
- public static function signMessage($text, $mimetype, Magicsig $magicsig)
+ public function signMessage($text, $mimetype, Magicsig $magicsig)
{
- $magic_env = new MagicEnvelope();
+ assert($magicsig->privateKey instanceof Crypt_RSA);
// Prepare text and metadata for signing
- $magic_env->data = Magicsig::base64_url_encode($text);
- $magic_env->data_type = $mimetype;
- $magic_env->encoding = self::ENCODING;
- $magic_env->alg = $magicsig->getName();
- // Get the actual signature
- $magic_env->sig = $magicsig->sign($magic_env->signingText());
+ $this->data = Magicsig::base64_url_encode($text);
+ $this->data_type = $mimetype;
+ $this->encoding = self::ENCODING;
+ $this->alg = $magicsig->getName();
- return $magic_env;
+ // Get the actual signature
+ $this->sig = $magicsig->sign($this->signingText());
}
/**
$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->sig);
+ $xs->element('me:sig', null, $this->getSignature());
$xs->elementEnd('me:env');
$string = $xs->getString();
- common_debug('MagicEnvelope XML: ' . $string);
return $string;
}
- /**
+ /*
* Extract the contained XML payload, and insert a copy of the envelope
* signature data as an <me:provenance> section.
*
- * @return string representation of modified XML document
+ * @return DOMDocument of Atom entry
*
* @fixme in case of XML parsing errors, this will spew to the error log or output
*/
- public function unfold()
+ public function getPayload()
{
$dom = new DOMDocument();
- $dom->loadXML(Magicsig::base64_url_decode($this->data));
+ if (!$dom->loadXML(Magicsig::base64_url_decode($this->data))) {
+ throw new ServerException('Malformed XML in Salmon payload');
+ }
- if ($dom->documentElement->tagName != 'entry') {
- return false;
+ 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 ServerException('Unknown Salmon payload data type');
}
+ return $dom;
+ }
- $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->sig);
- $prov->appendChild($sig);
-
- $dom->documentElement->appendChild($prov);
-
- return $dom->saveXML();
+ public function getSignature()
+ {
+ return $this->sig;
}
/**
- * Find the author URI referenced in the given Atom entry.
- *
- * @param string $text string containing Atom entry XML
- * @return mixed URI string or false if XML parsing fails, or null if no author URI can be found
+ * Find the author URI referenced in the payload Atom entry.
*
- * @fixme XML parsing failures will spew to error logs/output
+ * @return string URI for author
+ * @throws ServerException on failure
*/
- public function getAuthorUri($text) {
- $doc = new DOMDocument();
- if (!$doc->loadXML($text)) {
- return FALSE;
- }
-
- if ($doc->documentElement->tagName == 'entry') {
- $authors = $doc->documentElement->getElementsByTagName('author');
- foreach ($authors as $author) {
- $uris = $author->getElementsByTagName('uri');
- foreach ($uris as $uri) {
- return $uri->nodeValue;
- }
+ 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');
}
/**
*
* Details of failure conditions are dumped to output log and not exposed to caller.
*
+ * @param Profile $profile profile used to get locally cached public signature key
+ * or if necessary perform discovery on.
+ *
* @return boolean
*/
- public function verify()
+ public function verify(Profile $profile)
{
if ($this->alg != 'RSA-SHA256') {
- common_log(LOG_DEBUG, "Salmon error: bad algorithm");
+ common_debug("Salmon error: bad algorithm");
return false;
}
if ($this->encoding != self::ENCODING) {
- common_log(LOG_DEBUG, "Salmon error: bad encoding");
+ common_debug("Salmon error: bad encoding");
return false;
}
- // $this->data is base64_url_encoded and should contain XML which is passed to getAuthorUri
- $text = Magicsig::base64_url_decode($this->data);
- $signer_uri = $this->getAuthorUri($text);
-
try {
- $magicsig = $this->getKeyPair($signer_uri);
+ $magicsig = $this->getKeyPair($profile, true); // Do discovery too if necessary
} catch (Exception $e) {
- common_log(LOG_DEBUG, "Salmon error: ".$e->getMessage());
+ common_debug("Salmon error: ".$e->getMessage());
return false;
}
- return $magicsig->verify($this->signingText(), $this->sig);
+ return $magicsig->verify($this->signingText(), $this->getSignature());
}
/**
* on some systems.
*
* @param string $text XML fragment to sign, assumed to be Atom
- * @param Profile $actor Profile of a local user to use as signer
+ * @param User $user User who cryptographically signs $text
*
- * @return string XML string representation of magic envelope
+ * @return MagicEnvelope object complete with signature
*
* @throws Exception on bad profile input or key generation problems
- * @fixme if signing fails, this seems to return the original text without warning. Is there a reason for this?
*/
- public static function signForProfile($text, Profile $actor)
+ public static function signAsUser($text, User $user)
{
- // We only generate keys for our local users of course, so let
- // getUser throw an exception if the profile is not local.
- $user = $actor->getUser();
-
// Find already stored key
$magicsig = Magicsig::getKV('user_id', $user->id);
if (!$magicsig instanceof Magicsig) {
- // No keypair yet, let's generate one.
- $magicsig = new Magicsig();
- $magicsig->generate($user->id);
+ $magicsig = Magicsig::generate($user);
}
+ assert($magicsig instanceof Magicsig);
+ assert($magicsig->privateKey instanceof Crypt_RSA);
- $magic_env = self::signMessage($text, 'application/atom+xml', $magicsig);
-
- assert($magic_env instanceof MagicEnvelope);
+ $magic_env = new MagicEnvelope();
+ $magic_env->signMessage($text, 'application/atom+xml', $magicsig);
return $magic_env;
}