From b2034fdfec040a67988e543a911208ef2491ce7a Mon Sep 17 00:00:00 2001 From: Hugues Hiegel Date: Sun, 22 Feb 2015 12:58:46 +0100 Subject: New RoundCube Plugins Git folder --- enigma/lib/enigma_driver.php | 106 +++++++ enigma/lib/enigma_driver_gnupg.php | 303 ++++++++++++++++++++ enigma/lib/enigma_driver_phpssl.php | 238 ++++++++++++++++ enigma/lib/enigma_engine.php | 554 ++++++++++++++++++++++++++++++++++++ enigma/lib/enigma_error.php | 64 +++++ enigma/lib/enigma_key.php | 129 +++++++++ enigma/lib/enigma_signature.php | 34 +++ enigma/lib/enigma_subkey.php | 57 ++++ enigma/lib/enigma_ui.php | 455 +++++++++++++++++++++++++++++ enigma/lib/enigma_userid.php | 31 ++ 10 files changed, 1971 insertions(+) create mode 100644 enigma/lib/enigma_driver.php create mode 100644 enigma/lib/enigma_driver_gnupg.php create mode 100644 enigma/lib/enigma_driver_phpssl.php create mode 100644 enigma/lib/enigma_engine.php create mode 100644 enigma/lib/enigma_error.php create mode 100644 enigma/lib/enigma_key.php create mode 100644 enigma/lib/enigma_signature.php create mode 100644 enigma/lib/enigma_subkey.php create mode 100644 enigma/lib/enigma_ui.php create mode 100644 enigma/lib/enigma_userid.php (limited to 'enigma/lib') diff --git a/enigma/lib/enigma_driver.php b/enigma/lib/enigma_driver.php new file mode 100644 index 0000000..a9a3e47 --- /dev/null +++ b/enigma/lib/enigma_driver.php @@ -0,0 +1,106 @@ + | + +-------------------------------------------------------------------------+ +*/ + +abstract class enigma_driver +{ + /** + * Class constructor. + * + * @param string User name (email address) + */ + abstract function __construct($user); + + /** + * Driver initialization. + * + * @return mixed NULL on success, enigma_error on failure + */ + abstract function init(); + + /** + * Encryption. + */ + abstract function encrypt($text, $keys); + + /** + * Decryption.. + */ + abstract function decrypt($text, $key, $passwd); + + /** + * Signing. + */ + abstract function sign($text, $key, $passwd); + + /** + * Signature verification. + * + * @param string Message body + * @param string Signature, if message is of type PGP/MIME and body doesn't contain it + * + * @return mixed Signature information (enigma_signature) or enigma_error + */ + abstract function verify($text, $signature); + + /** + * Key/Cert file import. + * + * @param string File name or file content + * @param bollean True if first argument is a filename + * + * @return mixed Import status array or enigma_error + */ + abstract function import($content, $isfile=false); + + /** + * Keys listing. + * + * @param string Optional pattern for key ID, user ID or fingerprint + * + * @return mixed Array of enigma_key objects or enigma_error + */ + abstract function list_keys($pattern=''); + + /** + * Single key information. + * + * @param string Key ID, user ID or fingerprint + * + * @return mixed Key (enigma_key) object or enigma_error + */ + abstract function get_key($keyid); + + /** + * Key pair generation. + * + * @param array Key/User data + * + * @return mixed Key (enigma_key) object or enigma_error + */ + abstract function gen_key($data); + + /** + * Key deletion. + */ + abstract function del_key($keyid); +} diff --git a/enigma/lib/enigma_driver_gnupg.php b/enigma/lib/enigma_driver_gnupg.php new file mode 100644 index 0000000..c4280a0 --- /dev/null +++ b/enigma/lib/enigma_driver_gnupg.php @@ -0,0 +1,303 @@ + | + +-------------------------------------------------------------------------+ +*/ + +require_once 'Crypt/GPG.php'; + +class enigma_driver_gnupg extends enigma_driver +{ + private $rc; + private $gpg; + private $homedir; + private $user; + + function __construct($user) + { + $rcmail = rcmail::get_instance(); + $this->rc = $rcmail; + $this->user = $user; + } + + /** + * Driver initialization and environment checking. + * Should only return critical errors. + * + * @return mixed NULL on success, enigma_error on failure + */ + function init() + { + $homedir = $this->rc->config->get('enigma_pgp_homedir', INSTALL_PATH . '/plugins/enigma/home'); + + if (!$homedir) + return new enigma_error(enigma_error::E_INTERNAL, + "Option 'enigma_pgp_homedir' not specified"); + + // check if homedir exists (create it if not) and is readable + if (!file_exists($homedir)) + return new enigma_error(enigma_error::E_INTERNAL, + "Keys directory doesn't exists: $homedir"); + if (!is_writable($homedir)) + return new enigma_error(enigma_error::E_INTERNAL, + "Keys directory isn't writeable: $homedir"); + + $homedir = $homedir . '/' . $this->user; + + // check if user's homedir exists (create it if not) and is readable + if (!file_exists($homedir)) + mkdir($homedir, 0700); + + if (!file_exists($homedir)) + return new enigma_error(enigma_error::E_INTERNAL, + "Unable to create keys directory: $homedir"); + if (!is_writable($homedir)) + return new enigma_error(enigma_error::E_INTERNAL, + "Unable to write to keys directory: $homedir"); + + $this->homedir = $homedir; + + // Create Crypt_GPG object + try { + $this->gpg = new Crypt_GPG(array( + 'homedir' => $this->homedir, +// 'debug' => true, + )); + } + catch (Exception $e) { + return $this->get_error_from_exception($e); + } + } + + function encrypt($text, $keys) + { +/* + foreach ($keys as $key) { + $this->gpg->addEncryptKey($key); + } + $enc = $this->gpg->encrypt($text); + return $enc; +*/ + } + + function decrypt($text, $key, $passwd) + { +// $this->gpg->addDecryptKey($key, $passwd); + try { + $dec = $this->gpg->decrypt($text); + return $dec; + } + catch (Exception $e) { + return $this->get_error_from_exception($e); + } + } + + function sign($text, $key, $passwd) + { +/* + $this->gpg->addSignKey($key, $passwd); + $signed = $this->gpg->sign($text, Crypt_GPG::SIGN_MODE_DETACHED); + return $signed; +*/ + } + + function verify($text, $signature) + { + try { + $verified = $this->gpg->verify($text, $signature); + return $this->parse_signature($verified[0]); + } + catch (Exception $e) { + return $this->get_error_from_exception($e); + } + } + + public function import($content, $isfile=false) + { + try { + if ($isfile) + return $this->gpg->importKeyFile($content); + else + return $this->gpg->importKey($content); + } + catch (Exception $e) { + return $this->get_error_from_exception($e); + } + } + + public function list_keys($pattern='') + { + try { + $keys = $this->gpg->getKeys($pattern); + $result = array(); +//print_r($keys); + foreach ($keys as $idx => $key) { + $result[] = $this->parse_key($key); + unset($keys[$idx]); + } +//print_r($result); + return $result; + } + catch (Exception $e) { + return $this->get_error_from_exception($e); + } + } + + public function get_key($keyid) + { + $list = $this->list_keys($keyid); + + if (is_array($list)) + return array_shift($list); + + // error + return $list; + } + + public function gen_key($data) + { + } + + public function del_key($keyid) + { +// $this->get_key($keyid); + } + + public function del_privkey($keyid) + { + try { + $this->gpg->deletePrivateKey($keyid); + return true; + } + catch (Exception $e) { + return $this->get_error_from_exception($e); + } + } + + public function del_pubkey($keyid) + { + try { + $this->gpg->deletePublicKey($keyid); + return true; + } + catch (Exception $e) { + return $this->get_error_from_exception($e); + } + } + + /** + * Converts Crypt_GPG exception into Enigma's error object + * + * @param mixed Exception object + * + * @return enigma_error Error object + */ + private function get_error_from_exception($e) + { + $data = array(); + + if ($e instanceof Crypt_GPG_KeyNotFoundException) { + $error = enigma_error::E_KEYNOTFOUND; + $data['id'] = $e->getKeyId(); + } + else if ($e instanceof Crypt_GPG_BadPassphraseException) { + $error = enigma_error::E_BADPASS; + $data['bad'] = $e->getBadPassphrases(); + $data['missing'] = $e->getMissingPassphrases(); + } + else if ($e instanceof Crypt_GPG_NoDataException) + $error = enigma_error::E_NODATA; + else if ($e instanceof Crypt_GPG_DeletePrivateKeyException) + $error = enigma_error::E_DELKEY; + else + $error = enigma_error::E_INTERNAL; + + $msg = $e->getMessage(); + + return new enigma_error($error, $msg, $data); + } + + /** + * Converts Crypt_GPG_Signature object into Enigma's signature object + * + * @param Crypt_GPG_Signature Signature object + * + * @return enigma_signature Signature object + */ + private function parse_signature($sig) + { + $user = $sig->getUserId(); + + $data = new enigma_signature(); + $data->id = $sig->getId(); + $data->valid = $sig->isValid(); + $data->fingerprint = $sig->getKeyFingerprint(); + $data->created = $sig->getCreationDate(); + $data->expires = $sig->getExpirationDate(); + $data->name = $user->getName(); + $data->comment = $user->getComment(); + $data->email = $user->getEmail(); + + return $data; + } + + /** + * Converts Crypt_GPG_Key object into Enigma's key object + * + * @param Crypt_GPG_Key Key object + * + * @return enigma_key Key object + */ + private function parse_key($key) + { + $ekey = new enigma_key(); + + foreach ($key->getUserIds() as $idx => $user) { + $id = new enigma_userid(); + $id->name = $user->getName(); + $id->comment = $user->getComment(); + $id->email = $user->getEmail(); + $id->valid = $user->isValid(); + $id->revoked = $user->isRevoked(); + + $ekey->users[$idx] = $id; + } + + $ekey->name = trim($ekey->users[0]->name . ' <' . $ekey->users[0]->email . '>'); + + foreach ($key->getSubKeys() as $idx => $subkey) { + $skey = new enigma_subkey(); + $skey->id = $subkey->getId(); + $skey->revoked = $subkey->isRevoked(); + $skey->created = $subkey->getCreationDate(); + $skey->expires = $subkey->getExpirationDate(); + $skey->fingerprint = $subkey->getFingerprint(); + $skey->has_private = $subkey->hasPrivate(); + $skey->can_sign = $subkey->canSign(); + $skey->can_encrypt = $subkey->canEncrypt(); + + $ekey->subkeys[$idx] = $skey; + }; + + $ekey->id = $ekey->subkeys[0]->id; + + return $ekey; + } +} diff --git a/enigma/lib/enigma_driver_phpssl.php b/enigma/lib/enigma_driver_phpssl.php new file mode 100644 index 0000000..fcd15db --- /dev/null +++ b/enigma/lib/enigma_driver_phpssl.php @@ -0,0 +1,238 @@ + | + +-------------------------------------------------------------------------+ +*/ + +class enigma_driver_phpssl extends enigma_driver +{ + private $rc; + //private $gpg; + private $homedir; + private $user; + + function __construct($user) + { + $rcmail = rcmail::get_instance(); + $this->rc = $rcmail; + $this->user = $user; + } + + /** + * Driver initialization and environment checking. + * Should only return critical errors. + * + * @return mixed NULL on success, enigma_error on failure + */ + function init() + { + $homedir = $this->rc->config->get('enigma_smime_homedir', INSTALL_PATH . '/plugins/enigma/home'); + + if (!$homedir) + return new enigma_error(enigma_error::E_INTERNAL, + "Option 'enigma_smime_homedir' not specified"); + + // check if homedir exists (create it if not) and is readable + if (!file_exists($homedir)) + return new enigma_error(enigma_error::E_INTERNAL, + "Keys directory doesn't exists: $homedir"); + if (!is_writable($homedir)) + return new enigma_error(enigma_error::E_INTERNAL, + "Keys directory isn't writeable: $homedir"); + + $homedir = $homedir . '/' . $this->user; + + // check if user's homedir exists (create it if not) and is readable + if (!file_exists($homedir)) + mkdir($homedir, 0700); + + if (!file_exists($homedir)) + return new enigma_error(enigma_error::E_INTERNAL, + "Unable to create keys directory: $homedir"); + if (!is_writable($homedir)) + return new enigma_error(enigma_error::E_INTERNAL, + "Unable to write to keys directory: $homedir"); + + $this->homedir = $homedir; + + } + + function encrypt($text, $keys) + { + } + + function decrypt($text, $key, $passwd) + { + } + + function sign($text, $key, $passwd) + { + } + + function verify($struct, $message) + { + // use common temp dir + $temp_dir = $this->rc->config->get('temp_dir'); + $msg_file = tempnam($temp_dir, 'rcmMsg'); + $cert_file = tempnam($temp_dir, 'rcmCert'); + + $fh = fopen($msg_file, "w"); + if ($struct->mime_id) { + $message->get_part_body($struct->mime_id, false, 0, $fh); + } + else { + $this->rc->storage->get_raw_body($message->uid, $fh); + } + fclose($fh); + + // @TODO: use stored certificates + + // try with certificate verification + $sig = openssl_pkcs7_verify($msg_file, 0, $cert_file); + $validity = true; + + if ($sig !== true) { + // try without certificate verification + $sig = openssl_pkcs7_verify($msg_file, PKCS7_NOVERIFY, $cert_file); + $validity = enigma_error::E_UNVERIFIED; + } + + if ($sig === true) { + $sig = $this->parse_sig_cert($cert_file, $validity); + } + else { + $errorstr = $this->get_openssl_error(); + $sig = new enigma_error(enigma_error::E_INTERNAL, $errorstr); + } + + // remove temp files + @unlink($msg_file); + @unlink($cert_file); + + return $sig; + } + + public function import($content, $isfile=false) + { + } + + public function list_keys($pattern='') + { + } + + public function get_key($keyid) + { + } + + public function gen_key($data) + { + } + + public function del_key($keyid) + { + } + + public function del_privkey($keyid) + { + } + + public function del_pubkey($keyid) + { + } + + /** + * Converts Crypt_GPG_Key object into Enigma's key object + * + * @param Crypt_GPG_Key Key object + * + * @return enigma_key Key object + */ + private function parse_key($key) + { +/* + $ekey = new enigma_key(); + + foreach ($key->getUserIds() as $idx => $user) { + $id = new enigma_userid(); + $id->name = $user->getName(); + $id->comment = $user->getComment(); + $id->email = $user->getEmail(); + $id->valid = $user->isValid(); + $id->revoked = $user->isRevoked(); + + $ekey->users[$idx] = $id; + } + + $ekey->name = trim($ekey->users[0]->name . ' <' . $ekey->users[0]->email . '>'); + + foreach ($key->getSubKeys() as $idx => $subkey) { + $skey = new enigma_subkey(); + $skey->id = $subkey->getId(); + $skey->revoked = $subkey->isRevoked(); + $skey->created = $subkey->getCreationDate(); + $skey->expires = $subkey->getExpirationDate(); + $skey->fingerprint = $subkey->getFingerprint(); + $skey->has_private = $subkey->hasPrivate(); + $skey->can_sign = $subkey->canSign(); + $skey->can_encrypt = $subkey->canEncrypt(); + + $ekey->subkeys[$idx] = $skey; + }; + + $ekey->id = $ekey->subkeys[0]->id; + + return $ekey; +*/ + } + + private function get_openssl_error() + { + $tmp = array(); + while ($errorstr = openssl_error_string()) { + $tmp[] = $errorstr; + } + + return join("\n", array_values($tmp)); + } + + private function parse_sig_cert($file, $validity) + { + $cert = openssl_x509_parse(file_get_contents($file)); + + if (empty($cert) || empty($cert['subject'])) { + $errorstr = $this->get_openssl_error(); + return new enigma_error(enigm_error::E_INTERNAL, $errorstr); + } + + $data = new enigma_signature(); + + $data->id = $cert['hash']; //? + $data->valid = $validity; + $data->fingerprint = $cert['serialNumber']; + $data->created = $cert['validFrom_time_t']; + $data->expires = $cert['validTo_time_t']; + $data->name = $cert['subject']['CN']; +// $data->comment = ''; + $data->email = $cert['subject']['emailAddress']; + + return $data; + } + +} diff --git a/enigma/lib/enigma_engine.php b/enigma/lib/enigma_engine.php new file mode 100644 index 0000000..e4972c6 --- /dev/null +++ b/enigma/lib/enigma_engine.php @@ -0,0 +1,554 @@ + | + +-------------------------------------------------------------------------+ + +*/ + +/* + RFC2440: OpenPGP Message Format + RFC3156: MIME Security with OpenPGP + RFC3851: S/MIME +*/ + +class enigma_engine +{ + private $rc; + private $enigma; + private $pgp_driver; + private $smime_driver; + + public $decryptions = array(); + public $signatures = array(); + public $signed_parts = array(); + + + /** + * Plugin initialization. + */ + function __construct($enigma) + { + $rcmail = rcmail::get_instance(); + $this->rc = $rcmail; + $this->enigma = $enigma; + } + + /** + * PGP driver initialization. + */ + function load_pgp_driver() + { + if ($this->pgp_driver) + return; + + $driver = 'enigma_driver_' . $this->rc->config->get('enigma_pgp_driver', 'gnupg'); + $username = $this->rc->user->get_username(); + + // Load driver + $this->pgp_driver = new $driver($username); + + if (!$this->pgp_driver) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: Unable to load PGP driver: $driver" + ), true, true); + } + + // Initialise driver + $result = $this->pgp_driver->init(); + + if ($result instanceof enigma_error) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: ".$result->getMessage() + ), true, true); + } + } + + /** + * S/MIME driver initialization. + */ + function load_smime_driver() + { + if ($this->smime_driver) + return; + + $driver = 'enigma_driver_' . $this->rc->config->get('enigma_smime_driver', 'phpssl'); + $username = $this->rc->user->get_username(); + + // Load driver + $this->smime_driver = new $driver($username); + + if (!$this->smime_driver) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: Unable to load S/MIME driver: $driver" + ), true, true); + } + + // Initialise driver + $result = $this->smime_driver->init(); + + if ($result instanceof enigma_error) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: ".$result->getMessage() + ), true, true); + } + } + + /** + * Handler for plain/text message. + * + * @param array Reference to hook's parameters + */ + function parse_plain(&$p) + { + $part = $p['structure']; + + // Get message body from IMAP server + $this->set_part_body($part, $p['object']->uid); + + // @TODO: big message body can be a file resource + // PGP signed message + if (preg_match('/^-----BEGIN PGP SIGNED MESSAGE-----/', $part->body)) { + $this->parse_plain_signed($p); + } + // PGP encrypted message + else if (preg_match('/^-----BEGIN PGP MESSAGE-----/', $part->body)) { + $this->parse_plain_encrypted($p); + } + } + + /** + * Handler for multipart/signed message. + * + * @param array Reference to hook's parameters + */ + function parse_signed(&$p) + { + $struct = $p['structure']; + + // S/MIME + if ($struct->parts[1] && $struct->parts[1]->mimetype == 'application/pkcs7-signature') { + $this->parse_smime_signed($p); + } + // PGP/MIME: + // The multipart/signed body MUST consist of exactly two parts. + // The first part contains the signed data in MIME canonical format, + // including a set of appropriate content headers describing the data. + // The second body MUST contain the PGP digital signature. It MUST be + // labeled with a content type of "application/pgp-signature". + else if ($struct->parts[1] && $struct->parts[1]->mimetype == 'application/pgp-signature') { + $this->parse_pgp_signed($p); + } + } + + /** + * Handler for multipart/encrypted message. + * + * @param array Reference to hook's parameters + */ + function parse_encrypted(&$p) + { + $struct = $p['structure']; + + // S/MIME + if ($struct->mimetype == 'application/pkcs7-mime') { + $this->parse_smime_encrypted($p); + } + // PGP/MIME: + // The multipart/encrypted MUST consist of exactly two parts. The first + // MIME body part must have a content type of "application/pgp-encrypted". + // This body contains the control information. + // The second MIME body part MUST contain the actual encrypted data. It + // must be labeled with a content type of "application/octet-stream". + else if ($struct->parts[0] && $struct->parts[0]->mimetype == 'application/pgp-encrypted' && + $struct->parts[1] && $struct->parts[1]->mimetype == 'application/octet-stream' + ) { + $this->parse_pgp_encrypted($p); + } + } + + /** + * Handler for plain signed message. + * Excludes message and signature bodies and verifies signature. + * + * @param array Reference to hook's parameters + */ + private function parse_plain_signed(&$p) + { + $this->load_pgp_driver(); + $part = $p['structure']; + + // Verify signature + if ($this->rc->action == 'show' || $this->rc->action == 'preview') { + $sig = $this->pgp_verify($part->body); + } + + // @TODO: Handle big bodies using (temp) files + + // In this way we can use fgets on string as on file handle + $fh = fopen('php://memory', 'br+'); + // @TODO: fopen/fwrite errors handling + if ($fh) { + fwrite($fh, $part->body); + rewind($fh); + } + $part->body = null; + + // Extract body (and signature?) + while (!feof($fh)) { + $line = fgets($fh, 1024); + + if ($part->body === null) + $part->body = ''; + else if (preg_match('/^-----BEGIN PGP SIGNATURE-----/', $line)) + break; + else + $part->body .= $line; + } + + // Remove "Hash" Armor Headers + $part->body = preg_replace('/^.*\r*\n\r*\n/', '', $part->body); + // de-Dash-Escape (RFC2440) + $part->body = preg_replace('/(^|\n)- -/', '\\1-', $part->body); + + // Store signature data for display + if (!empty($sig)) { + $this->signed_parts[$part->mime_id] = $part->mime_id; + $this->signatures[$part->mime_id] = $sig; + } + + fclose($fh); + } + + /** + * Handler for PGP/MIME signed message. + * Verifies signature. + * + * @param array Reference to hook's parameters + */ + private function parse_pgp_signed(&$p) + { + // Verify signature + if ($this->rc->action == 'show' || $this->rc->action == 'preview') { + $this->load_pgp_driver(); + $struct = $p['structure']; + + $msg_part = $struct->parts[0]; + $sig_part = $struct->parts[1]; + + // Get bodies + $this->set_part_body($msg_part, $p['object']->uid); + $this->set_part_body($sig_part, $p['object']->uid); + + // Verify + $sig = $this->pgp_verify($msg_part->body, $sig_part->body); + + // Store signature data for display + $this->signatures[$struct->mime_id] = $sig; + + // Message can be multipart (assign signature to each subpart) + if (!empty($msg_part->parts)) { + foreach ($msg_part->parts as $part) + $this->signed_parts[$part->mime_id] = $struct->mime_id; + } + else + $this->signed_parts[$msg_part->mime_id] = $struct->mime_id; + + // Remove signature file from attachments list + unset($struct->parts[1]); + } + } + + /** + * Handler for S/MIME signed message. + * Verifies signature. + * + * @param array Reference to hook's parameters + */ + private function parse_smime_signed(&$p) + { + // Verify signature + if ($this->rc->action == 'show' || $this->rc->action == 'preview') { + $this->load_smime_driver(); + + $struct = $p['structure']; + $msg_part = $struct->parts[0]; + + // Verify + $sig = $this->smime_driver->verify($struct, $p['object']); + + // Store signature data for display + $this->signatures[$struct->mime_id] = $sig; + + // Message can be multipart (assign signature to each subpart) + if (!empty($msg_part->parts)) { + foreach ($msg_part->parts as $part) + $this->signed_parts[$part->mime_id] = $struct->mime_id; + } + else { + $this->signed_parts[$msg_part->mime_id] = $struct->mime_id; + } + + // Remove signature file from attachments list + unset($struct->parts[1]); + } + } + + /** + * Handler for plain encrypted message. + * + * @param array Reference to hook's parameters + */ + private function parse_plain_encrypted(&$p) + { + $this->load_pgp_driver(); + $part = $p['structure']; + + // Get body + $this->set_part_body($part, $p['object']->uid); + + // Decrypt + $result = $this->pgp_decrypt($part->body); + + // Store decryption status + $this->decryptions[$part->mime_id] = $result; + + // Parse decrypted message + if ($result === true) { + // @TODO + } + } + + /** + * Handler for PGP/MIME encrypted message. + * + * @param array Reference to hook's parameters + */ + private function parse_pgp_encrypted(&$p) + { + $this->load_pgp_driver(); + $struct = $p['structure']; + $part = $struct->parts[1]; + + // Get body + $this->set_part_body($part, $p['object']->uid); + + // Decrypt + $result = $this->pgp_decrypt($part->body); + + $this->decryptions[$part->mime_id] = $result; +//print_r($part); + // Parse decrypted message + if ($result === true) { + // @TODO + } + else { + // Make sure decryption status message will be displayed + $part->type = 'content'; + $p['object']->parts[] = $part; + } + } + + /** + * Handler for S/MIME encrypted message. + * + * @param array Reference to hook's parameters + */ + private function parse_smime_encrypted(&$p) + { +// $this->load_smime_driver(); + } + + /** + * PGP signature verification. + * + * @param mixed Message body + * @param mixed Signature body (for MIME messages) + * + * @return mixed enigma_signature or enigma_error + */ + private function pgp_verify(&$msg_body, $sig_body=null) + { + // @TODO: Handle big bodies using (temp) files + // @TODO: caching of verification result + $sig = $this->pgp_driver->verify($msg_body, $sig_body); + + if (($sig instanceof enigma_error) && $sig->getCode() != enigma_error::E_KEYNOTFOUND) + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: " . $sig->getMessage() + ), true, false); + + return $sig; + } + + /** + * PGP message decryption. + * + * @param mixed Message body + * + * @return mixed True or enigma_error + */ + private function pgp_decrypt(&$msg_body) + { + // @TODO: Handle big bodies using (temp) files + // @TODO: caching of verification result + $key = ''; $pass = ''; // @TODO + $result = $this->pgp_driver->decrypt($msg_body, $key, $pass); + + if ($result instanceof enigma_error) { + $err_code = $result->getCode(); + if (!in_array($err_code, array(enigma_error::E_KEYNOTFOUND, enigma_error::E_BADPASS))) + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: " . $result->getMessage() + ), true, false); + return $result; + } + +// $msg_body = $result; + return true; + } + + /** + * PGP keys listing. + * + * @param mixed Key ID/Name pattern + * + * @return mixed Array of keys or enigma_error + */ + function list_keys($pattern='') + { + $this->load_pgp_driver(); + $result = $this->pgp_driver->list_keys($pattern); + + if ($result instanceof enigma_error) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: " . $result->getMessage() + ), true, false); + } + + return $result; + } + + /** + * PGP key details. + * + * @param mixed Key ID + * + * @return mixed enigma_key or enigma_error + */ + function get_key($keyid) + { + $this->load_pgp_driver(); + $result = $this->pgp_driver->get_key($keyid); + + if ($result instanceof enigma_error) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: " . $result->getMessage() + ), true, false); + } + + return $result; + } + + /** + * PGP keys/certs importing. + * + * @param mixed Import file name or content + * @param boolean True if first argument is a filename + * + * @return mixed Import status data array or enigma_error + */ + function import_key($content, $isfile=false) + { + $this->load_pgp_driver(); + $result = $this->pgp_driver->import($content, $isfile); + + if ($result instanceof enigma_error) { + rcube::raise_error(array( + 'code' => 600, 'type' => 'php', + 'file' => __FILE__, 'line' => __LINE__, + 'message' => "Enigma plugin: " . $result->getMessage() + ), true, false); + } + else { + $result['imported'] = $result['public_imported'] + $result['private_imported']; + $result['unchanged'] = $result['public_unchanged'] + $result['private_unchanged']; + } + + return $result; + } + + /** + * Handler for keys/certs import request action + */ + function import_file() + { + $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST); + $mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST); + $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST); + $storage = $this->rc->get_storage(); + + if ($uid && $mime_id) { + $storage->set_folder($mbox); + $part = $storage->get_message_part($uid, $mime_id); + } + + if ($part && is_array($result = $this->import_key($part))) { + $this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation', + array('new' => $result['imported'], 'old' => $result['unchanged'])); + } + else + $this->rc->output->show_message('enigma.keysimportfailed', 'error'); + + $this->rc->output->send(); + } + + /** + * Checks if specified message part contains body data. + * If body is not set it will be fetched from IMAP server. + * + * @param rcube_message_part Message part object + * @param integer Message UID + */ + private function set_part_body($part, $uid) + { + // @TODO: Create such function in core + // @TODO: Handle big bodies using file handles + if (!isset($part->body)) { + $part->body = $this->rc->storage->get_message_part( + $uid, $part->mime_id, $part); + } + } +} diff --git a/enigma/lib/enigma_error.php b/enigma/lib/enigma_error.php new file mode 100644 index 0000000..ab8d015 --- /dev/null +++ b/enigma/lib/enigma_error.php @@ -0,0 +1,64 @@ + | + +-------------------------------------------------------------------------+ +*/ + +class enigma_error +{ + private $code; + private $message; + private $data = array(); + + // error codes + const E_OK = 0; + const E_INTERNAL = 1; + const E_NODATA = 2; + const E_KEYNOTFOUND = 3; + const E_DELKEY = 4; + const E_BADPASS = 5; + const E_EXPIRED = 6; + const E_UNVERIFIED = 7; + + function __construct($code = null, $message = '', $data = array()) + { + $this->code = $code; + $this->message = $message; + $this->data = $data; + } + + function getCode() + { + return $this->code; + } + + function getMessage() + { + return $this->message; + } + + function getData($name) + { + if ($name) + return $this->data[$name]; + else + return $this->data; + } +} diff --git a/enigma/lib/enigma_key.php b/enigma/lib/enigma_key.php new file mode 100644 index 0000000..520c36b --- /dev/null +++ b/enigma/lib/enigma_key.php @@ -0,0 +1,129 @@ + | + +-------------------------------------------------------------------------+ +*/ + +class enigma_key +{ + public $id; + public $name; + public $users = array(); + public $subkeys = array(); + + const TYPE_UNKNOWN = 0; + const TYPE_KEYPAIR = 1; + const TYPE_PUBLIC = 2; + + /** + * Keys list sorting callback for usort() + */ + static function cmp($a, $b) + { + return strcmp($a->name, $b->name); + } + + /** + * Returns key type + */ + function get_type() + { + if ($this->subkeys[0]->has_private) + return enigma_key::TYPE_KEYPAIR; + else if (!empty($this->subkeys[0])) + return enigma_key::TYPE_PUBLIC; + + return enigma_key::TYPE_UNKNOWN; + } + + /** + * Returns true if all user IDs are revoked + */ + function is_revoked() + { + foreach ($this->subkeys as $subkey) + if (!$subkey->revoked) + return false; + + return true; + } + + /** + * Returns true if any user ID is valid + */ + function is_valid() + { + foreach ($this->users as $user) + if ($user->valid) + return true; + + return false; + } + + /** + * Returns true if any of subkeys is not expired + */ + function is_expired() + { + $now = time(); + + foreach ($this->subkeys as $subkey) + if (!$subkey->expires || $subkey->expires > $now) + return true; + + return false; + } + + /** + * Converts long ID or Fingerprint to short ID + * Crypt_GPG uses internal, but e.g. Thunderbird's Enigmail displays short ID + * + * @param string Key ID or fingerprint + * @return string Key short ID + */ + static function format_id($id) + { + // E.g. 04622F2089E037A5 => 89E037A5 + + return substr($id, -8); + } + + /** + * Formats fingerprint string + * + * @param string Key fingerprint + * + * @return string Formatted fingerprint (with spaces) + */ + static function format_fingerprint($fingerprint) + { + if (!$fingerprint) + return ''; + + $result = ''; + for ($i=0; $i<40; $i++) { + if ($i % 4 == 0) + $result .= ' '; + $result .= $fingerprint[$i]; + } + return $result; + } + +} diff --git a/enigma/lib/enigma_signature.php b/enigma/lib/enigma_signature.php new file mode 100644 index 0000000..6599090 --- /dev/null +++ b/enigma/lib/enigma_signature.php @@ -0,0 +1,34 @@ + | + +-------------------------------------------------------------------------+ +*/ + +class enigma_signature +{ + public $id; + public $valid; + public $fingerprint; + public $created; + public $expires; + public $name; + public $comment; + public $email; +} diff --git a/enigma/lib/enigma_subkey.php b/enigma/lib/enigma_subkey.php new file mode 100644 index 0000000..1b9fb95 --- /dev/null +++ b/enigma/lib/enigma_subkey.php @@ -0,0 +1,57 @@ + | + +-------------------------------------------------------------------------+ +*/ + +class enigma_subkey +{ + public $id; + public $fingerprint; + public $expires; + public $created; + public $revoked; + public $has_private; + public $can_sign; + public $can_encrypt; + + /** + * Converts internal ID to short ID + * Crypt_GPG uses internal, but e.g. Thunderbird's Enigmail displays short ID + * + * @return string Key ID + */ + function get_short_id() + { + // E.g. 04622F2089E037A5 => 89E037A5 + return enigma_key::format_id($this->id); + } + + /** + * Getter for formatted fingerprint + * + * @return string Formatted fingerprint + */ + function get_fingerprint() + { + return enigma_key::format_fingerprint($this->fingerprint); + } + +} diff --git a/enigma/lib/enigma_ui.php b/enigma/lib/enigma_ui.php new file mode 100644 index 0000000..2e95938 --- /dev/null +++ b/enigma/lib/enigma_ui.php @@ -0,0 +1,455 @@ + | + +-------------------------------------------------------------------------+ +*/ + +class enigma_ui +{ + private $rc; + private $enigma; + private $home; + private $css_added; + private $data; + + + function __construct($enigma_plugin, $home='') + { + $this->enigma = $enigma_plugin; + $this->rc = $enigma_plugin->rc; + // we cannot use $enigma_plugin->home here + $this->home = $home; + } + + /** + * UI initialization and requests handlers. + * + * @param string Preferences section + */ + function init($section='') + { + $this->enigma->include_script('enigma.js'); + + // Enigma actions + if ($this->rc->action == 'plugin.enigma') { + $action = rcube_utils::get_input_value('_a', rcube_utils::INPUT_GPC); + + switch ($action) { + case 'keyedit': + $this->key_edit(); + break; + case 'keyimport': + $this->key_import(); + break; + case 'keysearch': + case 'keylist': + $this->key_list(); + break; + case 'keyinfo': + default: + $this->key_info(); + } + } + // Message composing UI + else if ($this->rc->action == 'compose') { + $this->compose_ui(); + } + // Preferences UI + else { // if ($this->rc->action == 'edit-prefs') { + if ($section == 'enigmacerts') { + $this->rc->output->add_handlers(array( + 'keyslist' => array($this, 'tpl_certs_list'), + 'keyframe' => array($this, 'tpl_cert_frame'), + 'countdisplay' => array($this, 'tpl_certs_rowcount'), + 'searchform' => array($this->rc->output, 'search_form'), + )); + $this->rc->output->set_pagetitle($this->enigma->gettext('enigmacerts')); + $this->rc->output->send('enigma.certs'); + } + else { + $this->rc->output->add_handlers(array( + 'keyslist' => array($this, 'tpl_keys_list'), + 'keyframe' => array($this, 'tpl_key_frame'), + 'countdisplay' => array($this, 'tpl_keys_rowcount'), + 'searchform' => array($this->rc->output, 'search_form'), + )); + $this->rc->output->set_pagetitle($this->enigma->gettext('enigmakeys')); + $this->rc->output->send('enigma.keys'); + } + } + } + + /** + * Adds CSS style file to the page header. + */ + function add_css() + { + if ($this->css_loaded) + return; + + $skin_path = $this->enigma->local_skin_path(); + if (is_file($this->home . "/$skin_path/enigma.css")) { + $this->enigma->include_stylesheet("$skin_path/enigma.css"); + } + + $this->css_added = true; + } + + /** + * Template object for key info/edit frame. + * + * @param array Object attributes + * + * @return string HTML output + */ + function tpl_key_frame($attrib) + { + if (!$attrib['id']) { + $attrib['id'] = 'rcmkeysframe'; + } + + $attrib['name'] = $attrib['id']; + + $this->rc->output->set_env('contentframe', $attrib['name']); + $this->rc->output->set_env('blankpage', $attrib['src'] ? + $this->rc->output->abs_url($attrib['src']) : 'program/resources/blank.gif'); + + return $this->rc->output->frame($attrib); + } + + /** + * Template object for list of keys. + * + * @param array Object attributes + * + * @return string HTML content + */ + function tpl_keys_list($attrib) + { + // add id to message list table if not specified + if (!strlen($attrib['id'])) { + $attrib['id'] = 'rcmenigmakeyslist'; + } + + // define list of cols to be displayed + $a_show_cols = array('name'); + + // create XHTML table + $out = $this->rc->table_output($attrib, array(), $a_show_cols, 'id'); + + // set client env + $this->rc->output->add_gui_object('keyslist', $attrib['id']); + $this->rc->output->include_script('list.js'); + + // add some labels to client + $this->rc->output->add_label('enigma.keyconfirmdelete'); + + return $out; + } + + /** + * Key listing (and searching) request handler + */ + private function key_list() + { + $this->enigma->load_engine(); + + $pagesize = $this->rc->config->get('pagesize', 100); + $page = max(intval(rcube_utils::get_input_value('_p', rcube_utils::INPUT_GPC)), 1); + $search = rcube_utils::get_input_value('_q', rcube_utils::INPUT_GPC); + + // define list of cols to be displayed +// $a_show_cols = array('name'); + + // Get the list + $list = $this->enigma->engine->list_keys($search); + + if ($list && ($list instanceof enigma_error)) + $this->rc->output->show_message('enigma.keylisterror', 'error'); + else if (empty($list)) + $this->rc->output->show_message('enigma.nokeysfound', 'notice'); + else { + if (is_array($list)) { + // Save the size + $listsize = count($list); + + // Sort the list by key (user) name + usort($list, array('enigma_key', 'cmp')); + + // Slice current page + $list = array_slice($list, ($page - 1) * $pagesize, $pagesize); + + $size = count($list); + + // Add rows + foreach ($list as $key) { + $this->rc->output->command('enigma_add_list_row', + array('name' => rcube::Q($key->name), 'id' => $key->id)); + } + } + } + + $this->rc->output->set_env('search_request', $search); + $this->rc->output->set_env('pagecount', ceil($listsize/$pagesize)); + $this->rc->output->set_env('current_page', $page); + $this->rc->output->command('set_rowcount', + $this->get_rowcount_text($listsize, $size, $page)); + + $this->rc->output->send(); + } + + /** + * Template object for list records counter. + * + * @param array Object attributes + * + * @return string HTML output + */ + function tpl_keys_rowcount($attrib) + { + if (!$attrib['id']) + $attrib['id'] = 'rcmcountdisplay'; + + $this->rc->output->add_gui_object('countdisplay', $attrib['id']); + + return html::span($attrib, $this->get_rowcount_text()); + } + + /** + * Returns text representation of list records counter + */ + private function get_rowcount_text($all=0, $curr_count=0, $page=1) + { + if (!$curr_count) + $out = $this->enigma->gettext('nokeysfound'); + else { + $pagesize = $this->rc->config->get('pagesize', 100); + $first = ($page - 1) * $pagesize; + + $out = $this->enigma->gettext(array( + 'name' => 'keysfromto', + 'vars' => array( + 'from' => $first + 1, + 'to' => $first + $curr_count, + 'count' => $all) + )); + } + + return $out; + } + + /** + * Key information page handler + */ + private function key_info() + { + $id = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GET); + + $this->enigma->load_engine(); + $res = $this->enigma->engine->get_key($id); + + if ($res instanceof enigma_key) + $this->data = $res; + else { // error + $this->rc->output->show_message('enigma.keyopenerror', 'error'); + $this->rc->output->command('parent.enigma_loadframe'); + $this->rc->output->send('iframe'); + } + + $this->rc->output->add_handlers(array( + 'keyname' => array($this, 'tpl_key_name'), + 'keydata' => array($this, 'tpl_key_data'), + )); + + $this->rc->output->set_pagetitle($this->enigma->gettext('keyinfo')); + $this->rc->output->send('enigma.keyinfo'); + } + + /** + * Template object for key name + */ + function tpl_key_name($attrib) + { + return rcube::Q($this->data->name); + } + + /** + * Template object for key information page content + */ + function tpl_key_data($attrib) + { + $out = ''; + $table = new html_table(array('cols' => 2)); + + // Key user ID + $table->add('title', $this->enigma->gettext('keyuserid')); + $table->add(null, rcube::Q($this->data->name)); + // Key ID + $table->add('title', $this->enigma->gettext('keyid')); + $table->add(null, $this->data->subkeys[0]->get_short_id()); + // Key type + $keytype = $this->data->get_type(); + if ($keytype == enigma_key::TYPE_KEYPAIR) + $type = $this->enigma->gettext('typekeypair'); + else if ($keytype == enigma_key::TYPE_PUBLIC) + $type = $this->enigma->gettext('typepublickey'); + $table->add('title', $this->enigma->gettext('keytype')); + $table->add(null, $type); + // Key fingerprint + $table->add('title', $this->enigma->gettext('fingerprint')); + $table->add(null, $this->data->subkeys[0]->get_fingerprint()); + + $out .= html::tag('fieldset', null, + html::tag('legend', null, + $this->enigma->gettext('basicinfo')) . $table->show($attrib)); + + // Subkeys + $table = new html_table(array('cols' => 6)); + // Columns: Type, ID, Algorithm, Size, Created, Expires + + $out .= html::tag('fieldset', null, + html::tag('legend', null, + $this->enigma->gettext('subkeys')) . $table->show($attrib)); + + // Additional user IDs + $table = new html_table(array('cols' => 2)); + // Columns: User ID, Validity + + $out .= html::tag('fieldset', null, + html::tag('legend', null, + $this->enigma->gettext('userids')) . $table->show($attrib)); + + return $out; + } + + /** + * Key import page handler + */ + private function key_import() + { + // Import process + if ($_FILES['_file']['tmp_name'] && is_uploaded_file($_FILES['_file']['tmp_name'])) { + $this->enigma->load_engine(); + $result = $this->enigma->engine->import_key($_FILES['_file']['tmp_name'], true); + + if (is_array($result)) { + // reload list if any keys has been added + if ($result['imported']) { + $this->rc->output->command('parent.enigma_list', 1); + } + else + $this->rc->output->command('parent.enigma_loadframe'); + + $this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation', + array('new' => $result['imported'], 'old' => $result['unchanged'])); + + $this->rc->output->send('iframe'); + } + else + $this->rc->output->show_message('enigma.keysimportfailed', 'error'); + } + else if ($err = $_FILES['_file']['error']) { + if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) { + $this->rc->output->show_message('filesizeerror', 'error', + array('size' => $this->rc->show_bytes(parse_bytes(ini_get('upload_max_filesize'))))); + } else { + $this->rc->output->show_message('fileuploaderror', 'error'); + } + } + + $this->rc->output->add_handlers(array( + 'importform' => array($this, 'tpl_key_import_form'), + )); + + $this->rc->output->set_pagetitle($this->enigma->gettext('keyimport')); + $this->rc->output->send('enigma.keyimport'); + } + + /** + * Template object for key import (upload) form + */ + function tpl_key_import_form($attrib) + { + $attrib += array('id' => 'rcmKeyImportForm'); + + $upload = new html_inputfield(array('type' => 'file', 'name' => '_file', + 'id' => 'rcmimportfile', 'size' => 30)); + + $form = html::p(null, + rcube::Q($this->enigma->gettext('keyimporttext'), 'show') + . html::br() . html::br() . $upload->show() + ); + + $this->rc->output->add_label('selectimportfile', 'importwait'); + $this->rc->output->add_gui_object('importform', $attrib['id']); + + $out = $this->rc->output->form_tag(array( + 'action' => $this->rc->url(array('action' => 'plugin.enigma', 'a' => 'keyimport')), + 'method' => 'post', + 'enctype' => 'multipart/form-data') + $attrib, + $form); + + return $out; + } + + private function compose_ui() + { + // Options menu button + // @TODO: make this work with non-default skins + $this->enigma->add_button(array( + 'name' => 'enigmamenu', + 'imagepas' => 'skins/classic/enigma.png', + 'imageact' => 'skins/classic/enigma.png', + 'onclick' => "rcmail_ui.show_popup('enigmamenu', true); return false", + 'title' => 'securityoptions', + 'domain' => 'enigma', + ), 'toolbar'); + + // Options menu contents + $this->enigma->add_hook('render_page', array($this, 'compose_menu')); + } + + function compose_menu($p) + { + $menu = new html_table(array('cols' => 2)); + $chbox = new html_checkbox(array('value' => 1)); + + $menu->add(null, html::label(array('for' => 'enigmadefaultopt'), + rcube::Q($this->enigma->gettext('identdefault')))); + $menu->add(null, $chbox->show(1, array('name' => '_enigma_default', 'id' => 'enigmadefaultopt'))); + + $menu->add(null, html::label(array('for' => 'enigmasignopt'), + rcube::Q($this->enigma->gettext('signmsg')))); + $menu->add(null, $chbox->show(1, array('name' => '_enigma_sign', 'id' => 'enigmasignopt'))); + + $menu->add(null, html::label(array('for' => 'enigmacryptopt'), + rcube::Q($this->enigma->gettext('encryptmsg')))); + $menu->add(null, $chbox->show(1, array('name' => '_enigma_crypt', 'id' => 'enigmacryptopt'))); + + $menu = html::div(array('id' => 'enigmamenu', 'class' => 'popupmenu'), + $menu->show()); + + $p['content'] = preg_replace('/(
]+>)/i', '\\1'."\n$menu", $p['content']); + + return $p; + + } + +} diff --git a/enigma/lib/enigma_userid.php b/enigma/lib/enigma_userid.php new file mode 100644 index 0000000..36185e7 --- /dev/null +++ b/enigma/lib/enigma_userid.php @@ -0,0 +1,31 @@ + | + +-------------------------------------------------------------------------+ +*/ + +class enigma_userid +{ + public $revoked; + public $valid; + public $name; + public $comment; + public $email; +} -- cgit v1.2.3