diff --git a/build/phpcs/Joomla/ruleset.xml b/build/phpcs/Joomla/ruleset.xml index a89bb3b2c472a..55fbbf0afd19d 100644 --- a/build/phpcs/Joomla/ruleset.xml +++ b/build/phpcs/Joomla/ruleset.xml @@ -14,6 +14,7 @@ libraries/compat/password/* libraries/fof/* libraries/idna_convert/* + libraries/php-encryption/* libraries/phputf8/* libraries/simplepie/* libraries/phpass/* diff --git a/libraries/cms.php b/libraries/cms.php index e0a831699ed64..1e22507a2323a 100644 --- a/libraries/cms.php +++ b/libraries/cms.php @@ -64,6 +64,9 @@ // Register JArrayHelper due to JRegistry moved to composer's vendor folder JLoader::register('JArrayHelper', JPATH_PLATFORM . '/joomla/utilities/arrayhelper.php'); +// Register the Crypto lib +JLoader::register('Crypto', JPATH_PLATFORM . '/php-encryption/Crypto.php'); + // Register classes where the names have been changed to fit the autoloader rules // @deprecated 4.0 JLoader::register('JToolBar', JPATH_PLATFORM . '/cms/toolbar/toolbar.php'); diff --git a/libraries/joomla/crypt/cipher/crypto.php b/libraries/joomla/crypt/cipher/crypto.php new file mode 100644 index 0000000000000..18011c11edaa0 --- /dev/null +++ b/libraries/joomla/crypt/cipher/crypto.php @@ -0,0 +1,125 @@ +type != 'crypto') + { + throw new InvalidArgumentException('Invalid key of type: ' . $key->type . '. Expected crypto.'); + } + + // Decrypt the data. + try + { + return Crypto::Decrypt($data, $key->public); + } + catch (InvalidCiphertextException $ex) + { + throw new RuntimeException('DANGER! DANGER! The ciphertext has been tampered with!', $ex->getCode(), $ex); + } + catch (CryptoTestFailedException $ex) + { + throw new RuntimeException('Cannot safely perform decryption', $ex->getCode(), $ex); + } + catch (CannotPerformOperationException $ex) + { + throw new RuntimeException('Cannot safely perform decryption', $ex->getCode(), $ex); + } + } + + /** + * Method to encrypt a data string. + * + * @param string $data The data string to encrypt. + * @param JCryptKey $key The key object to use for encryption. + * + * @return string The encrypted data string. + * + * @since 3.5 + * @throws RuntimeException + */ + public function encrypt($data, JCryptKey $key) + { + // Validate key. + if ($key->type != 'crypto') + { + throw new InvalidArgumentException('Invalid key of type: ' . $key->type . '. Expected crypto.'); + } + + // Encrypt the data. + try + { + return Crypto::Encrypt($data, $key->public); + } + catch (CryptoTestFailedException $ex) + { + throw new RuntimeException('Cannot safely perform encryption', $ex->getCode(), $ex); + } + catch (CannotPerformOperationException $ex) + { + throw new RuntimeException('Cannot safely perform encryption', $ex->getCode(), $ex); + } + } + + /** + * Method to generate a new encryption key object. + * + * @param array $options Key generation options. + * + * @return JCryptKey + * + * @since 3.5 + * @throws RuntimeException + */ + public function generateKey(array $options = array()) + { + // Create the new encryption key object. + $key = new JCryptKey('crypto'); + + // Generate the encryption key. + try + { + $key->public = Crypto::CreateNewRandomKey(); + } + catch (CryptoTestFailedException $ex) + { + throw new RuntimeException('Cannot safely create a key', $ex->getCode(), $ex); + } + catch (CannotPerformOperationException $ex) + { + throw new RuntimeException('Cannot safely create a key', $ex->getCode(), $ex); + } + + // Explicitly flag the private as unused in this cipher. + $key->private = 'unused'; + + return $key; + } +} diff --git a/libraries/php-encryption/Crypto.php b/libraries/php-encryption/Crypto.php new file mode 100644 index 0000000000000..1d7586f485bc1 --- /dev/null +++ b/libraries/php-encryption/Crypto.php @@ -0,0 +1,676 @@ + $block) { + throw new CannotPerformOperationException(); + } + $plaintext = self::our_substr($plaintext, 0, self::our_strlen($plaintext) - $pad); + if ($plaintext === FALSE) { + throw new CannotPerformOperationException(); + } + + return $plaintext; + } + + /* + * Returns a random binary string of length $octets bytes. + */ + private static function SecureRandom($octets) + { + self::EnsureFunctionExists("mcrypt_create_iv"); + $random = mcrypt_create_iv($octets, MCRYPT_DEV_URANDOM); + if ($random === FALSE) { + throw new CannotPerformOperationException(); + } else { + return $random; + } + } + + /* + * Use HKDF to derive multiple keys from one. + * http://tools.ietf.org/html/rfc5869 + */ + private static function HKDF($hash, $ikm, $length, $info = '', $salt = NULL) + { + // Find the correct digest length as quickly as we can. + $digest_length = self::MAC_BYTE_SIZE; + if ($hash != self::HASH_FUNCTION) { + $digest_length = self::our_strlen(hash_hmac($hash, '', '', true)); + } + + // Sanity-check the desired output length. + if (empty($length) || !is_int($length) || + $length < 0 || $length > 255 * $digest_length) { + throw new CannotPerformOperationException(); + } + + // "if [salt] not provided, is set to a string of HashLen zeroes." + if (is_null($salt)) { + $salt = str_repeat("\x00", $digest_length); + } + + // HKDF-Extract: + // PRK = HMAC-Hash(salt, IKM) + // The salt is the HMAC key. + $prk = hash_hmac($hash, $ikm, $salt, true); + + // HKDF-Expand: + + // This check is useless, but it serves as a reminder to the spec. + if (self::our_strlen($prk) < $digest_length) { + throw new CannotPerformOperationException(); + } + + // T(0) = '' + $t = ''; + $last_block = ''; + for ($block_index = 1; self::our_strlen($t) < $length; $block_index++) { + // T(i) = HMAC-Hash(PRK, T(i-1) | info | 0x??) + $last_block = hash_hmac( + $hash, + $last_block . $info . chr($block_index), + $prk, + true + ); + // T = T(1) | T(2) | T(3) | ... | T(N) + $t .= $last_block; + } + + // ORM = first L octets of T + $orm = self::our_substr($t, 0, $length); + if ($orm === FALSE) { + throw new CannotPerformOperationException(); + } + return $orm; + } + + private static function VerifyHMAC($correct_hmac, $message, $key) + { + $message_hmac = hash_hmac(self::HASH_FUNCTION, $message, $key, true); + + // We can't just compare the strings with '==', since it would make + // timing attacks possible. We could use the XOR-OR constant-time + // comparison algorithm, but I'm not sure if that's good enough way up + // here in an interpreted language. So we use the method of HMACing the + // strings we want to compare with a random key, then comparing those. + + // NOTE: This leaks information when the strings are not the same + // length, but they should always be the same length here. Enforce it: + if (self::our_strlen($correct_hmac) !== self::our_strlen($message_hmac)) { + throw new CannotPerformOperationException(); + } + + $blind = self::CreateNewRandomKey(); + $message_compare = hash_hmac(self::HASH_FUNCTION, $message_hmac, $blind); + $correct_compare = hash_hmac(self::HASH_FUNCTION, $correct_hmac, $blind); + return $correct_compare === $message_compare; + } + + private static function TestEncryptDecrypt() + { + $key = Crypto::CreateNewRandomKey(); + $data = "EnCrYpT EvErYThInG\x00\x00"; + + // Make sure encrypting then decrypting doesn't change the message. + $ciphertext = Crypto::Encrypt($data, $key); + try { + $decrypted = Crypto::Decrypt($ciphertext, $key); + } catch (InvalidCiphertextException $ex) { + // It's important to catch this and change it into a + // CryptoTestFailedException, otherwise a test failure could trick + // the user into thinking it's just an invalid ciphertext! + throw new CryptoTestFailedException(); + } + if($decrypted !== $data) + { + throw new CryptoTestFailedException(); + } + + // Modifying the ciphertext: Appending a string. + try { + Crypto::Decrypt($ciphertext . "a", $key); + throw new CryptoTestFailedException(); + } catch (InvalidCiphertextException $e) { /* expected */ } + + // Modifying the ciphertext: Changing an IV byte. + try { + $ciphertext[0] = chr((ord($ciphertext[0]) + 1) % 256); + Crypto::Decrypt($ciphertext, $key); + throw new CryptoTestFailedException(); + } catch (InvalidCiphertextException $e) { /* expected */ } + + // Decrypting with the wrong key. + $key = Crypto::CreateNewRandomKey(); + $data = "abcdef"; + $ciphertext = Crypto::Encrypt($data, $key); + $wrong_key = Crypto::CreateNewRandomKey(); + try { + Crypto::Decrypt($ciphertext, $wrong_key); + throw new CryptoTestFailedException(); + } catch (InvalidCiphertextException $e) { /* expected */ } + + // Ciphertext too small (shorter than HMAC). + $key = Crypto::CreateNewRandomKey(); + $ciphertext = str_repeat("A", self::MAC_BYTE_SIZE - 1); + try { + Crypto::Decrypt($ciphertext, $key); + throw new CryptoTestFailedException(); + } catch (InvalidCiphertextException $e) { /* expected */ } + } + + private static function HKDFTestVector() + { + // HKDF test vectors from RFC 5869 + + // Test Case 1 + $ikm = str_repeat("\x0b", 22); + $salt = self::hexToBytes("000102030405060708090a0b0c"); + $info = self::hexToBytes("f0f1f2f3f4f5f6f7f8f9"); + $length = 42; + $okm = self::hexToBytes( + "3cb25f25faacd57a90434f64d0362f2a" . + "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" . + "34007208d5b887185865" + ); + $computed_okm = self::HKDF("sha256", $ikm, $length, $info, $salt); + if ($computed_okm !== $okm) { + throw new CryptoTestFailedException(); + } + + // Test Case 7 + $ikm = str_repeat("\x0c", 22); + $length = 42; + $okm = self::hexToBytes( + "2c91117204d745f3500d636a62f64f0a" . + "b3bae548aa53d423b0d1f27ebba6f5e5" . + "673a081d70cce7acfc48" + ); + $computed_okm = self::HKDF("sha1", $ikm, $length); + if ($computed_okm !== $okm) { + throw new CryptoTestFailedException(); + } + + } + + private static function HMACTestVector() + { + // HMAC test vector From RFC 4231 (Test Case 1) + $key = str_repeat("\x0b", 20); + $data = "Hi There"; + $correct = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"; + if (hash_hmac(self::HASH_FUNCTION, $data, $key) != $correct) { + throw new CryptoTestFailedException(); + } + } + + private static function AESTestVector() + { + // AES CBC mode test vector from NIST SP 800-38A + $key = self::hexToBytes("2b7e151628aed2a6abf7158809cf4f3c"); + $iv = self::hexToBytes("000102030405060708090a0b0c0d0e0f"); + $plaintext = self::hexToBytes( + "6bc1bee22e409f96e93d7e117393172a" . + "ae2d8a571e03ac9c9eb76fac45af8e51" . + "30c81c46a35ce411e5fbc1191a0a52ef" . + "f69f2445df4f9b17ad2b417be66c3710" + ); + $ciphertext = self::hexToBytes( + "7649abac8119b246cee98e9b12e9197d" . + "5086cb9b507219ee95db113a917678b2" . + "73bed6b8e3c1743b7116e69e22229516" . + "3ff1caa1681fac09120eca307586e1a7" . + /* Block due to padding. Not from NIST test vector. + Padding Block: 10101010101010101010101010101010 + Ciphertext: 3ff1caa1681fac09120eca307586e1a7 + (+) 2fe1dab1780fbc19021eda206596f1b7 + AES 8cb82807230e1321d3fae00d18cc2012 + + */ + "8cb82807230e1321d3fae00d18cc2012" + ); + + $computed_ciphertext = self::PlainEncrypt($plaintext, $key, $iv); + if ($computed_ciphertext !== $ciphertext) { + throw new CryptoTestFailedException(); + } + + $computed_plaintext = self::PlainDecrypt($ciphertext, $key, $iv); + if ($computed_plaintext !== $plaintext) { + throw new CryptoTestFailedException(); + } + } + + /* WARNING: Do not call this function on secrets. It creates side channels. */ + private static function hexToBytes($hex_string) + { + return pack("H*", $hex_string); + } + + private static function EnsureFunctionExists($name) + { + if (!function_exists($name)) { + throw new CannotPerformOperationException(); + } + } + + /* + * We need these strlen() and substr() functions because when + * 'mbstring.func_overload' is set in php.ini, the standard strlen() and + * substr() are replaced by mb_strlen() and mb_substr(). + */ + + private static function our_strlen($str) + { + if (function_exists('mb_strlen')) { + $length = mb_strlen($str, '8bit'); + if ($length === FALSE) { + throw new CannotPerformOperationException(); + } + return $length; + } else { + return strlen($str); + } + } + + private static function our_substr($str, $start, $length = NULL) + { + if (function_exists('mb_substr')) + { + // mb_substr($str, 0, NULL, '8bit') returns an empty string on PHP + // 5.3, so we have to find the length ourselves. + if (!isset($length)) { + if ($start >= 0) { + $length = self::our_strlen($str) - $start; + } else { + $length = -$start; + } + } + + return mb_substr($str, $start, $length, '8bit'); + } + + // Unlike mb_substr(), substr() doesn't accept NULL for length + if (isset($length)) { + return substr($str, $start, $length); + } else { + return substr($str, $start); + } + } + +} + +/* + * We want to catch all uncaught exceptions that come from the Crypto class, + * since by default, PHP will leak the key in the stack trace from an uncaught + * exception. This is a really ugly hack, but I think it's justified. + * + * Everything up to handler() getting called should be reliable, so this should + * reliably suppress the stack traces. The rest is just a bonus so that we don't + * make it impossible to debug other exceptions. + * + * This bit of code was adapted from: http://stackoverflow.com/a/7939492 + */ + +class CryptoExceptionHandler +{ + private $rethrow = NULL; + + public function __construct() + { + set_exception_handler(array($this, "handler")); + } + + public function handler($ex) + { + if ( + $ex instanceof InvalidCiphertextException || + $ex instanceof CannotPerformOperationException || + $ex instanceof CryptoTestFailedException + ) { + echo "FATAL ERROR: Uncaught crypto exception. Suppresssing output.\n"; + } else { + /* Re-throw the exception in the destructor. */ + $this->rethrow = $ex; + } + } + + public function __destruct() { + if ($this->rethrow) { + throw $this->rethrow; + } + } +} + +$crypto_exception_handler_object_dont_touch_me = new CryptoExceptionHandler(); + diff --git a/tests/unit/suites/libraries/joomla/crypt/cipher/JCryptCipherCryptoTest.php b/tests/unit/suites/libraries/joomla/crypt/cipher/JCryptCipherCryptoTest.php new file mode 100644 index 0000000000000..8db6ba2c1a986 --- /dev/null +++ b/tests/unit/suites/libraries/joomla/crypt/cipher/JCryptCipherCryptoTest.php @@ -0,0 +1,99 @@ +{DJzOHMCv_<#yKuN/G`/Us{GkgicWG$M|HW;kI0BVZ^|FY/"Obt53?PNaWwhmRtH;lWkWE4vlG5CIFA!abu&F=Xo#Qw}gAp3;GL\'k])%D}C+W&ne6_F$3P5'), + array('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ' . + 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor ' . + 'in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt ' . + 'in culpa qui officia deserunt mollit anim id est laborum.'), + array('لا أحد يحب الألم بذاته، يسعى ورائه أو يبتغيه، ببساطة لأنه الألم...'), + array('Широкая электрификация южных губерний даст мощный толчок подъёму сельского хозяйства'), + array('The quick brown fox jumps over the lazy dog.') + ); + } + + /** + * @testdox Validates data is encrypted and decrypted correctly + * + * @param string $data The decrypted data to validate + * + * @covers JCryptCipherCrypto::decrypt + * @covers JCryptCipherCrypto::encrypt + * @dataProvider dataStrings + */ + public function testDataEncryptionAndDecryption($data) + { + $cipher = new JCryptCipherCrypto; + $key = $cipher->generateKey(); + + $encrypted = $cipher->encrypt($data, $key); + + // Assert that the encrypted value is not the same as the clear text value. + $this->assertNotSame($data, $encrypted); + + $decrypted = $cipher->decrypt($encrypted, $key); + + // Assert the decrypted string is the same value we started with + $this->assertSame($data, $decrypted); + } + + /** + * @testdox Validates keys are correctly generated + * + * @covers JCryptCipherCrypto::generateKey + */ + public function testGenerateKey() + { + $cipher = new JCryptCipherCrypto; + $key = $cipher->generateKey(); + + // Assert that the key is the correct type. + $this->assertInstanceOf('JCryptKey', $key); + + // Assert the private key is our expected value. + $this->assertSame('unused', $key->private); + + // Assert the public key is the expected length + $this->assertSame(Crypto::KEY_BYTE_SIZE, JCrypt::safeStrlen($key->public)); + + // Assert the key is of the correct type. + $this->assertAttributeEquals('crypto', 'type', $key); + } +}