From 6a4b3760214557c53001d688405f22adb911fb6b Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Tue, 7 Jan 2020 14:42:56 +0100 Subject: [PATCH] Kernel: Validate ftruncate(fd, length) syscall inputs - EINVAL if 'length' is negative - EBADF if 'fd' is not open for writing --- Kernel/Process.cpp | 5 ++++- Userland/test_io.cpp | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Kernel/Process.cpp b/Kernel/Process.cpp index 9b8bd908e3..67a8be2353 100644 --- a/Kernel/Process.cpp +++ b/Kernel/Process.cpp @@ -3424,10 +3424,13 @@ int Process::sys$rename(const char* oldpath, const char* newpath) int Process::sys$ftruncate(int fd, off_t length) { + if (length < 0) + return -EINVAL; auto* description = file_description(fd); if (!description) return -EBADF; - // FIXME: Check that fd is writable, otherwise EINVAL. + if (!description->is_writable()) + return -EBADF; return description->truncate(length); } diff --git a/Userland/test_io.cpp b/Userland/test_io.cpp index d276da97e6..dc8f1e7961 100644 --- a/Userland/test_io.cpp +++ b/Userland/test_io.cpp @@ -87,6 +87,24 @@ void test_read_past_eof() ASSERT(rc == 0); } +void test_ftruncate_readonly() +{ + int fd = open("/tmp/trunctest", O_RDONLY | O_CREAT, 0666); + ASSERT(fd >= 0); + int rc; + EXPECT_ERROR_2(EBADF, ftruncate, fd, 0); + close(fd); +} + +void test_ftruncate_negative() +{ + int fd = open("/tmp/trunctest", O_RDWR | O_CREAT, 0666); + ASSERT(fd >= 0); + int rc; + EXPECT_ERROR_2(EINVAL, ftruncate, fd, -1); + close(fd); +} + int main(int, char**) { int rc; @@ -103,6 +121,8 @@ int main(int, char**) test_read_from_writeonly(); test_write_to_readonly(); test_read_past_eof(); + test_ftruncate_readonly(); + test_ftruncate_negative(); return 0; }