Gasol / pecl-nacl

NaCl PHP Extension
https://nacl.cr.yp.to/
Other
4 stars 2 forks source link

Not working #1

Open aletheia7 opened 11 years ago

aletheia7 commented 11 years ago

Any ideas why the following test code does not work?

<?php

nacl_crypto_box_keypair($bobpk, $bobsk, true);
nacl_crypto_box_keypair($alicepk, $alicesk, true);

$nonce = str_pad("", 24, "0123abc");
$plain = "one two three";

$cipher = nacl_crypto_box($plain, $nonce, $bobpk, $alicesk, true); // Use Bob's public key to send to Bob
// Fails because $alicepk and/or $bobpk are changed when these keys contains nulls (0x00).
// strncpy() is not binary safe. strncpy() is used in nacl_crytpo_box_open()
$plain_again = nacl_crypto_box_open($cipher, $nonce, $alicepk, $bobpk);

printf("%s %d\n%s %d\n%s %d\n%s %d\n"

    , $nonce
    , strlen($nonce)
    , $plain
    , strlen($plain)
    , bin2hex($cipher)
    , strlen($cipher)
    , $plain_again
    , strlen($plain_again)
);
?>
aletheia7 commented 11 years ago

Resolution

nacl_crypto_box_open() fails intermittently. The exact cause of the problem is the use of strncpy() in nacl_crypto_box() and nacl_crypto_box_open(). strncpy() is not binary safe. When strncpy() encounters a null (0x00) in a string, it stops copying characters. strncpy() is used in these two functions to copy the public_key and secret_key to an array. When the public_key and/or the secret_key contain 0x00 characters, the nacl_crypto_box_open() call will fail to decrypt the encrypted data from nacl_crypto_box() because the keys will be changed internally.

Problem 1

All strncpy() calls must be changed to memcpy(). memcpy is binary safe. There are 21 calls to strncpy() that need to be replaced.

Problem 2

There are numerous memory loss issues with the extension. I used the valgrind memory checker against the extension, and memory loss is occurring with every function call. The extension should not be used until it has been properly debugged with valgrind.

You may also be interested in this project: php-sodium. php-sodium uses libsodium. libsodium is a shared library version of NaCL ported to Linux, Mac, and Windows.