tty: pty: Fix race condition between release_one_tty and pty_write
authorSahara <keun-o.park@darkmatter.ae>
Mon, 11 Feb 2019 07:09:15 +0000 (11:09 +0400)
committerGreg Kroah-Hartman <gregkh@linuxfoundation.org>
Wed, 27 Mar 2019 16:28:23 +0000 (01:28 +0900)
Especially when a linked tty is used such as pty, the linked tty
port's buf works have not been cancelled while master tty port's
buf work has been cancelled. Since release_one_tty and flush_to_ldisc
run in workqueue threads separately, when pty_cleanup happens and
link tty port is freed, flush_to_ldisc tries to access freed port
and port->itty, eventually it causes a panic.
This patch utilizes the magic value with holding the tty_mutex to
check if the tty->link is valid.

Fixes: 2b022ab7542d ("pty: cancel pty slave port buf's work in tty_release")
Signed-off-by: Sahara <keun-o.park@darkmatter.ae>
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
drivers/tty/pty.c
drivers/tty/tty_io.c

index 00099a8..ef72031 100644 (file)
@@ -116,6 +116,12 @@ static int pty_write(struct tty_struct *tty, const unsigned char *buf, int c)
        if (tty->stopped)
                return 0;
 
+       mutex_lock(&tty_mutex);
+       if (to->magic != TTY_MAGIC) {
+               mutex_unlock(&tty_mutex);
+               return -EIO;
+       }
+
        if (c > 0) {
                spin_lock_irqsave(&to->port->lock, flags);
                /* Stuff the data into the input queue of the other end */
@@ -125,6 +131,7 @@ static int pty_write(struct tty_struct *tty, const unsigned char *buf, int c)
                        tty_flip_buffer_push(to->port);
                spin_unlock_irqrestore(&to->port->lock, flags);
        }
+       mutex_unlock(&tty_mutex);
        return c;
 }
 
index 5fa2501..c27777f 100644 (file)
@@ -1448,10 +1448,13 @@ static void release_one_tty(struct work_struct *work)
        struct tty_driver *driver = tty->driver;
        struct module *owner = driver->owner;
 
+       mutex_lock(&tty_mutex);
        if (tty->ops->cleanup)
                tty->ops->cleanup(tty);
 
        tty->magic = 0;
+       mutex_unlock(&tty_mutex);
+
        tty_driver_kref_put(driver);
        module_put(owner);