tty: Fix ->pgrp locking in tiocspgrp()

tiocspgrp() takes two tty_struct pointers: One to the tty that userspace
passed to ioctl() (`tty`) and one to the TTY being changed (`real_tty`).
These pointers are different when ioctl() is called with a master fd.

To properly lock real_tty->pgrp, we must take real_tty->ctrl_lock.

This bug makes it possible for racing ioctl(TIOCSPGRP, ...) calls on
both sides of a PTY pair to corrupt the refcount of `struct pid`,
leading to use-after-free errors.

Fixes: 47f86834bbd4 ("redo locking of tty->pgrp")
CC: stable@kernel.org
Signed-off-by: Jann Horn <jannh@google.com>
Reviewed-by: Jiri Slaby <jirislaby@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

authored by Jann Horn and committed by Greg Kroah-Hartman 54ffccbf 418baf2c

Changed files
+2 -2
drivers
+2 -2
drivers/tty/tty_jobctrl.c
··· 494 494 if (session_of_pgrp(pgrp) != task_session(current)) 495 495 goto out_unlock; 496 496 retval = 0; 497 - spin_lock_irq(&tty->ctrl_lock); 497 + spin_lock_irq(&real_tty->ctrl_lock); 498 498 put_pid(real_tty->pgrp); 499 499 real_tty->pgrp = get_pid(pgrp); 500 - spin_unlock_irq(&tty->ctrl_lock); 500 + spin_unlock_irq(&real_tty->ctrl_lock); 501 501 out_unlock: 502 502 rcu_read_unlock(); 503 503 return retval;