[PATCH] security:trusted_tpm2: Fix memory leak in tpm2_key_encode()

Jarkko Sakkinen jarkko at kernel.org
Wed Dec 29 00:08:59 UTC 2021


KEYS: trusted: Fix memory leak in tpm2_key_encode()

On Tue, Dec 21, 2021 at 04:54:04PM +0800, Jianglei Nie wrote:
> Line 36 (#1) allocates a memory chunk for scratch by kmalloc(), but
> it is never freed through the function, which will lead to a memory
> leak.
> 
> We should kfree() scratch before the function returns (#2, #3 and #4).
> 
> 31 static int tpm2_key_encode(struct trusted_key_payload *payload,
> 32			   struct trusted_key_options *options,
> 33			   u8 *src, u32 len)
> 34 {
> 36	u8 *scratch = kmalloc(SCRATCH_SIZE, GFP_KERNEL);
>       	// #1: kmalloc space
> 50	if (!scratch)
> 51		return -ENOMEM;
> 
> 56	if (options->blobauth_len == 0) {
> 60		if (WARN(IS_ERR(w), "BUG: Boolean failed to encode"))
> 61			return PTR_ERR(w); // #2: missing kfree
> 63	}
> 
> 71	if (WARN(work - scratch + pub_len + priv_len + 14 > SCRATCH_SIZE,
> 72		 "BUG: scratch buffer is too small"))
> 73		return -EINVAL; // #3: missing kfree
> 
>   	// #4: missing kfree: scratch is never used afterwards.
> 82	if (WARN(IS_ERR(work1), "BUG: ASN.1 encoder failed"))
> 83		return PTR_ERR(work1);
> 
> 85	return work1 - payload->blob;
> 86 }
> 
> Signed-off-by: Jianglei Nie <niejianglei2021 at 163.com>

Please write a proper commit message and not just dump tool output. You
are completely lacking analysis of what the heck you are doing.

E.g. you could just:

"The internal buffer in tpm2_key_encode() is not freed, which leads to a
memory leak. Handle those cases with kfree()."

/Jarkko



More information about the Linux-security-module-archive mailing list