chore(app/device_assignment): only free mbed TLS crypto ctx if inited

Signed-off-by: Mate Toth-Pal <mate.toth-pal@arm.com>
Change-Id: I840e26dfca9acd97e5a10cbe8553c9daa229ce96
diff --git a/app/device_assignment/el0_app/src/dev_assign_el0_app.c b/app/device_assignment/el0_app/src/dev_assign_el0_app.c
index ef44b68..5a26820 100644
--- a/app/device_assignment/el0_app/src/dev_assign_el0_app.c
+++ b/app/device_assignment/el0_app/src/dev_assign_el0_app.c
@@ -421,11 +421,15 @@
 	libspdm_data_parameter_t parameter;
 	void *data_ptr;
 
-	if ((info->key_sig_algo == RMI_SIGNATURE_ALGORITHM_ECDSA_P256) ||
-	    (info->key_sig_algo == RMI_SIGNATURE_ALGORITHM_ECDSA_P384)) {
-		mbedtls_ecdh_free(&info->pk_ctx.ecdh);
-	} else {
-		mbedtls_rsa_free(&info->pk_ctx.rsa);
+	if (info->pk_ctx.initialised) {
+		if ((info->key_sig_algo == RMI_SIGNATURE_ALGORITHM_ECDSA_P256) ||
+		    (info->key_sig_algo == RMI_SIGNATURE_ALGORITHM_ECDSA_P384)) {
+			mbedtls_ecdh_free(&info->pk_ctx.ecdh);
+		} else {
+			assert(info->key_sig_algo == RMI_SIGNATURE_ALGORITHM_RSASSA_3072);
+			mbedtls_rsa_free(&info->pk_ctx.rsa);
+		}
+		info->pk_ctx.initialised = false;
 	}
 
 	/* Set LIBSPDM_DATA_PEER_USED_CERT_CHAIN_PUBLIC_KEY in spdm connection */
@@ -529,6 +533,7 @@
 	}
 
 	info->key_sig_algo = (uint32_t)key_sig_algo;
+	info->pk_ctx.initialised = true;
 
 	/* Set LIBSPDM_DATA_PEER_USED_CERT_CHAIN_PUBLIC_KEY in spdm connection */
 	(void)memset(&parameter, 0, sizeof(parameter));
@@ -692,6 +697,7 @@
 		info->ide_sid = params->ide_sid;
 	}
 	info->spdm_cert_chain_digest_length = 0;
+	info->pk_ctx.initialised = false;
 
 	info->psa_hash_algo = rmi_to_psa_hash_algo(params->rmi_hash_algo);
 
diff --git a/app/device_assignment/el0_app/src/dev_assign_private.h b/app/device_assignment/el0_app/src/dev_assign_private.h
index 93c0dd0..4afbcb5 100644
--- a/app/device_assignment/el0_app/src/dev_assign_private.h
+++ b/app/device_assignment/el0_app/src/dev_assign_private.h
@@ -249,9 +249,12 @@
 
 	/* Public key context */
 	uint32_t key_sig_algo;
-	union {
-		mbedtls_ecdh_context ecdh;
-		mbedtls_rsa_context rsa;
+	struct {
+		union{
+			mbedtls_ecdh_context ecdh;
+			mbedtls_rsa_context rsa;
+		};
+		bool initialised;
 	} pk_ctx;
 
 	/* Exit and Entry args for dev_communicate cmds */