Subject: Re: [PATCH v2 net] netlink: Use copy_to_user() for optval in netlink_getsockopt().

From: Jakub Kicinski <[email-masked]>
Date: Thu, 20 Apr 2023 20:33:24 -0700

On Thu, 20 Apr 2023 16:33:51 -0700 Kuniyuki Iwashima wrote:
> diff --git a/net/netlink/af_netlink.c b/net/netlink/af_netlink.c
> index f365dfdd672d..5c0d17b3984c 100644
> --- a/net/netlink/af_netlink.c
> +++ b/net/netlink/af_netlink.c
> @@ -1742,7 +1742,7 @@ static int netlink_getsockopt(struct socket *sock, int level, int optname,
>  {
>  	struct sock *sk = sock->sk;
>  	struct netlink_sock *nlk = nlk_sk(sk);
> -	int len, val, err;
> +	int len, val;
>  
>  	if (level != SOL_NETLINK)
>  		return -ENOPROTOOPT;
> @@ -1753,40 +1753,27 @@ static int netlink_getsockopt(struct socket *sock, int level, int optname,
>  		return -EINVAL;
>  
>  	switch (optname) {
> -	case NETLINK_PKTINFO:
> +	case NETLINK_LIST_MEMBERSHIPS:
> +		break;
> +	default:
>  		if (len < sizeof(int))
>  			return -EINVAL;
>  		len = sizeof(int);
> +	}

> -		err = 0;
>  		break;
>  	default:
> -		err = -ENOPROTOOPT;
> +		return -ENOPROTOOPT;
>  	}
> -	return err;
> +
> +	if (put_user(len, optlen) ||
> +	    copy_to_user(optval, &val, len))
> +		return -EFAULT;

Maybe this is a nit pick but we'd unnecessarily change the return value
to unknown opts when len < 4, from -ENOPROTOOPT to -EINVAL, right?

How about we do:

	unsigned int flag;

	flag = 0;
	switch (optname) {
	case NETLINK_PKTINFO:
		flag = NETLINK_F_RECV_PKTINFO;
 		break;
 	case NETLINK_BROADCAST_ERROR:
		flag = NETLINK_F_BROADCAST_SEND_ERROR;
		break;
	...
	case NETLINK_LIST_MEMBERSHIPS: {
	...
	default:
		return -ENOPROTOOPT;
	}

	if (flag) {
		if (len < sizeof(int))
			return -EINVAL;
		len = sizeof(int);
 		val = nlk->flags & flag ? 1 : 0;
		if (put_user(len, optlen) || 
		    copy_to_user(optval, &val, len))
			return -EFAULT;
		...
	}