Wednesday, July 10, 2013

CodeIgniter: Encryption is Not Authentication

After encrypting a string, the CodeIgniter PHP framework applies this function to the ciphertext. The function is a shift cipher using a hash of the encryption key.

The comment says they are doing it "to protect against Man-in-the-middle attacks on CBC mode ciphers." I have no idea what that means. I can only guess that they're slightly aware of the fact that encryption is not authentication, and that attackers can modify a CBC mode ciphertext to decrypt the way they want.

 /**  
  * Adds permuted noise to the IV + encrypted data to protect  
  * against Man-in-the-middle attacks on CBC mode ciphers  
  * http://www.ciphersbyritter.com/GLOSSARY.HTM#IV  
  *  
  * @param     string  
  * @param     string  
  * @return     string  
  */  
 protected function _add_cipher_noise($data, $key)  
 {  
      $key = $this->hash($key);  
      $str = '';  
   
      for ($i = 0, $j = 0, $ld = strlen($data), $lk = strlen($key); $i < $ld; ++$i, ++$j)  
      {  
           if ($j >= $lk)  
           {  
                $j = 0;  
           }  
   
           $str .= chr((ord($data[$i]) + ord($key[$j])) % 256);  
      }  
     
   return $str;  
 }  

Lessons Learned:
  • If you need to detect malicious changes to ciphertexts, use HMAC over the IV and ciphertext, or an authenticating mode like OCB.
  • If you find a vulnerability, don't come up with your own way to solve it. Find out how cryptographers have already solved it, and do it the right way.

2 comments:

  1. See the ref. in the code comment, they're worried about an attacker who can control (or even predict) the IV being able to mess with the first block contents. Their fix for it is, however, uhh... novel.

    ReplyDelete
  2. Cool, guess this is now public. I might publish my proof-of-concepts sometime now. They recover keys for the mcrypt code in the presence of a decryption oracle, and recover keys always for the xor cipher garbage.

    ReplyDelete