Saturday, August 10, 2013

Very Bad Password Advice

This post on How-To-Geek about generating passwords from the command line advocates generating passwords from the current date and time.


The first command they give is (note double fail: base64-encoding hex):
 date +%s | sha256sum | base64 | head -c 32 ; echo  
They do provide a command that gives a good alphanumeric password:
 tr -cd '[:alnum:]' < /dev/urandom | fold -w30 | head -n1  
 However, they also mention this one:
 date | md5sum  
 About the above command, they say, "I'm sure that some people will complain that it’s not as random as some of the other options, but honestly, it’s random enough if you’re going to be using the whole thing." That is absolutely wrong and demonstrates a complete lack of understanding what a hash function is.

Lessons Learned:
  • Hashing does not add randomness. The output of a hash is as random as its input.
  • Use a cryptographically-secure random number generator to generate passwords. 

Monday, July 29, 2013

PHP Documentation Woes

This bit of php documentation has some interesting code:

 <?php  
 $passphrase = 'My secret';  
   
 /* Turn a human readable passphrase  
  * into a reproducable iv/key pair  
  */  
 $iv = substr(md5('iv'.$passphrase, true), 0, 8);  
 $key = substr(md5('pass1'.$passphrase, true) .   
         md5('pass2'.$passphrase, true), 0, 24);  
 $opts = array('iv'=>$iv, 'key'=>$key);  
   
 $fp = fopen('secret-file.enc', 'wb');  
 stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);  
 fwrite($fp, 'Secret secret secret data');  
 fclose($fp);  
 ?>  

3DES takes a 192-bit key (actually 168), so the first two keys are taken from the first MD5 and the third key is taken from the second MD5. I have a strong suspicion that that alignment introduces some kind of vulnerability, but I can't quite put my finger on it. If anyone knows, please leave a comment.

This tweet says it all:

Lessons Learned:
  • Don't use MD5 to derive keys from passwords. Use PBKDF2.
  • Use a random, unique IV. Don't derive it from the password.
  • Documentation will be used by many people. It's worth hiring a cryptographer to check it.

Thursday, July 25, 2013

Password Hashing Fail

Here's a bit of password hashing fail.

I'm not sure if it will win the Password Hashing Competition, but it certainly is novel. I really like how, after it goes through all of that sha1/md5/rot13 "encryption", it saves the plaintext to the database. Oh, and if it weren't for a misplaced '}', it would accept any password in the database, not just the one for your account. It's also vulnerable to SQL injection (pointed out by an Anonymous commenter).

Hashing a password:
 public function encryptData($string)
 {  
   $stringORG = $string;  
   $string = str_rot13($string);  
   $string = md5($string);  
   $string = substr($string, 5, 15);  
   $string = sha1(SALT . $string);  
   $string = md5($string);  
   $string = sha1(SALT . $string);  
   $string = str_rot13($string);  
   $string = substr($string, 5, 15);  
   $string = md5(SALT . $string);  
   mysql_query("INSERT INTO `encryptions` (`encvalue`, `realvalue`) VALUES ('".$string."', '".$stringORG."');");  
   return $string;  
   }  
Testing a password:
public function tryEncryption($tried)
{  
  $query = mysql_query('SELECT * FROM encryptions');  
  while($row = mysql_fetch_assoc($query))  
  {  
    $encVal = $row['encvalue'];  
    $actVal = $row['realvalue'];  
  }  
    $actTried = $tried;  
    $tried = str_rot13($tried);  
    $tried = md5($tried);  
    $tried = substr($tried, 5, 15);  
    $tried = sha1(SALT . $tried);  
    $tried = md5($tried);  
    $tried = sha1(SALT . $tried);  
    $tried = str_rot13($tried);  
    $tried = substr($tried, 5, 15);  
    $tried = md5(SALT . $tried);  
    if($encVal==$tried)  
    {  
      if($actVal==$actTried)  
      {  
        return true;  
      }  
    }  
}  

Lessons Learned:
  • When you encrypt something, make sure the plaintext is safely destroyed.
  • Hash passwords properly.
  • Write unit tests for your code.

Monday, July 15, 2013

PHP-Encrypt-Decrypt: Binary vs. Hex

This PHP script makes an interesting mistake. It attempts to derive a key from a password using md5, but it uses the hex-encoded MD5 output as the key, not the raw binary output. The hexadecimal string is passed to the mcrypt_encrypt() function, which interprets the 32-character hex string as a 256-bit key, even though it's really only 128 bits.

The author's intention was probably to use AES. In PHP, MCRYPT_RIJNDAEL_256 refers to the 256-bit block variant of Rijndael, not the 128-bit block version that was selected for AES. The key size of 128, 192, or 256 bits is determined by the length of the key parameter.

 $SECRET_KEY = 'YOUR SECRET KEY';  
 // ...  
 $encrypted_i = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($SECRET_KEY), $value, MCRYPT_MODE_CBC, md5(md5($SECRET_KEY))));  

Lessons Learned:
  • Specify crypto parameters in the right format. Look at the output of the functions you use to make sure it's in the format you expect.
  • Use key stretching (PBKDF2) to derive a key from a password, not MD5.
  • Generate a random IV at the time of encryption. Do not derive it from the key.
  • Use test vectors to ensure you are using the correct primitives.

