Subject: Re: [PATCH v3] iproute2: prevent memory leak

From: Petr Machata <[email-masked]>
Date: Wed, 15 Nov 2023 11:23:28 +0100

heminhong <[email-masked]> writes:

> When the return value of rtnl_talk() is greater than
> or equal to 0, 'answer' will be allocated.
> The 'answer' should be free after using,
> otherwise it will cause memory leak.

The patch also frees the memory when rtnl_talk() returns < 0. In that
case the answer has not been initialized. You should probably initialize
the answer to NULL.

> Signed-off-by: heminhong <[email-masked]>
> ---
>  ip/link_gre.c    | 1 +
>  ip/link_gre6.c   | 1 +
>  ip/link_ip6tnl.c | 1 +
>  ip/link_iptnl.c  | 1 +
>  ip/link_vti.c    | 1 +
>  ip/link_vti6.c   | 1 +
>  6 files changed, 6 insertions(+)
>
> diff --git a/ip/link_gre.c b/ip/link_gre.c
> index 74a5b5e9..3d3fcbae 100644
> --- a/ip/link_gre.c
> +++ b/ip/link_gre.c
> @@ -113,6 +113,7 @@ static int gre_parse_opt(struct link_util *lu, int argc, char **argv,
>  get_failed:
>  			fprintf(stderr,
>  				"Failed to get existing tunnel info.\n");
> +			free(answer);
>  			return -1;
>  		}
>  

The context of this hunk is:

 	struct nlmsghdr *answer;
 
 	... answer untouched here ...
 
 		if (rtnl_talk(&rth, &req.n, &answer) < 0) {
 get_failed:
+			free(answer);
 			fprintf(stderr,
 				"Failed to get existing tunnel info.\n");
 			return -1;
 		}

If rtnl_talk() fails, answer is never initialized, so passing it to free
is invalid.