From b44946447b49e4f8f5c49ec6b55c9b46b93ed3f7 Mon Sep 17 00:00:00 2001
From: Fam Zheng <famz@redhat.com>
Date: Wed, 22 Mar 2017 23:51:08 +0100
Subject: [PATCH 11/12] file-posix: clean up max_segments buffer termination

RH-Author: Fam Zheng <famz@redhat.com>
Message-id: <20170322235109.24122-3-famz@redhat.com>
Patchwork-id: 74432
O-Subject: [RHEV-7.3.z qemu-kvm-rhev PATCH v2 2/3] file-posix: clean up max_segments buffer termination
Bugzilla: 1431149
RH-Acked-by: Stefan Hajnoczi <stefanha@redhat.com>
RH-Acked-by: Paolo Bonzini <pbonzini@redhat.com>
RH-Acked-by: Markus Armbruster <armbru@redhat.com>

From: Stefan Hajnoczi <stefanha@redhat.com>

The following pattern is unsafe:

  char buf[32];
  ret = read(fd, buf, sizeof(buf));
  ...
  buf[ret] = 0;

If read(2) returns 32 then a byte beyond the end of the buffer is
zeroed.

In practice this buffer overflow does not occur because the sysfs
max_segments file only contains an unsigned short + '\n'.  The string is
always shorter than 32 bytes.

Regardless, avoid this pattern because static analysis tools might
complain and it could lead to real buffer overflows if copy-pasted
elsewhere in the codebase.

Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
(cherry picked from commit 69583490856713f693291b32fc74b6d0f5992b72)
Signed-off-by: Fam Zheng <famz@redhat.com>
Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
---
 block/raw-posix.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/block/raw-posix.c b/block/raw-posix.c
index 9d9a6a0..ce9d113 100644
--- a/block/raw-posix.c
+++ b/block/raw-posix.c
@@ -760,7 +760,7 @@ static int hdev_get_max_segments(const struct stat *st)
         goto out;
     }
     do {
-        ret = read(fd, buf, sizeof(buf));
+        ret = read(fd, buf, sizeof(buf) - 1);
     } while (ret == -1 && errno == EINTR);
     if (ret < 0) {
         ret = -errno;
-- 
1.8.3.1

