ektrah/libsodium-core

Wrong additionalData precondition in crypto_aead_xchacha20poly1305_ietf_encrypt

Closed this issue · 0 comments

I'm currently trying to decrypt some data that was originally encrypted via the typescript libsodium wrapper.
The message is encrypted with xchacha and some data in the additionalData field, encrypting with libsodium-core fails because of the following assertion:

https://github.com/tabrath/libsodium-core/blob/73bf33294cd352853fa1f08813187f722b270eae/src/Sodium.Core/SecretAeadXChaCha20Poly1305.cs#L112-L114

Unfortunately I can't really say I'm that deep into security/encryption, but here's what I found out:

  • Neither in the typescript/javascript wappers nor in the libsodium source is the additional data capped at 16 bytes
  • The documentation also doesn't limit the length of the additional parameter field
  • If I simply take the libsodium-core code and remove that check then nothing breaks and he method actually returns my desired value

Testcase

	var key = Convert.FromBase64String("GVyHGrcNV5XkhUB9sj72YTpagFLpAEZNK8V/SalmCqY=");
	var nonce = Convert.FromBase64String("A8iAcKWPwNTsVWmfF3fTMClvy1qt+GOF");
	var ciphertext = Convert.FromBase64String("Tgr1Dvxi9TnCpnTjDWNc/DkRqzHZzL7p4uWvUvX1KgHyaDMjCLn3QCIzyffocPud713mjz8d0NxOntwgtKE0LjpXVQpRO9MgpXnOaiMvdQk=");
	var encoded_authenticated_data = Encoding.UTF8.GetBytes("eyJrcCI6eyJpZGVudGlmaWVyIjoidHJhc2grMDA0QG1pa2VzY2hlci5kZSIsInB3X25vbmNlIjoiOWQzZTE3OTRhOGUxZjY2ZjBiMjNhZmZkZWY4MmRjZWE1YmJhM2NiYjIwYzkyNzgxYmMwMjI0YWU2OTA5YmUyMSIsInZlcnNpb24iOiIwMDQiLCJvcmlnaW5hdGlvbiI6InJlZ2lzdHJhdGlvbiIsImNyZWF0ZWQiOiIxNjA5NTIzNzU2MjkwIn0sInUiOiI1YzhhNWQ3Ny01NzgwLTRkODctYTg0Yy1kMzUxMmQ0NDE5NDMiLCJ2IjoiMDA0In0=");
	
	var plaintext = SecretAeadXChaCha20Poly1305.Decrypt(ciphertext, nonce, key, encoded_authenticated_data);
	
        // Decrypt throws AdditionalDataOutOfRangeException:
        // Specified argument was out of the range of valid values. (Parameter 'additionalData must be between 0 and 16 bytes in length.'

	Debug.Assert(Encoding.UTF8.GetString(plaintext) == "047db3c4e3c6a812ecd347cb10078d26525094c1d2cecfc3ddff866234e2151b")

Solution

It seems simply removing the additionalData.Length check in SecretAeadXChaCha20Poly1305.cs should fix all problems - if you want I can create a PR.
The check exists two times, once in the Encrypt (line 55-57) and once in the Decrypt (line 112-114) method