Aleksander Machniak
2016-01-25 53fa08d8ae051d10bed7fb08840d2f873e75c264
plugins/enigma/lib/enigma_engine.php
@@ -1,5 +1,6 @@
<?php
/*
/**
 +-------------------------------------------------------------------------+
 | Engine of the Enigma Plugin                                             |
 |                                                                         |
@@ -14,24 +15,25 @@
 +-------------------------------------------------------------------------+
*/
/*
    RFC2440: OpenPGP Message Format
    RFC3156: MIME Security with OpenPGP
    RFC3851: S/MIME
*/
/**
 * Enigma plugin engine.
 *
 * 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;
    private $password_time;
    public $decryptions  = array();
    public $signatures   = array();
    public $signed_parts = array();
    const PASSWORD_TIME = 120;
    public $decryptions     = array();
    public $signatures      = array();
    public $signed_parts    = array();
    public $encrypted_parts = array();
    const SIGN_MODE_BODY     = 1;
    const SIGN_MODE_SEPARATE = 2;
@@ -49,8 +51,12 @@
        $this->rc     = rcmail::get_instance();
        $this->enigma = $enigma;
        $this->password_time = $this->rc->config->get('enigma_password_time') * 60;
        // this will remove passwords from session after some time
        $this->get_passwords();
        if ($this->password_time) {
            $this->get_passwords();
        }
    }
    /**
@@ -140,7 +146,7 @@
        $key = $this->find_key($from, true);
        if (empty($key)) {
            return new enigma_error(enigma_error::E_KEYNOTFOUND);
            return new enigma_error(enigma_error::KEYNOTFOUND);
        }
        // check if we have password for this key
@@ -150,7 +156,7 @@
        if ($pass === null) {
            // ask for password
            $error = array('missing' => array($key->id => $key->name));
            return new enigma_error(enigma_error::E_BADPASS, '', $error);
            return new enigma_error(enigma_error::BADPASS, '', $error);
        }
        // select mode
@@ -191,10 +197,10 @@
        $result = $this->pgp_sign($body, $key->id, $pass, $pgp_mode);
        if ($result !== true) {
            if ($result->getCode() == enigma_error::E_BADPASS) {
            if ($result->getCode() == enigma_error::BADPASS) {
                // ask for password
                $error = array('missing' => array($key->id => $key->name));
                return new enigma_error(enigma_error::E_BADPASS, '', $error);
                return new enigma_error(enigma_error::BADPASS, '', $error);
            }
            return $result;
@@ -232,7 +238,7 @@
        }
        if (empty($recipients)) {
            return new enigma_error(enigma_error::E_KEYNOTFOUND);
            return new enigma_error(enigma_error::KEYNOTFOUND);
        }
        $recipients = array_unique($recipients);
@@ -242,7 +248,7 @@
            $key = $this->find_key($email);
            if (empty($key)) {
                return new enigma_error(enigma_error::E_KEYNOTFOUND, '', array(
                return new enigma_error(enigma_error::KEYNOTFOUND, '', array(
                    'missing' => $email
                ));
            }
@@ -296,17 +302,18 @@
     * Handler for message_part_structure hook.
     * Called for every part of the message.
     *
     * @param array Original parameters
     * @param array  Original parameters
     * @param string Part body (will be set if used internally)
     *
     * @return array Modified parameters
     */
    function part_structure($p)
    function part_structure($p, $body = null)
    {
        if ($p['mimetype'] == 'text/plain' || $p['mimetype'] == 'application/pgp') {
            $this->parse_plain($p);
            $this->parse_plain($p, $body);
        }
        else if ($p['mimetype'] == 'multipart/signed') {
            $this->parse_signed($p);
            $this->parse_signed($p, $body);
        }
        else if ($p['mimetype'] == 'multipart/encrypted') {
            $this->parse_encrypted($p);
@@ -329,6 +336,8 @@
    {
        // encrypted attachment, see parse_plain_encrypted()
        if ($p['part']->need_decryption && $p['part']->body === null) {
            $this->load_pgp_driver();
            $storage = $this->rc->get_storage();
            $body    = $storage->get_message_part($p['object']->uid, $p['part']->mime_id, $p['part'], null, null, true, 0, false);
            $result  = $this->pgp_decrypt($body);
@@ -347,19 +356,22 @@
    /**
     * Handler for plain/text message.
     *
     * @param array Reference to hook's parameters
     * @param array  Reference to hook's parameters
     * @param string Part body (will be set if used internally)
     */
    function parse_plain(&$p)
    function parse_plain(&$p, $body = null)
    {
        $part = $p['structure'];
        // exit, if we're already inside a decrypted message
        if ($part->encrypted) {
        if (in_array($part->mime_id, $this->encrypted_parts)) {
            return;
        }
        // Get message body from IMAP server
        $body = $this->get_part_body($p['object'], $part->mime_id);
        if ($body === null) {
            $body = $this->get_part_body($p['object'], $part);
        }
        // @TODO: big message body could be a file resource
        // PGP signed message
@@ -375,15 +387,16 @@
    /**
     * Handler for multipart/signed message.
     *
     * @param array Reference to hook's parameters
     * @param array  Reference to hook's parameters
     * @param string Part body (will be set if used internally)
     */
    function parse_signed(&$p)
    function parse_signed(&$p, $body = null)
    {
        $struct = $p['structure'];
        // S/MIME
        if ($struct->parts[1] && $struct->parts[1]->mimetype == 'application/pkcs7-signature') {
            $this->parse_smime_signed($p);
            $this->parse_smime_signed($p, $body);
        }
        // PGP/MIME: RFC3156
        // The multipart/signed body MUST consist of exactly two parts.
@@ -395,7 +408,7 @@
            && count($struct->parts) == 2
            && $struct->parts[1] && $struct->parts[1]->mimetype == 'application/pgp-signature'
        ) {
            $this->parse_pgp_signed($p);
            $this->parse_pgp_signed($p, $body);
        }
    }
@@ -436,11 +449,15 @@
     */
    private function parse_plain_signed(&$p, $body)
    {
        if (!$this->rc->config->get('enigma_signatures', true)) {
            return;
        }
        $this->load_pgp_driver();
        $part = $p['structure'];
        // Verify signature
        if ($this->rc->action == 'show' || $this->rc->action == 'preview') {
        if ($this->rc->action == 'show' || $this->rc->action == 'preview' || $this->rc->action == 'print') {
            $sig = $this->pgp_verify($body);
        }
@@ -477,7 +494,7 @@
        // Store signature data for display
        if (!empty($sig)) {
            $this->signed_parts[$part->mime_id] = $part->mime_id;
            $this->signatures[$part->mime_id] = $sig;
            $this->signatures[$part->mime_id]   = $sig;
        }
        fclose($fh);
@@ -488,40 +505,49 @@
     * Verifies signature.
     *
     * @param array  Reference to hook's parameters
     * @param string Part body (will be set if used internally)
     */
    private function parse_pgp_signed(&$p)
    private function parse_pgp_signed(&$p, $body = null)
    {
        // Verify signature
        if ($this->rc->action == 'show' || $this->rc->action == 'preview') {
            $this->load_pgp_driver();
            $struct = $p['structure'];
        if (!$this->rc->config->get('enigma_signatures', true)) {
            return;
        }
            $msg_part = $struct->parts[0];
            $sig_part = $struct->parts[1];
        if ($this->rc->action != 'show' && $this->rc->action != 'preview' && $this->rc->action != 'print') {
            return;
        }
            // Get bodies
            // Note: The first part body need to be full part body with headers
            //       it also cannot be decoded
            $msg_body = $this->get_part_body($p['object'], $msg_part->mime_id, true);
            $sig_body = $this->get_part_body($p['object'], $sig_part->mime_id);
        $this->load_pgp_driver();
        $struct = $p['structure'];
            // Verify
            $sig = $this->pgp_verify($msg_body, $sig_body);
        $msg_part = $struct->parts[0];
        $sig_part = $struct->parts[1];
            // Store signature data for display
            $this->signatures[$struct->mime_id] = $sig;
        // Get bodies
        // Note: The first part body need to be full part body with headers
        //       it also cannot be decoded
        if ($body !== null) {
            // set signed part body
            list($msg_body, $sig_body) = $this->explode_signed_body($body, $struct->ctype_parameters['boundary']);
        }
        else {
            $msg_body = $this->get_part_body($p['object'], $msg_part, true);
            $sig_body = $this->get_part_body($p['object'], $sig_part);
        }
            // 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;
            }
        // Verify
        $sig = $this->pgp_verify($msg_body, $sig_body);
            // Remove signature file from attachments list (?)
            unset($struct->parts[1]);
        // 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;
        }
    }
@@ -529,37 +555,16 @@
     * Handler for S/MIME signed message.
     * Verifies signature.
     *
     * @param array Reference to hook's parameters
     * @param array  Reference to hook's parameters
     * @param string Part body (will be set if used internally)
     */
    private function parse_smime_signed(&$p)
    private function parse_smime_signed(&$p, $body = null)
    {
        return; // @TODO
        // 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]);
        if (!$this->rc->config->get('enigma_signatures', true)) {
            return;
        }
        // @TODO
    }
    /**
@@ -570,6 +575,10 @@
     */
    private function parse_plain_encrypted(&$p, $body)
    {
        if (!$this->rc->config->get('enigma_decryption', true)) {
            return;
        }
        $this->load_pgp_driver();
        $part = $p['structure'];
@@ -579,26 +588,33 @@
        // Store decryption status
        $this->decryptions[$part->mime_id] = $result;
        // find parent part ID
        if (strpos($part->mime_id, '.')) {
            $items = explode('.', $part->mime_id);
            array_pop($items);
            $parent = implode('.', $items);
        }
        else {
            $parent = 0;
        }
        // Parse decrypted message
        if ($result === true) {
            $part->body          = $body;
            $part->body_modified = true;
            $part->encrypted     = true;
            // Remember it was decrypted
            $this->encrypted_parts[] = $part->mime_id;
            // PGP signed inside? verify signature
            if (preg_match('/^-----BEGIN PGP SIGNED MESSAGE-----/', $body)) {
                $this->parse_plain_signed($p, $body);
            }
            // Encrypted plain message may contain encrypted attachments
            // in such case attachments have .pgp extension and application/octet-stream.
            // in such case attachments have .pgp extension and type application/octet-stream.
            // This is what happens when you select "Encrypt each attachment separately
            // and send the message using inline PGP" in Thunderbird's Enigmail.
            // find parent part ID
            if (strpos($part->mime_id, '.')) {
                $items = explode('.', $part->mime_id);
                array_pop($items);
                $parent = implode('.', $items);
            }
            else {
                $parent = 0;
            }
            if ($p['object']->mime_parts[$parent]) {
                foreach ((array)$p['object']->mime_parts[$parent]->parts as $p) {
@@ -615,6 +631,19 @@
                }
            }
        }
        // decryption failed, but the message may have already
        // been cached with the modified parts (see above),
        // let's bring the original state back
        else if ($p['object']->mime_parts[$parent]) {
            foreach ((array)$p['object']->mime_parts[$parent]->parts as $p) {
                if ($p->need_decryption && !preg_match('/^(.*)\.pgp$/i', $p->filename, $m)) {
                    // modify filename
                    $p->filename .= '.pgp';
                    // flag the part, it will be decrypted when needed
                    unset($p->need_decryption);
                }
            }
        }
    }
    /**
@@ -624,13 +653,17 @@
     */
    private function parse_pgp_encrypted(&$p)
    {
        if (!$this->rc->config->get('enigma_decryption', true)) {
            return;
        }
        $this->load_pgp_driver();
        $struct = $p['structure'];
        $part   = $struct->parts[1];
        // Get body
        $body = $this->get_part_body($p['object'], $part->mime_id);
        $body = $this->get_part_body($p['object'], $part);
        // Decrypt
        $result = $this->pgp_decrypt($body);
@@ -641,6 +674,13 @@
            // Modify original message structure
            $this->modify_structure($p, $struct);
            // Parse the structure (there may be encrypted/signed parts inside
            $this->part_structure(array(
                    'object'    => $p['object'],
                    'structure' => $struct,
                    'mimetype'  => $struct->mimetype
                ), $body);
            // Attach the decryption message to all parts
            $this->decryptions[$struct->mime_id] = $result;
@@ -654,6 +694,10 @@
            // Make sure decryption status message will be displayed
            $part->type = 'content';
            $p['object']->parts[] = $part;
            // don't show encrypted part on attachments list
            // don't show "cannot display encrypted message" text
            $p['abort'] = true;
        }
    }
@@ -664,7 +708,11 @@
     */
    private function parse_smime_encrypted(&$p)
    {
//        $this->load_smime_driver();
        if (!$this->rc->config->get('enigma_decryption', true)) {
            return;
        }
        // @TODO
    }
    /**
@@ -680,7 +728,7 @@
        // @TODO: Handle big bodies using (temp) files
        $sig = $this->pgp_driver->verify($msg_body, $sig_body);
        if (($sig instanceof enigma_error) && $sig->getCode() != enigma_error::E_KEYNOTFOUND)
        if (($sig instanceof enigma_error) && $sig->getCode() != enigma_error::KEYNOTFOUND)
            rcube::raise_error(array(
                'code' => 600, 'type' => 'php',
                'file' => __FILE__, 'line' => __LINE__,
@@ -705,7 +753,7 @@
        if ($result instanceof enigma_error) {
            $err_code = $result->getCode();
            if (!in_array($err_code, array(enigma_error::E_KEYNOTFOUND, enigma_error::E_BADPASS)))
            if (!in_array($err_code, array(enigma_error::KEYNOTFOUND, enigma_error::BADPASS)))
                rcube::raise_error(array(
                    'code' => 600, 'type' => 'php',
                    'file' => __FILE__, 'line' => __LINE__,
@@ -736,7 +784,7 @@
        if ($result instanceof enigma_error) {
            $err_code = $result->getCode();
            if (!in_array($err_code, array(enigma_error::E_KEYNOTFOUND, enigma_error::E_BADPASS)))
            if (!in_array($err_code, array(enigma_error::KEYNOTFOUND, enigma_error::BADPASS)))
                rcube::raise_error(array(
                    'code' => 600, 'type' => 'php',
                    'file' => __FILE__, 'line' => __LINE__,
@@ -765,7 +813,7 @@
        if ($result instanceof enigma_error) {
            $err_code = $result->getCode();
            if (!in_array($err_code, array(enigma_error::E_KEYNOTFOUND, enigma_error::E_BADPASS)))
            if (!in_array($err_code, array(enigma_error::KEYNOTFOUND, enigma_error::BADPASS)))
                rcube::raise_error(array(
                    'code' => 600, 'type' => 'php',
                    'file' => __FILE__, 'line' => __LINE__,
@@ -882,6 +930,29 @@
    }
    /**
     * PGP keys pair generation.
     *
     * @param array Key pair parameters
     *
     * @return mixed enigma_key or enigma_error
     */
    function generate_key($data)
    {
        $this->load_pgp_driver();
        $result = $this->pgp_driver->gen_key($data);
        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
@@ -934,6 +1005,40 @@
        $this->rc->output->send();
    }
    /**
     * PGP keys/certs export..
     *
     * @param string   Key ID
     * @param resource Optional output stream
     *
     * @return mixed Key content or enigma_error
     */
    function export_key($key, $fp = null)
    {
        $this->load_pgp_driver();
        $result = $this->pgp_driver->export($key, $fp);
        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;
        }
        if ($fp) {
            fwrite($fp, $result);
        }
        else {
            return $result;
        }
    }
    /**
     * Registers password for specified key/cert sent by the password prompt.
     */
    function password_handler()
    {
        $keyid  = rcube_utils::get_input_value('_keyid', rcube_utils::INPUT_POST);
@@ -944,6 +1049,9 @@
        }
    }
    /**
     * Saves key/cert password in user session
     */
    function save_password($keyid, $password)
    {
        // we store passwords in session for specified time
@@ -957,6 +1065,9 @@
        $_SESSION['enigma_pass'] = $this->rc->encrypt(serialize($config));
    }
    /**
     * Returns currently stored passwords
     */
    function get_passwords()
    {
        if ($config = $_SESSION['enigma_pass']) {
@@ -964,12 +1075,12 @@
            $config = @unserialize($config);
        }
        $threshold = time() - self::PASSWORD_TIME;
        $threshold = $this->password_time ? time() - $this->password_time : 0;
        $keys      = array();
        // delete expired passwords
        foreach ((array) $config as $key => $value) {
            if ($value[1] < $threshold) {
            if ($threshold && $value[1] < $threshold) {
                unset($config[$key]);
                $modified = true;
            }
@@ -988,20 +1099,21 @@
    /**
     * Get message part body.
     *
     * @param rcube_message Message object
     * @param string        Message part ID
     * @param bool          Return raw body with headers
     * @param rcube_message      Message object
     * @param rcube_message_part Message part
     * @param bool               Return raw body with headers
     */
    private function get_part_body($msg, $part_id, $full = false)
    private function get_part_body($msg, $part, $full = false)
    {
        // @TODO: Handle big bodies using file handles
        if ($full) {
            $storage = $this->rc->get_storage();
            $body    = $storage->get_raw_headers($msg->uid, $part_id);
            $body   .= $storage->get_raw_body($msg->uid, null, $part_id);
            $body    = $storage->get_raw_headers($msg->uid, $part->mime_id);
            $body   .= $storage->get_raw_body($msg->uid, null, $part->mime_id);
        }
        else {
            $body = $msg->get_part_body($part_id, false);
            $body = $msg->get_part_body($part->mime_id, false);
        }
        return $body;
@@ -1035,6 +1147,7 @@
    {
        // modify mime_parts property of the message object
        $old_id = $p['structure']->mime_id;
        foreach (array_keys($p['object']->mime_parts) as $idx) {
            if (!$old_id || $idx == $old_id || strpos($idx, $old_id . '.') === 0) {
                unset($p['object']->mime_parts[$idx]);
@@ -1061,13 +1174,13 @@
        $part->body_modified = true;
        $part->encoding      = 'stream';
        // Cache the fact it was decrypted
        $part->encrypted = true;
        // modify part identifier
        if ($old_id) {
            $part->mime_id = !$part->mime_id ? $old_id : ($old_id . '.' . $part->mime_id);
        }
        // Cache the fact it was decrypted
        $this->encrypted_parts[] = $part->mime_id;
        $msg->mime_parts[$part->mime_id] = $part;
@@ -1078,6 +1191,33 @@
    }
    /**
     * Extracts body and signature of multipart/signed message body
     */
    private function explode_signed_body($body, $boundary)
    {
        if (!$body) {
            return array();
        }
        $boundary     = '--' . $boundary;
        $boundary_len = strlen($boundary) + 2;
        // Find boundaries
        $start = strpos($body, $boundary) + $boundary_len;
        $end   = strpos($body, $boundary, $start);
        // Get signed body and signature
        $sig  = substr($body, $end + $boundary_len);
        $body = substr($body, $start, $end - $start - 2);
        // Cleanup signature
        $sig = substr($sig, strpos($sig, "\r\n\r\n") + 4);
        $sig = substr($sig, 0, strpos($sig, $boundary));
        return array($body, $sig);
    }
    /**
     * Checks if specified message part is a PGP-key or S/MIME cert data
     *
     * @param rcube_message_part Part object