From 11031849ef821361fda9dd72605f323fefe99463 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Wed, 8 Feb 2023 07:55:50 -0800 Subject: [PATCH] Fix potential memory leak when attestation delegate is set (#24906) --- .../java/DeviceAttestationDelegateBridge.cpp | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp index 50020b93a603b1..b201a073661b9a 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.cpp +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -79,6 +79,9 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( VerifyOrReturn(deviceAttestationDelegateCls != nullptr, ChipLogError(Controller, "Could not find device attestation delegate class.")); + // Auto delete deviceAttestationDelegateCls object when exit from the local scope + JniClass deviceAttestationDelegateJniCls(deviceAttestationDelegateCls); + if (env->IsInstanceOf(mDeviceAttestationDelegate, deviceAttestationDelegateCls)) { jmethodID onDeviceAttestationCompletedMethod; @@ -87,10 +90,17 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( &onDeviceAttestationCompletedMethod); VerifyOrReturn(onDeviceAttestationCompletedMethod != nullptr, ChipLogError(Controller, "Could not find deviceAttestation completed method")); - jobject javaAttestationInfo; - CHIP_ERROR err = N2J_AttestationInfo(env, info, javaAttestationInfo); - VerifyOrReturn(err == CHIP_NO_ERROR, - ChipLogError(Controller, "Failed to create AttestationInfo, error: %s", err.AsString())); + + jobject javaAttestationInfo = nullptr; + + // Don't need to pass attestationInfo for additional verification when attestation failed. + if (attestationResult == chip::Credentials::AttestationVerificationResult::kSuccess) + { + CHIP_ERROR err = N2J_AttestationInfo(env, info, javaAttestationInfo); + VerifyOrReturn(err == CHIP_NO_ERROR, + ChipLogError(Controller, "Failed to create AttestationInfo, error: %s", err.AsString())); + } + env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationCompletedMethod, reinterpret_cast(device), javaAttestationInfo, static_cast(attestationResult)); }