1From 8c9602e3a145e9596dc1a63c6ed67865814b6633 Mon Sep 17 00:00:00 2001
2From: Pádraig Brady <P@draigBrady.com>
3Date: Tue, 20 May 2025 16:03:44 +0100
4Subject: sort: fix buffer under-read (CWE-127)
5
6* src/sort.c (begfield): Check pointer adjustment
7to avoid Out-of-range pointer offset (CWE-823).
8(limfield): Likewise.
9* tests/sort/sort-field-limit.sh: Add a new test,
10which triggers with ASAN or Valgrind.
11* tests/local.mk: Reference the new test.
12* NEWS: Mention bug fix introduced in v7.2 (2009).
13Fixes https://bugs.gnu.org/78507
14---
15 NEWS | 5 +++++
16 src/sort.c | 12 ++++++++++--
17 tests/local.mk | 1 +
18 tests/sort/sort-field-limit.sh | 35 +++++++++++++++++++++++++++++++++++
19 4 files changed, 51 insertions(+), 2 deletions(-)
20 create mode 100755 tests/sort/sort-field-limit.sh
21
22The new tests is NOT added in NixOS.
23
24diff --git a/NEWS b/NEWS
25index 6ff403206..923aa72f8 100644
26--- a/NEWS
27+++ b/NEWS
28@@ -8,6 +8,11 @@ GNU coreutils NEWS -*- outline -*-
29 copying to non-NFS files from NFSv4 files with trivial ACLs.
30 [bug introduced in coreutils-9.6]
31
32+ sort with key character offsets of SIZE_MAX, could induce
33+ a read of 1 byte before an allocated heap buffer. For example:
34+ 'sort +0.18446744073709551615R input' on 64 bit systems.
35+ [bug introduced in coreutils-7.2]
36+
37
38 * Noteworthy changes in release 9.7 (2025-04-09) [stable]
39
40diff --git a/src/sort.c b/src/sort.c
41index b10183b6f..7af1a2512 100644
42--- a/src/sort.c
43+++ b/src/sort.c
44@@ -1644,7 +1644,11 @@ begfield (struct line const *line, struct keyfield const *key)
45 ++ptr;
46
47 /* Advance PTR by SCHAR (if possible), but no further than LIM. */
48- ptr = MIN (lim, ptr + schar);
49+ size_t remaining_bytes = lim - ptr;
50+ if (schar < remaining_bytes)
51+ ptr += schar;
52+ else
53+ ptr = lim;
54
55 return ptr;
56 }
57@@ -1746,7 +1750,11 @@ limfield (struct line const *line, struct keyfield const *key)
58 ++ptr;
59
60 /* Advance PTR by ECHAR (if possible), but no further than LIM. */
61- ptr = MIN (lim, ptr + echar);
62+ size_t remaining_bytes = lim - ptr;
63+ if (echar < remaining_bytes)
64+ ptr += echar;
65+ else
66+ ptr = lim;
67 }
68
69 return ptr;