Subject: Re: [PATCH v2 net 2/2] af_packet: Fix warning of fortified memcpy() in packet_getname().

From: Kuniyuki Iwashima <[email-masked]>
Date: Thu, 20 Jul 2023 10:02:36 -0700

From: Kees Cook <[email-masked]>
Date: Thu, 20 Jul 2023 08:04:53 -0700
> On Wed, Jul 19, 2023 at 05:44:10PM -0700, Kuniyuki Iwashima wrote:
> > syzkaller found a warning in packet_getname() [0], where we try to
> > copy 16 bytes to sockaddr_ll.sll_addr[8].
> > 
> > Some devices (ip6gre, vti6, ip6tnl) have 16 bytes address expressed
> > by struct in6_addr.  Also, Infiniband has 32 bytes as MAX_ADDR_LEN.
> > 
> > The write seems to overflow, but actually not since we use struct
> > sockaddr_storage defined in __sys_getsockname() and its size is 128
> > (_K_SS_MAXSIZE) bytes.  Thus, we have sufficient room after sll_addr[]
> > as __data[].
> 
> Ah, so the issue here is that the UAPI for sll_addr is lying about its
> size. I think a better fix here is to fix the structure (without
> breaking UAPI sizes or names):

Doesn't it forcify sll_addr here ?

> 
> diff --git a/include/uapi/linux/if_packet.h b/include/uapi/linux/if_packet.h
> index 9efc42382fdb..4d0ad22f83b5 100644
> --- a/include/uapi/linux/if_packet.h
> +++ b/include/uapi/linux/if_packet.h
> @@ -18,7 +18,11 @@ struct sockaddr_ll {
>  	unsigned short	sll_hatype;
>  	unsigned char	sll_pkttype;
>  	unsigned char	sll_halen;
> -	unsigned char	sll_addr[8];
> +	union {
> +		unsigned char	sll_addr[8];
> +		/* Actual length is in sll_halen. */
> +		__DECLARE_FLEX_ARRAY(unsigned char, sll_addr_flex);
> +	};
>  };
>  
>  /* Packet types */
> diff --git a/net/packet/af_packet.c b/net/packet/af_packet.c
> index 85ff90a03b0c..8e3ddec4c3d5 100644
> --- a/net/packet/af_packet.c
> +++ b/net/packet/af_packet.c
> @@ -3601,7 +3601,7 @@ static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
>  	if (dev) {
>  		sll->sll_hatype = dev->type;
>  		sll->sll_halen = dev->addr_len;
> -		memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
> +		memcpy(sll->sll_addr_flex, dev->dev_addr, dev->addr_len);
>  	} else {
>  		sll->sll_hatype = 0;	/* Bad: we have no ARPHRD_UNSPEC */
>  		sll->sll_halen = 0;
> 
> We can't rename sll_data nor change it's size, as userspace uses it
> pretty extensively:
> https://codesearch.debian.net/search?q=sizeof.*sll_addr&literal=0
> 
> -- 
> Kees Cook