[PATCH AUTOSEL 4.9 16/16] virtio_console: Assure used length from device is limited

From: Sasha Levin
Date: Sat Jul 10 2021 - 19:58:15 EST


From: Xie Yongji <xieyongji@xxxxxxxxxxxxx>

[ Upstream commit d00d8da5869a2608e97cfede094dfc5e11462a46 ]

The buf->len might come from an untrusted device. This
ensures the value would not exceed the size of the buffer
to avoid data corruption or loss.

Signed-off-by: Xie Yongji <xieyongji@xxxxxxxxxxxxx>
Acked-by: Jason Wang <jasowang@xxxxxxxxxx>
Link: https://lore.kernel.org/r/20210525125622.1203-1-xieyongji@xxxxxxxxxxxxx
Signed-off-by: Michael S. Tsirkin <mst@xxxxxxxxxx>
Signed-off-by: Sasha Levin <sashal@xxxxxxxxxx>
---
drivers/char/virtio_console.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/drivers/char/virtio_console.c b/drivers/char/virtio_console.c
index 4ec08c7a7b65..2632b0fdb1b5 100644
--- a/drivers/char/virtio_console.c
+++ b/drivers/char/virtio_console.c
@@ -492,7 +492,7 @@ static struct port_buffer *get_inbuf(struct port *port)

buf = virtqueue_get_buf(port->in_vq, &len);
if (buf) {
- buf->len = len;
+ buf->len = min_t(size_t, len, buf->size);
buf->offset = 0;
port->stats.bytes_received += len;
}
@@ -1758,7 +1758,7 @@ static void control_work_handler(struct work_struct *work)
while ((buf = virtqueue_get_buf(vq, &len))) {
spin_unlock(&portdev->c_ivq_lock);

- buf->len = len;
+ buf->len = min_t(size_t, len, buf->size);
buf->offset = 0;

handle_control_message(vq->vdev, portdev, buf);
--
2.30.2