ninjaframework / ninja

Ninja is a full stack web framework for Java. Rock solid, fast and super productive.
http://www.ninjaframework.org
Apache License 2.0
1.91k stars 521 forks source link

Insecure Cookie Encryption due to usage of insecure mode of operation when doing AES cipher #759

Open JAckLosingHeart opened 3 months ago

JAckLosingHeart commented 3 months ago

Hi team,

There might be a potential security issue in ninja-core/src/main/java/ninja/utils/CookieEncryption.java (ninja-core 7.0.0 the latest version) that I want to report and check with you guys.

Security risk:

In the function encrypt(), when AES is specified as the cipher algorithm without any more settings, AES/ECB/PKCS5Padding is used by default image

image

However, ECB as a block cipher mode is not secure, encrypting each block independently without any IV. Patterns in the plaintext can be easily observed in the ciphertext if similar blocks are present, which is a significant security weakness In Ninja case the weakness could lead to leakage of sensitive information in session data when encryption mode is used

Proof Of Concept:

I will use the unit test case under src/test/java/ninja/utils/CookieEncryptionTest.java here as an example We got 16 'a's, 16 'b's, 16 'c's, and another 16 'b's in the end, which's 64 characters in total as a string to encrypt image

As said before we'll see the pattern in the ciphertext as well. Encrypt it and check the cipher text before Base64 encoding: image

image

As we can see, same plaintext block generates identical 16 bytes cipher text block

Recommendation:

Could specify cipher mode explicitly and consider using more secure cipher modes. Only for example which might not apply to this case:

SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key);

That's pretty much the security issue I found.