Re: [PATCH] net: tun: Fix use-after-free in tun_detach()

From: Eric Dumazet
Date: Sat Nov 19 2022 - 13:31:56 EST


On Fri, Nov 18, 2022 at 11:56 PM Shigeru Yoshida <syoshida@xxxxxxxxxx> wrote:
>
> syzbot reported use-after-free in tun_detach() [1]. This causes call
> trace like below:
>
> ==================================================================
> BUG: KASAN: use-after-free in notifier_call_chain+0x1da/0x1e0
> ...
> Call Trace:

Please include a symbolic stack trace, I think syzbot has them.

> <TASK>
> dump_stack_lvl+0x100/0x178
> print_report+0x167/0x470
> ? __virt_addr_valid+0x5e/0x2d0
> ? __phys_addr+0xc6/0x140
> ? notifier_call_chain+0x1da/0x1e0
> ? notifier_call_chain+0x1da/0x1e0
> kasan_report+0xbf/0x1e0
> ? notifier_call_chain+0x1da/0x1e0
> notifier_call_chain+0x1da/0x1e0
> call_netdevice_notifiers_info+0x83/0x130
> netdev_run_todo+0xc33/0x11b0
> ? generic_xdp_install+0x490/0x490
> ? __tun_detach+0x1500/0x1500
> tun_chr_close+0xe2/0x190
> __fput+0x26a/0xa40
> task_work_run+0x14d/0x240
> ? task_work_cancel+0x30/0x30
> do_exit+0xb31/0x2a40
> ? reacquire_held_locks+0x4a0/0x4a0
> ? do_raw_spin_lock+0x12e/0x2b0
> ? mm_update_next_owner+0x7c0/0x7c0
> ? rwlock_bug.part.0+0x90/0x90
> ? lockdep_hardirqs_on_prepare+0x17f/0x410
> do_group_exit+0xd4/0x2a0
> __x64_sys_exit_group+0x3e/0x50
> do_syscall_64+0x38/0xb0
> entry_SYSCALL_64_after_hwframe+0x63/0xcd
>
> The cause of the issue is that sock_put() from __tun_detach() drops
> last reference count for struct net, and then notifier_call_chain()
> from netdev_state_change() accesses that struct net.
>
> This patch fixes the issue by calling sock_put() from tun_detach()
> after all necessary accesses for the struct net has done.
>
> Link: https://syzkaller.appspot.com/bug?id=96eb7f1ce75ef933697f24eeab928c4a716edefe [1]
> Signed-off-by: Shigeru Yoshida <syoshida@xxxxxxxxxx>

Please add a Fixes: tag, once you identified which commit added this bug.

> ---
> drivers/net/tun.c | 6 +++++-
> 1 file changed, 5 insertions(+), 1 deletion(-)
>
> diff --git a/drivers/net/tun.c b/drivers/net/tun.c
> index 7a3ab3427369..ce9fcf4c8ef4 100644
> --- a/drivers/net/tun.c
> +++ b/drivers/net/tun.c
> @@ -686,7 +686,6 @@ static void __tun_detach(struct tun_file *tfile, bool clean)
> if (tun)
> xdp_rxq_info_unreg(&tfile->xdp_rxq);
> ptr_ring_cleanup(&tfile->tx_ring, tun_ptr_free);
> - sock_put(&tfile->sk);
> }
> }
>
> @@ -702,6 +701,11 @@ static void tun_detach(struct tun_file *tfile, bool clean)
> if (dev)
> netdev_state_change(dev);
> rtnl_unlock();
> +
> + if (clean) {
> + synchronize_rcu();
> + sock_put(&tfile->sk);
> + }
> }
>
> static void tun_detach_all(struct net_device *dev)
> --
> 2.38.1
>