Skip to content

Commit e91517c

Browse files
gr8manmichalsn
andauthored
fix: normalize SodiumHandler params and padding failures (#10321)
* fix: SodiumHandler encrypt/decrypt key handling bugs * chore: clean up redundant comments * test: use Reflection to access protected property in SodiumHandlerTest * test: resolve ReflectionException * Update tests/system/Encryption/Handlers/SodiumHandlerTest.php Co-authored-by: Michal Sniatala <michal@sniatala.pl> * fix: address PR review comments on SodiumHandler * style: apply cs-fix to SodiumHandler * fix: import SodiumException to resolve PHPStan error * test: update expected exception for mismatched block size * style: remove unused SodiumException import in test * Update user_guide_src/source/changelogs/v4.7.4.rst Co-authored-by: Michal Sniatala <michal@sniatala.pl> --------- Co-authored-by: Michal Sniatala <michal@sniatala.pl>
1 parent 19cae6e commit e91517c

3 files changed

Lines changed: 86 additions & 38 deletions

File tree

‎system/Encryption/Handlers/SodiumHandler.php‎

Lines changed: 32 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use CodeIgniter\Encryption\Exceptions\EncryptionException;
1717
use SensitiveParameter;
18+
use SodiumException;
1819

1920
/**
2021
* SodiumHandler uses libsodium in encryption.
@@ -43,34 +44,31 @@ class SodiumHandler extends BaseHandler
4344
*/
4445
public function encrypt(#[SensitiveParameter] $data, #[SensitiveParameter] $params = null)
4546
{
46-
// Allow key override
47-
$key = $params !== null
48-
? (is_array($params) && isset($params['key']) ? $params['key'] : $params)
49-
: $this->key;
50-
51-
// Allow blockSize override
52-
$blockSize = (is_array($params) && isset($params['blockSize']))
53-
? $params['blockSize']
54-
: $this->blockSize;
47+
$key = $this->key;
48+
$blockSize = $this->blockSize;
49+
50+
if ($params !== null) {
51+
if (is_array($params)) {
52+
$key = $params['key'] ?? $key;
53+
$blockSize = $params['blockSize'] ?? $blockSize;
54+
} else {
55+
$key = $params;
56+
}
57+
}
5558

56-
if (empty($key)) {
59+
if (empty($key) || strlen((string) $key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
5760
throw EncryptionException::forNeedsStarterKey();
5861
}
5962

60-
// create a nonce for this operation
61-
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes
62-
63-
// add padding before we encrypt the data
6463
if ($blockSize <= 0) {
6564
throw EncryptionException::forEncryptionFailed();
6665
}
6766

68-
$data = sodium_pad($data, $blockSize);
67+
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
68+
$data = sodium_pad($data, $blockSize);
6969

70-
// encrypt message and combine with nonce
7170
$ciphertext = $nonce . sodium_crypto_secretbox($data, $nonce, $key);
7271

73-
// cleanup buffers
7472
sodium_memzero($data);
7573
sodium_memzero($key);
7674

@@ -82,45 +80,41 @@ public function encrypt(#[SensitiveParameter] $data, #[SensitiveParameter] $para
8280
*/
8381
public function decrypt($data, #[SensitiveParameter] $params = null)
8482
{
85-
// Allow key override
86-
$key = $params !== null
87-
? (is_array($params) && isset($params['key']) ? $params['key'] : $params)
88-
: $this->key;
89-
90-
// Allow blockSize override
91-
$blockSize = (is_array($params) && isset($params['blockSize']))
92-
? $params['blockSize']
93-
: $this->blockSize;
83+
$key = $this->key;
84+
$blockSize = $this->blockSize;
85+
86+
if ($params !== null) {
87+
if (is_array($params)) {
88+
$key = $params['key'] ?? $key;
89+
$blockSize = $params['blockSize'] ?? $blockSize;
90+
} else {
91+
$key = $params;
92+
}
93+
}
9494

95-
if (empty($key)) {
95+
if (empty($key) || strlen((string) $key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
9696
throw EncryptionException::forNeedsStarterKey();
9797
}
9898

9999
if (mb_strlen($data, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
100-
// message was truncated
101100
throw EncryptionException::forAuthenticationFailed();
102101
}
103102

104-
// Extract info from encrypted data
105103
$nonce = self::substr($data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
106104
$ciphertext = self::substr($data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
107105

108-
// decrypt data
109106
$data = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
110107

111-
if ($data === false) {
112-
// message was tampered in transit
113-
throw EncryptionException::forAuthenticationFailed(); // @codeCoverageIgnore
108+
if ($data === false || $blockSize <= 0) {
109+
throw EncryptionException::forAuthenticationFailed();
114110
}
115111

116-
// remove extra padding during encryption
117-
if ($blockSize <= 0) {
112+
try {
113+
$data = sodium_unpad($data, $blockSize);
114+
} catch (SodiumException) {
118115
throw EncryptionException::forAuthenticationFailed();
119116
}
120117

121-
$data = sodium_unpad($data, $blockSize);
122-
123-
// cleanup buffers
124118
sodium_memzero($ciphertext);
125119
sodium_memzero($key);
126120

‎tests/system/Encryption/Handlers/SodiumHandlerTest.php‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,4 +151,57 @@ public function testInternalKeyNotModifiedByParams(): void
151151

152152
$this->assertSame($message, $encrypter->decrypt($encoded, ['key' => $differentKey]));
153153
}
154+
155+
public function testNullKeyOverrideFallsBackToInstanceKey(): void
156+
{
157+
/** @var SodiumHandler $encrypter */
158+
$encrypter = $this->encryption->initialize($this->config);
159+
160+
$ciphertext = $encrypter->encrypt('message', ['key' => null]);
161+
162+
$this->assertSame('message', $encrypter->decrypt($ciphertext, ['key' => null]));
163+
}
164+
165+
public function testInvalidKeyLengthThrowsEncryptionException(): void
166+
{
167+
$this->expectException(EncryptionException::class);
168+
/** @var SodiumHandler $encrypter */
169+
$encrypter = $this->encryption->initialize($this->config);
170+
171+
$encrypter->encrypt('message', str_repeat('a', 31));
172+
}
173+
174+
public function testMismatchedBlockSizeThrowsEncryptionException(): void
175+
{
176+
$this->expectException(EncryptionException::class);
177+
/** @var SodiumHandler $encrypter */
178+
$encrypter = $this->encryption->initialize($this->config);
179+
180+
$ciphertext = $encrypter->encrypt('message', ['blockSize' => 16]);
181+
182+
$encrypter->decrypt($ciphertext, ['blockSize' => 32]);
183+
}
184+
185+
public function testDecryptTamperedMessageThrowsException(): void
186+
{
187+
$this->expectException(EncryptionException::class);
188+
$encrypter = $this->encryption->initialize($this->config);
189+
190+
$ciphertext = $encrypter->encrypt('message');
191+
192+
$ciphertext[0] = $ciphertext[0] === 'a' ? 'b' : 'a';
193+
194+
$encrypter->decrypt($ciphertext);
195+
}
196+
197+
public function testOverrideKeyAsStringWorks(): void
198+
{
199+
$encrypter = $this->encryption->initialize($this->config);
200+
$newKey = sodium_crypto_secretbox_keygen();
201+
202+
$ciphertext = $encrypter->encrypt('message', $newKey);
203+
$decrypted = $encrypter->decrypt($ciphertext, $newKey);
204+
205+
$this->assertSame('message', $decrypted);
206+
}
154207
}

‎user_guide_src/source/changelogs/v4.7.4.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ Bugs Fixed
3737
- **Commands:** Fixed a bug where ``spark lang:find`` treated translation keys already provided by the framework or another namespace (such as ``Errors.*`` in ``system/Language``) as new, listing them under ``--show-new`` and writing untranslated placeholders into ``app/Language`` that overrode the existing translations.
3838
- **Config:** Fixed a bug where ``BaseService::injectMock`` did not apply ``strtolower`` consistently, causing inconsistent Service and Mock registration and resolution.
3939
- **Database:** Fixed a bug where ``updateBatch()`` could be called after Query Builder ``where()`` conditions, even though it's not supported. In this situation, now the ``DatabaseException`` is thrown.
40+
- **Encryption:** Fixed bugs in ``SodiumHandler`` where runtime ``blockSize`` overrides without ``key`` were handled incorrectly, invalid key lengths could leak native Sodium errors, and mismatched decrypt ``blockSize`` values could throw ``SodiumException`` instead of ``EncryptionException``.
4041
- **Filters:** Fixed a bug in ``InvalidChars`` filter where invalid UTF-8 or control characters in array keys were not checked.
4142
- **HTTP:** Fixed a bug where the User Agent library reported Safari's WebKit version instead of the browser version from the ``Version`` token.
4243
- **Model:** Fixed a bug in ``Model::objectToRawArray()`` where the ``$recursive`` parameter was ignored.

0 commit comments

Comments
 (0)