Skip to content

Commit 646b980

Browse files
Avoid memory leak associated with symmetric init (#376)
The `NativeInterface.CIPHER_init` method initializes a given context such that it is ready to perform encryption and decryption for a given Cipher. As part of the initialization method a `ockCipher->cached_context` can be optionally created in addition to the context being used. While allocating the `ockCipher->cached_context` the logic did not account for any previously created contexts that were previously stored in the `ockCipher->cached_context` location. This caused a leak of context objects for each initialization done on objects that already contained a context. Additional error checking was done for the calls to `ICC_EVP_CIPHER_CTX_new` and `ICC_EVP_CIPHER_CTX_copy` to ensure that the method worked as expected. Signed-off-by: Jason Katonica <katonica@us.ibm.com>
1 parent 30a6e8e commit 646b980

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

src/main/native/SymmetricCipher.c

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,14 +211,24 @@ JNIEXPORT jlong JNICALL Java_com_ibm_crypto_plus_provider_ock_NativeInterface_CI
211211

212212
if( rc == ICC_OSSL_SUCCESS ) {
213213
rc = ICC_EVP_CIPHER_CTX_set_padding(ockCtx, ockCipher->cipherCtx, ockPadType);
214-
if(ockCipher->copy_context == 0) {
215-
ockCipher->cached_context = ICC_EVP_CIPHER_CTX_new(ockCtx);
216-
ICC_EVP_CIPHER_CTX_copy(ockCtx, ockCipher->cached_context, ockCipher->cipherCtx);
217-
}
218214
if( rc != ICC_OSSL_SUCCESS ) {
219215
ockCheckStatus(ockCtx);
220216
throwOCKException(env, 0, "ICC_EVP_set_padding failed");
221217
}
218+
if (0 == ockCipher->copy_context) {
219+
if (NULL == ockCipher->cached_context) {
220+
ockCipher->cached_context = ICC_EVP_CIPHER_CTX_new(ockCtx);
221+
}
222+
if (NULL == ockCipher->cached_context) {
223+
ockCheckStatus(ockCtx);
224+
throwOCKException(env, 0, "ICC_EVP_CIPHER_CTX_new failed for CIPHER_init cached context");
225+
}
226+
rc = ICC_EVP_CIPHER_CTX_copy(ockCtx, ockCipher->cached_context, ockCipher->cipherCtx);
227+
if( rc != ICC_OSSL_SUCCESS ) {
228+
ockCheckStatus(ockCtx);
229+
throwOCKException(env, 0, "ICC_EVP_CIPHER_CTX_copy failed for CIPHER_init");
230+
}
231+
}
222232
}
223233
}
224234
}

0 commit comments

Comments
 (0)