From 3cc6ec573d93ed05adf98d69a6fab6e38c776731 Mon Sep 17 00:00:00 2001
From: Aleksander Machniak <alec@alec.pl>
Date: Wed, 27 May 2015 07:37:10 -0400
Subject: [PATCH] Make password encryption algorithms available for all drivers (#1490134)

---
 plugins/password/drivers/sql.php             |  130 ++++-------
 plugins/password/composer.json               |    2 
 plugins/password/helpers/dovecot_hmacmd5.php |    2 
 plugins/password/drivers/ldap.php            |  164 --------------
 plugins/password/drivers/ldap_simple.php     |    4 
 plugins/password/config.inc.php.dist         |   78 ++++--
 plugins/password/password.php                |  266 ++++++++++++++++++++++++
 7 files changed, 363 insertions(+), 283 deletions(-)

diff --git a/plugins/password/composer.json b/plugins/password/composer.json
index 3aba2a2..743d15e 100644
--- a/plugins/password/composer.json
+++ b/plugins/password/composer.json
@@ -3,7 +3,7 @@
     "type": "roundcube-plugin",
     "description": "Password Change for Roundcube. Plugin adds a possibility to change user password using many methods (drivers) via Settings/Password tab.",
     "license": "GPLv3+",
-    "version": "3.5",
+    "version": "4.0",
     "authors": [
         {
             "name": "Aleksander Machniak",
diff --git a/plugins/password/config.inc.php.dist b/plugins/password/config.inc.php.dist
index af87a83..0b004b8 100644
--- a/plugins/password/config.inc.php.dist
+++ b/plugins/password/config.inc.php.dist
@@ -27,8 +27,7 @@
 
 // Array of hosts that support password changing. Default is NULL.
 // Listed hosts will feature a Password option in Settings; others will not.
-// Example:
-//$config['password_hosts'] = array('mail.example.com', 'mail2.example.org');
+// Example: array('mail.example.com', 'mail2.example.org');
 $config['password_hosts'] = null;
 
 // Enables saving the new password even if it matches the old password. Useful
@@ -37,6 +36,30 @@
 
 // Enables forcing new users to change their password at their first login.
 $config['password_force_new_user'] = false;
+
+// Default password hashing/crypting algorithm.
+// Possible options: des-crypt, ext-des-crypt, md5-crypt, blowfish-crypt,
+// sha256-crypt, sha512-crypt, md5, sha, smd5, ssha, samba, ad, dovecot, clear.
+// For details see password::hash_password() method.
+$config['password_algorithm'] = 'clear';
+
+// Password prefix (e.g. {CRYPT}, {SHA}) for passwords generated
+// using password_algorithm above. Default: empty.
+$config['password_algorithm_prefix'] = '';
+
+// Path for dovecotpw/doveadm-pw (if not in $PATH)
+// Used for password_algorithm = 'dovecot'.
+// $config['password_dovecotpw'] = '/usr/local/sbin/dovecotpw';
+
+// Dovecot method (dovecotpw -s 'method')
+// Used for password_algorithm = 'dovecot'.
+$config['password_dovecotpw_method'] = 'CRAM-MD5';
+
+// Iteration count parameter for Blowfish-based hashing algo.
+// It must be between 4 and 31. Default: 12.
+// Be aware, the higher the value, the longer it takes to generate the password hashes.
+$config['password_blowfish_cost'] = 12;
+
 
 
 // SQL Driver options
@@ -48,44 +71,42 @@
 // The SQL query used to change the password.
 // The query can contain the following macros that will be expanded as follows:
 //      %p is replaced with the plaintext new password
-//      %c is replaced with the crypt version of the new password, MD5 if available
-//         otherwise DES. More hash function can be enabled using the password_crypt_hash 
-//         configuration parameter.
-//      %D is replaced with the dovecotpw-crypted version of the new password
-//      %o is replaced with the password before the change
-//      %n is replaced with the hashed version of the new password
-//      %q is replaced with the hashed password before the change
+//      %P is replaced with the crypted/hashed new password
+//         according to configured password_method
+//      %o is replaced with the old (current) password
+//      %O is replaced with the crypted/hashed old (current) password
+//         according to configured password_method
 //      %h is replaced with the imap host (from the session info)
 //      %u is replaced with the username (from the session info)
 //      %l is replaced with the local part of the username
 //         (in case the username is an email address)
 //      %d is replaced with the domain part of the username
 //         (in case the username is an email address)
+// Deprecated macros:
+//      %c is replaced with the crypt version of the new password, MD5 if available
+//         otherwise DES. More hash function can be enabled using the password_crypt_hash
+//         configuration parameter.
+//      %D is replaced with the dovecotpw-crypted version of the new password
+//      %n is replaced with the hashed version of the new password
+//      %q is replaced with the hashed password before the change
 // Escaping of macros is handled by this module.
 // Default: "SELECT update_passwd(%c, %u)"
 $config['password_query'] = 'SELECT update_passwd(%c, %u)';
 
-// By default the crypt() function which is used to create the '%c' 
-// parameter uses the md5 algorithm. To use different algorithms 
-// you can choose between: des, md5, blowfish, sha256, sha512.
-// Before using other hash functions than des or md5 please make sure
-// your operating system supports the other hash functions.
+// By default the crypt() function which is used to create the %c
+// parameter uses the md5 algorithm (deprecated, use %P).
+// You can choose between: des, md5, blowfish, sha256, sha512.
 $config['password_crypt_hash'] = 'md5';
 
 // By default domains in variables are using unicode.
 // Enable this option to use punycoded names
 $config['password_idn_ascii'] = false;
 
-// Path for dovecotpw (if not in $PATH)
-// $config['password_dovecotpw'] = '/usr/local/sbin/dovecotpw';
-
-// Dovecot method (dovecotpw -s 'method')
-$config['password_dovecotpw_method'] = 'CRAM-MD5';
-
 // Enables use of password with crypt method prefix in %D, e.g. {MD5}$1$LUiMYWqx$fEkg/ggr/L6Mb2X7be4i1/
+// when using the %D macro (deprecated, use %P)
 $config['password_dovecotpw_with_method'] = false;
 
-// Using a password hash for %n and %q variables.
+// Using a password hash for %n and %q variables (deprecated, use %P).
 // Determine which hashing algorithm should be used to generate
 // the hashed new and current password for using them within the
 // SQL query. Requires PHP's 'hash' extension.
@@ -94,11 +115,6 @@
 // You can also decide whether the hash should be provided
 // as hex string or in base64 encoded format.
 $config['password_hash_base64'] = false;
-
-// Iteration count parameter for Blowfish-based hashing algo.
-// It must be between 4 and 31. Default: 12.
-// Be aware, the higher the value, the longer it takes to generate the password hashes.
-$config['password_blowfish_cost'] = 12;
 
 
 // Poppassd Driver options
@@ -210,8 +226,7 @@
 // LDAP password hash type
 // Standard LDAP encryption type which must be one of: crypt,
 // ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, ad, cram-md5 (dovecot style) or clear.
-// Please note that most encodage types require external libraries
-// to be included in your PHP installation, see function hashPassword in drivers/ldap.php for more info.
+// Set to 'default' if you want to use method specified in password_algorithm option above.
 // Multiple password Values can be generated by concatenating encodings with a +. E.g. 'cram-md5+crypt'
 // Default: 'crypt'.
 $config['password_ldap_encodage'] = 'crypt';
@@ -315,9 +330,9 @@
 $config['hmailserver_remote_dcom'] = false;
 // Windows credentials
 $config['hmailserver_server'] = array(
-    'Server' => 'localhost', // hostname or ip address
-    'Username' => 'administrator', // windows username
-    'Password' => 'password' // windows user password
+    'Server'   => 'localhost',      // hostname or ip address
+    'Username' => 'administrator',  // windows username
+    'Password' => 'password'        // windows user password
 );
 
 
@@ -377,7 +392,6 @@
 // ---------------------
 // Gearman host (default: localhost)
 $config['password_gearman_host'] = 'localhost';
-
 
 
 // Plesk/PPA Driver options
diff --git a/plugins/password/drivers/ldap.php b/plugins/password/drivers/ldap.php
index 6ed5ada..46c7835 100644
--- a/plugins/password/drivers/ldap.php
+++ b/plugins/password/drivers/ldap.php
@@ -93,8 +93,7 @@
         $crypted_pass = array();
 
         foreach ($encodages as $enc) {
-            $cpw = self::hash_password($passwd, $enc);
-            if (!empty($cpw)) {
+            if ($cpw = password::hash_password($passwd, $enc)) {
                 $crypted_pass[] = $cpw;
             }
         }
@@ -111,7 +110,7 @@
         }
 
         // Crypt new samba password
-        if ($smbpwattr && !($samba_pass = self::hash_password($passwd, 'samba'))) {
+        if ($smbpwattr && !($samba_pass = password::hash_password($passwd, 'samba'))) {
             return PASSWORD_CRYPT_ERROR;
         }
 
@@ -215,165 +214,6 @@
             $str = str_replace('%dc', $dc, $str);
             $str = str_replace('%domain', $parts[1], $str);
             $str = str_replace('%d', $parts[1], $str);
-        }
-
-        return $str;
-    }
-
-    /**
-     * Code originaly from the phpLDAPadmin development team
-     * http://phpldapadmin.sourceforge.net/
-     *
-     * Hashes a password and returns the hash based on the specified enc_type
-     */
-    static function hash_password($password_clear, $encodage_type)
-    {
-        $encodage_type = strtolower($encodage_type);
-        switch ($encodage_type) {
-        case 'crypt':
-            $crypted_password = '{CRYPT}' . crypt($password_clear, self::random_salt(2));
-            break;
-
-        case 'ext_des':
-            /* Extended DES crypt. see OpenBSD crypt man page */
-            if (!defined('CRYPT_EXT_DES') || CRYPT_EXT_DES == 0) {
-                /* Your system crypt library does not support extended DES encryption */
-                return false;
-            }
-
-            $crypted_password = '{CRYPT}' . crypt($password_clear, '_' . self::random_salt(8));
-            break;
-
-        case 'md5crypt':
-            if (!defined('CRYPT_MD5') || CRYPT_MD5 == 0) {
-                /* Your system crypt library does not support md5crypt encryption */
-                return false;
-            }
-
-            $crypted_password = '{CRYPT}' . crypt($password_clear, '$1$' . self::random_salt(9));
-            break;
-
-        case 'blowfish':
-            if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH == 0) {
-                /* Your system crypt library does not support blowfish encryption */
-                return false;
-            }
-
-            $rcmail = rcmail::get_instance();
-            $cost   = (int) $rcmail->config->get('password_blowfish_cost');
-            $cost   = $cost < 4 || $cost > 31 ? 12 : $cost;
-            $prefix = sprintf('$2a$%02d$', $cost);
-
-            $crypted_password = '{CRYPT}' . crypt($password_clear, $prefix . self::random_salt(22));
-            break;
-
-        case 'md5':
-            $crypted_password = '{MD5}' . base64_encode(pack('H*', md5($password_clear)));
-            break;
-
-        case 'sha':
-            if (function_exists('sha1')) {
-                /* Use PHP 4.3.0+ sha1 function, if it is available */
-                $crypted_password = '{SHA}' . base64_encode(pack('H*', sha1($password_clear)));
-            }
-            else if (function_exists('hash')) {
-                $crypted_password = '{SHA}' . base64_encode(hash('sha1', $password_clear, true));
-            }
-            else if (function_exists('mhash')) {
-                $crypted_password = '{SHA}' . base64_encode(mhash(MHASH_SHA1, $password_clear));
-            }
-            else {
-                /* Your PHP install does not have the mhash()/hash() nor sha1() function */
-                return false;
-            }
-            break;
-
-        case 'ssha':
-            $salt = substr(pack('h*', md5(mt_rand())), 0, 8);
-
-            if (function_exists('mhash') && function_exists('mhash_keygen_s2k')) {
-                $salt     = mhash_keygen_s2k(MHASH_SHA1, $password_clear, $salt, 4);
-                $password = mhash(MHASH_SHA1, $password_clear . $salt);
-            }
-            else if (function_exists('sha1')) {
-                $salt     = substr(pack("H*", sha1($salt . $password_clear)), 0, 4);
-                $password = sha1($password_clear . $salt, true);
-            }
-            else if (function_exists('hash')) {
-                $salt     = substr(pack("H*", hash('sha1', $salt . $password_clear)), 0, 4);
-                $password = hash('sha1', $password_clear . $salt, true);
-            }
-
-            if ($password) {
-                $crypted_password = '{SSHA}' . base64_encode($password . $salt);
-            }
-            else {
-                /* Your PHP install does not have the mhash()/hash() nor sha1() function */
-                return false;
-            }
-            break;
-
-
-        case 'smd5':
-            $salt = substr(pack('h*', md5(mt_rand())), 0, 8);
-
-            if (function_exists('mhash') && function_exists('mhash_keygen_s2k')) {
-                $salt     = mhash_keygen_s2k(MHASH_MD5, $password_clear, $salt, 4);
-                $password = mhash(MHASH_MD5, $password_clear . $salt);
-            }
-            else if (function_exists('hash')) {
-                $salt     = substr(pack("H*", hash('md5', $salt . $password_clear)), 0, 4);
-                $password = hash('md5', $password_clear . $salt, true);
-            }
-            else {
-                $salt     = substr(pack("H*", md5($salt . $password_clear)), 0, 4);
-                $password = md5($password_clear . $salt, true);
-            }
-
-            $crypted_password = '{SMD5}' . base64_encode($password . $salt);
-            break;
-
-        case 'samba':
-            if (function_exists('hash')) {
-                $crypted_password = hash('md4', rcube_charset::convert($password_clear, RCUBE_CHARSET, 'UTF-16LE'));
-                $crypted_password = strtoupper($crypted_password);
-            }
-            else {
-                /* Your PHP install does not have the hash() function */
-                return false;
-            }
-            break;
-
-        case 'ad':
-            $crypted_password = rcube_charset::convert('"' . $password_clear . '"', RCUBE_CHARSET, 'UTF-16LE');
-            break;
-
-        case 'cram-md5':
-            require_once __DIR__ . '/../helpers/dovecot_hmacmd5.php';
-            return dovecot_hmacmd5($password_clear);
-            break;
-
-        case 'clear':
-        default:
-            $crypted_password = $password_clear;
-        }
-
-        return $crypted_password;
-    }
-
-    /**
-     * Code originaly from the phpLDAPadmin development team
-     * http://phpldapadmin.sourceforge.net/
-     *
-     * Used to generate a random salt for crypt-style passwords
-     */
-    static function random_salt($length)
-    {
-        $possible = '0123456789' . 'abcdefghijklmnopqrstuvwxyz' . 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . './';
-        $str = '';
-
-        while (strlen($str) < $length) {
-            $str .= substr($possible, (rand() % strlen($possible)), 1);
         }
 
         return $str;
diff --git a/plugins/password/drivers/ldap_simple.php b/plugins/password/drivers/ldap_simple.php
index 9123ea8..5b82205 100644
--- a/plugins/password/drivers/ldap_simple.php
+++ b/plugins/password/drivers/ldap_simple.php
@@ -111,7 +111,7 @@
         $smblchattr   = $rcmail->config->get('password_ldap_samba_lchattr');
         $samba        = $rcmail->config->get('password_ldap_samba');
         $pass_mode    = $rcmail->config->get('password_ldap_encodage');
-        $crypted_pass = rcube_ldap_password::hash_password($passwd, $pass_mode);
+        $crypted_pass = password::hash_password($passwd, $pass_mode);
 
         // Support password_ldap_samba option for backward compat.
         if ($samba && !$smbpwattr) {
@@ -125,7 +125,7 @@
         }
 
         // Crypt new Samba password
-        if ($smbpwattr && !($samba_pass = rcube_ldap_password::hash_password($passwd, 'samba'))) {
+        if ($smbpwattr && !($samba_pass = password::hash_password($passwd, 'samba'))) {
             return PASSWORD_CRYPT_ERROR;
         }
 
diff --git a/plugins/password/drivers/sql.php b/plugins/password/drivers/sql.php
index 37e162e..9659fa0 100644
--- a/plugins/password/drivers/sql.php
+++ b/plugins/password/drivers/sql.php
@@ -46,110 +46,70 @@
             return PASSWORD_ERROR;
         }
 
-        // crypted password
-        if (strpos($sql, '%c') !== FALSE) {
-            $salt = '';
+        // new password - default hash method
+        if (strpos($sql, '%P') !== false) {
+            $password = password::hash_password($passwd);
 
-            if (!($crypt_hash = $rcmail->config->get('password_crypt_hash'))) {
-                if (CRYPT_MD5)
-                    $crypt_hash = 'md5';
-                else if (CRYPT_STD_DES)
-                    $crypt_hash = 'des';
-            }
-
-            switch ($crypt_hash) {
-            case 'md5':
-                $len = 8;
-                $salt_hashindicator = '$1$';
-                break;
-            case 'des':
-                $len = 2;
-                break;
-            case 'blowfish':
-                $cost = (int) $rcmail->config->get('password_blowfish_cost');
-                $cost = $cost < 4 || $cost > 31 ? 12 : $cost;
-                $len  = 22;
-                $salt_hashindicator = sprintf('$2a$%02d$', $cost);
-                break;
-            case 'sha256':
-                $len = 16;
-                $salt_hashindicator = '$5$';
-                break;
-            case 'sha512':
-                $len = 16;
-                $salt_hashindicator = '$6$';
-                break;
-            default:
+            if ($password === false) {
                 return PASSWORD_CRYPT_ERROR;
             }
 
-            //Restrict the character set used as salt (#1488136)
-            $seedchars = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
-            for ($i = 0; $i < $len ; $i++) {
-                $salt .= $seedchars[rand(0, 63)];
-            }
-
-            $sql = str_replace('%c',  $db->quote(crypt($passwd, $salt_hashindicator ? $salt_hashindicator .$salt.'$' : $salt)), $sql);
+            $sql = str_replace('%P',  $db->quote($password), $sql);
         }
 
-        // dovecotpw
-        if (strpos($sql, '%D') !== FALSE) {
-            if (!($dovecotpw = $rcmail->config->get('password_dovecotpw')))
-                $dovecotpw = 'dovecotpw';
-            if (!($method = $rcmail->config->get('password_dovecotpw_method')))
-                $method = 'CRAM-MD5';
+        // old password - default hash method
+        if (strpos($sql, '%O') !== false) {
+            $password = password::hash_password($curpass);
 
-            // use common temp dir
-            $tmp_dir = $rcmail->config->get('temp_dir');
-            $tmpfile = tempnam($tmp_dir, 'roundcube-');
-
-            $pipe = popen("$dovecotpw -s '$method' > '$tmpfile'", "w");
-            if (!$pipe) {
-                unlink($tmpfile);
+            if ($password === false) {
                 return PASSWORD_CRYPT_ERROR;
             }
-            else {
-                fwrite($pipe, $passwd . "\n", 1+strlen($passwd)); usleep(1000);
-                fwrite($pipe, $passwd . "\n", 1+strlen($passwd));
-                pclose($pipe);
-                $newpass = trim(file_get_contents($tmpfile), "\n");
-                if (!preg_match('/^\{' . $method . '\}/', $newpass)) {
-                    return PASSWORD_CRYPT_ERROR;
-                }
-                if (!$rcmail->config->get('password_dovecotpw_with_method'))
-                    $newpass = trim(str_replace('{' . $method . '}', '', $newpass));
-                unlink($tmpfile);
-            }
-            $sql = str_replace('%D', $db->quote($newpass), $sql);
+
+            $sql = str_replace('%O',  $db->quote($password), $sql);
         }
 
-        // hashed passwords
-        if (preg_match('/%[n|q]/', $sql)) {
-            if (!extension_loaded('hash')) {
-                rcube::raise_error(array(
-                    'code' => 600,
-                    'type' => 'php',
-                    'file' => __FILE__, 'line' => __LINE__,
-                    'message' => "Password plugin: 'hash' extension not loaded!"
-                ), true, false);
+        // crypted password (deprecated, use %P)
+        if (strpos($sql, '%c') !== false) {
+            $password = password::hash_password($passwd, 'crypt', false);
 
-                return PASSWORD_ERROR;
+            if ($password === false) {
+                return PASSWORD_CRYPT_ERROR;
             }
 
-            if (!($hash_algo = strtolower($rcmail->config->get('password_hash_algorithm')))) {
-                $hash_algo = 'sha1';
+            $sql = str_replace('%c',  $db->quote($password), $sql);
+        }
+
+        // dovecotpw (deprecated, use %P)
+        if (strpos($sql, '%D') !== false) {
+            $password = password::hash_password($passwd, 'dovecot', false);
+
+            if ($password === false) {
+                return PASSWORD_CRYPT_ERROR;
             }
 
-            $hash_passwd = hash($hash_algo, $passwd);
-            $hash_curpass = hash($hash_algo, $curpass);
+            $sql = str_replace('%D', $db->quote($password), $sql);
+        }
 
-            if ($rcmail->config->get('password_hash_base64')) {
-                $hash_passwd = base64_encode(pack('H*', $hash_passwd));
-                $hash_curpass = base64_encode(pack('H*', $hash_curpass));
+        // hashed passwords (deprecated, use %P)
+        if (strpos($sql, '%n') !== false) {
+            $password = password::hash_password($passwd, 'hash', false);
+
+            if ($password === false) {
+                return PASSWORD_CRYPT_ERROR;
             }
 
-            $sql = str_replace('%n', $db->quote($hash_passwd, 'text'), $sql);
-            $sql = str_replace('%q', $db->quote($hash_curpass, 'text'), $sql);
+            $sql = str_replace('%n', $db->quote($password, 'text'), $sql);
+        }
+
+        // hashed passwords (deprecated, use %P)
+        if (strpos($sql, '%q') !== false) {
+            $password = password::hash_password($curpass, 'hash', false);
+
+            if ($password === false) {
+                return PASSWORD_CRYPT_ERROR;
+            }
+
+            $sql = str_replace('%q', $db->quote($password, 'text'), $sql);
         }
 
         // Handle clear text passwords securely (#1487034)
diff --git a/plugins/password/helpers/dovecot_hmacmd5.php b/plugins/password/helpers/dovecot_hmacmd5.php
index 644b537..da4d005 100644
--- a/plugins/password/helpers/dovecot_hmacmd5.php
+++ b/plugins/password/helpers/dovecot_hmacmd5.php
@@ -187,5 +187,5 @@
 
 function dovecot_hmacmd5 ($s) {
 	if (strlen($s) > 64) $s=pack("H*", md5($s));
-	return "{CRAM-MD5}" . md5_oneround($s, 0) . md5_oneround($s, 1);
+	return md5_oneround($s, 0) . md5_oneround($s, 1);
 }
diff --git a/plugins/password/password.php b/plugins/password/password.php
index 9239cd0..476e9ea 100644
--- a/plugins/password/password.php
+++ b/plugins/password/password.php
@@ -367,4 +367,270 @@
 
         return true;
     }
+
+    /**
+     * Hashes a password and returns the hash based on the specified method
+     *
+     * Parts of the code originally from the phpLDAPadmin development team
+     * http://phpldapadmin.sourceforge.net/
+     *
+     * @param string      Clear password
+     * @param string      Hashing method
+     * @param bool|string Prefix string or TRUE to add a default prefix
+     *
+     * @return string Hashed password
+     */
+    static function hash_password($password, $method = '', $prefixed = true)
+    {
+        $method = strtolower($method);
+        $rcmail = rcmail::get_instance();
+
+        if (empty($method) || $method == 'default') {
+            $method   = $rcmail->config->get('password_algorithm');
+            $prefixed = $rcmail->config->get('password_algorithm_prefix');
+            $default  = true;
+        }
+        else if ($method == 'crypt') { // deprecated
+            if (!($method = $rcmail->config->get('password_crypt_hash'))) {
+                $method = 'md5';
+            }
+
+            if (!strpos($method, '-crypt')) {
+                $method .= '-crypt';
+            }
+        }
+
+        switch ($method) {
+        case 'des':
+        case 'des-crypt':
+            $crypted = crypt($password, self::random_salt(2));
+            $prefix  = '{CRYPT}';
+            break;
+
+        case 'ext_des': // for BC
+        case 'ext-des-crypt':
+            $crypted = crypt($password, '_' . self::random_salt(8));
+            $prefix  = '{CRYPT}';
+            break;
+
+        case 'md5crypt': // for BC
+        case 'md5-crypt':
+            $crypted = crypt($password, '$1$' . self::random_salt(9));
+            $prefix  = '{CRYPT}';
+            break;
+
+        case 'sha256-crypt':
+            $crypted = crypt($password, '$5$' . self::random_salt(16));
+            $prefix  = '{CRYPT}';
+            break;
+
+        case 'sha512-crypt':
+            $crypted = crypt($password, '$6$' . self::random_salt(16));
+            $prefix  = '{CRYPT}';
+            break;
+
+        case 'blowfish': // for BC
+        case 'blowfish-crypt':
+            $cost   = (int) $rcmail->config->get('password_blowfish_cost');
+            $cost   = $cost < 4 || $cost > 31 ? 12 : $cost;
+            $prefix = sprintf('$2a$%02d$', $cost);
+
+            $crypted = crypt($password, $prefix . self::random_salt(22));
+            $prefix  = '{CRYPT}';
+            break;
+
+        case 'md5':
+            $crypted = base64_encode(pack('H*', md5($password)));
+            $prefix  = '{MD5}';
+            break;
+
+        case 'sha':
+            if (function_exists('sha1')) {
+                $crypted = pack('H*', sha1($password));
+            }
+            else if (function_exists('hash')) {
+                $crypted = hash('sha1', $password, true);
+            }
+            else if (function_exists('mhash')) {
+                $crypted = mhash(MHASH_SHA1, $password);
+            }
+            else {
+                rcube::raise_error(array(
+                    'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
+                    'message' => "Password plugin: Your PHP install does not have the mhash()/hash() nor sha1() function"
+                ), true, true);
+            }
+
+            $crypted = base64_encode($crypted);
+            $prefix = '{SHA}';
+            break;
+
+        case 'ssha':
+            $salt = substr(pack('h*', md5(mt_rand())), 0, 8);
+
+            if (function_exists('mhash') && function_exists('mhash_keygen_s2k')) {
+                $salt    = mhash_keygen_s2k(MHASH_SHA1, $password, $salt, 4);
+                $crypted = mhash(MHASH_SHA1, $password . $salt);
+            }
+            else if (function_exists('sha1')) {
+                $salt    = substr(pack("H*", sha1($salt . $password)), 0, 4);
+                $crypted = sha1($password . $salt, true);
+            }
+            else if (function_exists('hash')) {
+                $salt    = substr(pack("H*", hash('sha1', $salt . $password)), 0, 4);
+                $crypted = hash('sha1', $password . $salt, true);
+            }
+            else {
+                rcube::raise_error(array(
+                    'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
+                    'message' => "Password plugin: Your PHP install does not have the mhash()/hash() nor sha1() function"
+                ), true, true);
+            }
+
+            $crypted = base64_encode($crypted . $salt);
+            $prefix  = '{SSHA}';
+            break;
+
+        case 'smd5':
+            $salt = substr(pack('h*', md5(mt_rand())), 0, 8);
+
+            if (function_exists('mhash') && function_exists('mhash_keygen_s2k')) {
+                $salt    = mhash_keygen_s2k(MHASH_MD5, $password, $salt, 4);
+                $crypted = mhash(MHASH_MD5, $password . $salt);
+            }
+            else if (function_exists('hash')) {
+                $salt    = substr(pack("H*", hash('md5', $salt . $password)), 0, 4);
+                $crypted = hash('md5', $password . $salt, true);
+            }
+            else {
+                $salt    = substr(pack("H*", md5($salt . $password)), 0, 4);
+                $crypted = md5($password . $salt, true);
+            }
+
+            $crypted = base64_encode($crypted . $salt);
+            $prefix  = '{SMD5}';
+            break;
+
+        case 'samba':
+            if (function_exists('hash')) {
+                $crypted = hash('md4', rcube_charset::convert($password, RCUBE_CHARSET, 'UTF-16LE'));
+                $crypted = strtoupper($crypted_password);
+            }
+            else {
+                rcube::raise_error(array(
+                    'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
+                    'message' => "Password plugin: Your PHP install does not have hash() function"
+                ), true, true);
+            }
+            break;
+
+        case 'ad':
+            $crypted = rcube_charset::convert('"' . $password . '"', RCUBE_CHARSET, 'UTF-16LE');
+            break;
+
+        case 'cram-md5': // deprecated
+            require_once __DIR__ . '/../helpers/dovecot_hmacmd5.php';
+            $crypted = dovecot_hmacmd5($password);
+            $prefix  = '{CRAM-MD5}';
+            break;
+
+        case 'dovecot':
+            if (!($dovecotpw = $rcmail->config->get('password_dovecotpw'))) {
+                $dovecotpw = 'dovecotpw';
+            }
+            if (!($method = $rcmail->config->get('password_dovecotpw_method'))) {
+                $method = 'CRAM-MD5';
+            }
+
+            // use common temp dir
+            $tmp_dir = $rcmail->config->get('temp_dir');
+            $tmpfile = tempnam($tmp_dir, 'roundcube-');
+
+            $pipe = popen("$dovecotpw -s '$method' > '$tmpfile'", "w");
+            if (!$pipe) {
+                unlink($tmpfile);
+                return false;
+            }
+            else {
+                fwrite($pipe, $passwd . "\n", 1+strlen($passwd)); usleep(1000);
+                fwrite($pipe, $passwd . "\n", 1+strlen($passwd));
+                pclose($pipe);
+
+                $crypted = trim(file_get_contents($tmpfile), "\n");
+                unlink($tmpfile);
+
+                if (!preg_match('/^\{' . $method . '\}/', $newpass)) {
+                    return false;
+                }
+
+                if (!$default) {
+                    $prefixed = (bool) $rcmail->config->get('password_dovecotpw_with_method');
+                }
+
+                if (!$prefixed) {
+                    $crypted = trim(str_replace('{' . $method . '}', '', $crypted));
+                }
+
+                $prefixed = false;
+            }
+
+            break;
+
+        case 'hash': // deprecated
+            if (!extension_loaded('hash')) {
+                rcube::raise_error(array(
+                    'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
+                    'message' => "Password plugin: 'hash' extension not loaded!"
+                ), true, true);
+            }
+
+            if (!($hash_algo = strtolower($rcmail->config->get('password_hash_algorithm')))) {
+                $hash_algo = 'sha1';
+            }
+
+            $crypted = hash($hash_algo, $password);
+
+            if ($rcmail->config->get('password_hash_base64')) {
+                $crypted = base64_encode(pack('H*', $crypted));
+            }
+
+            break;
+
+        case 'clear':
+            $crypted = $password;
+        }
+
+        if ($crypted === null || $crypted === false) {
+            return false;
+        }
+
+        if ($prefixed && $prefixed !== true) {
+            $prefix   = $prefixed;
+            $prefixed = true;
+        }
+
+        if ($prefixed === true && $prefix) {
+            $crypted = $prefix . $crypted;
+        }
+
+        return $crypted;
+    }
+
+    /**
+     * Used to generate a random salt for crypt-style passwords
+     *
+     * Code originaly from the phpLDAPadmin development team
+     * http://phpldapadmin.sourceforge.net/
+     */
+    static function random_salt($length)
+    {
+        $possible = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./';
+        $str      = '';
+
+        while (strlen($str) < $length) {
+            $str .= substr($possible, (rand() % strlen($possible)), 1);
+        }
+
+        return $str;
+    }
 }

--
Gitblit v1.9.1