Saturday, July 13, 2013

PHP-Security-Library: $ciphertext->key

It's generally not a good idea to store the key in your ciphertext object. If you do, naive users are going to think it's ok to store the key with the ciphertext, and advanced users are going to serialize() it all by accident.

 use \PSL\Encrypter;  
 $confidentalText = 'I am using PSL';  
 $cipherText = Encrypter::encrypt(MCRYPT_RIJNDAEL_256, $confidentalText);  
 // $cipherText is an instance of \PSL\CipherText.  
 // To extract, do something like this:  
 $key = $cipherText->key;  
 $plainText = Encrypter::decrypt($cipherText, $key);  
 // $plainText is now same as $confidentalText.  

Lessons Learned:
  • Do not store the key in the ciphertext.
  • Design APIs so that it is as difficult as possible to use them incorrectly.

Friday, July 12, 2013

Password Generators: Math.random()

When you do a Google search for "password generator", you find a lot of JavaScript-based password generators. Unfortunately, all of the high-ranking ones use Math.random(), which is a pseudorandom number generator unfit for cryptographic use. In Firefox and other browsers, Math.random() is seeded with the time and provides at most 41 bits of entropy. The JavaScript-based generators don't support SSL/TLS connections, either.

In this one, the programmer attempted to generate an integer in the range [0, 25] by multiplying Math.random() by 25 then rounding to the nearest integer. This creates a bias away from 0 and 25. To get a 0 or 25, the unrounded value must fall in the range [0, 0.5) or [24.5, 25] respectively. The width of these ranges is 0.5. For all other results (1 through 24), the width of the range is 1.0. For example, to get a 6, the unrounded value can fall anywhere in [5.5, 6.5).

 for (var i = 0; i < lengthOfPassword; i++) {  
      capitalise = Math.round(Math.random() * 1);  
      if (capitalise === 0) {  
           StrongPasswordArray[i] = theLetters.charAt(Math.round(Math.random() * 25)).toUpperCase();  
      }  
      else {  
           StrongPasswordArray[i] = theLetters.charAt(Math.round(Math.random() * 25));  
      }  
 }  

Lessons Learned:
  • Use a cryptographically secure random number generator when generating a key, password, or initialization vector.
  • Don't use floating point numbers for cryptography.
  • Test the output of your random number generator with tools like diehard.
  • Enforce an SSL/TLS connection if client-side scripts deal with sensitive information.

Thursday, July 11, 2013

osTicket: Fail Open, Fail Often

osTicket is (according to them) the "world's most popular open source customer support ticket system." They use one of the worst-designed encryption functions I've ever seen.

First of all, they're trying to use symmetric encryption to secure passwords. They should be using a slow hash (pbkdf2, bcrypt, scrypt) with salt. Edit: Actually, they have to be able to decrypt passwords, because they are used in POP3/IMAP connections. They have to be able to provide the plaintext passwords to a third party, not just verify them. Users' passwords are hashed.

Second, the encryption function fails open. If the mcrypt library is missing, encryption does nothing, and passwords are stored in the database in plain text. It does log a warning message, but who's going to see that?

I can almost feel the programmer's frustration, trying all possible combinations of trim(), IVs, and cipher modes to get the damn thing to decrypt properly. They tried to generate a random IV at encryption time, but did not realize they need to encode it with the ciphertext so it can be given to mcrypt_decrypt(). Instead, they use ECB mode, which ignores the IV. They even generate a random IV in the decryption function!

 function encrypt($text, $salt) {  
   
   //if mcrypt extension is not installed--simply return unencryted text and log a warning.  
   if(!function_exists('mcrypt_encrypt') || !function_exists('mcrypt_decrypt')) {  
     $msg='Cryptography extension mcrypt is not enabled or installed. IMAP/POP passwords are being stored as plain text in database.';  
     Sys::log(LOG_WARN,'mcrypt missing',$msg);  
     return $text;  
   }  
   
   return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,$salt, $text, MCRYPT_MODE_ECB,  
             mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));  
 }  
   
 function decrypt($text, $salt) {  
   if(!function_exists('mcrypt_encrypt') || !function_exists('mcrypt_decrypt'))  
     return $text;  
   
   return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB,  
           mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));  
 }  

The "salt" (which is really the encryption key) is "randomly" generated at install time and stored in a source code file. If that happens to be missing, they use the md5 hash of the admin's email address.

 # This is to support old installations. with no secret salt.  
 if(!defined('SECRET_SALT')) define('SECRET_SALT',md5(TABLE_PREFIX.ADMIN_EMAIL));  

Here's how they generate the "salt." I shouldn't need to explain why this is wrong.

 function randCode($len=8) {  
   return substr(strtoupper(base_convert(microtime(),10,16)),0,$len);  
 }  
 $configFile= str_replace('%CONFIG-SIRI',Misc::randcode(32),$configFile);

Lessons Learned:
  • Fail safe. If your encryption library isn't available, fail hard, don't just return the plaintext.
  • Use a cryptographically secure random number generator to generate secrets.
  • Protect passwords by hashing them.