From dadd37b60ca43b436a2287d28d6497bcc5bf4b9a Mon Sep 17 00:00:00 2001
From: Paul Eggert <eggert@cs.ucla.edu>
Date: Tue, 28 Apr 2026 11:25:00 -0700
Subject: [PATCH] uniq: fix read overrun with -w
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Problem reported by Michał Majchrowicz.
* src/uniq.c (find_field): Fix typo.
* tests/uniq/uniq.pl (add_z_variants): Test for the bug.

CVE: CVE-2026-56391
Upstream-Status: Backport [https://cgit.git.savannah.gnu.org/cgit/coreutils.git/commit/?id=d64e35a8a4c0e4608321433e0d84d917e4e36371]

Backport Changes:
- The NEWS file has not been updated.

Signed-off-by: Leonid Iziumtsev <leonid.iziumtsev@est.tech>
---
 THANKS.in          | 1 +
 src/uniq.c         | 4 ++--
 tests/uniq/uniq.pl | 3 +++
 3 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/THANKS.in b/THANKS.in
index 35fee75..5a2fd35 100644
--- a/THANKS.in
+++ b/THANKS.in
@@ -459,6 +459,7 @@ Michail Litvak                      mci@owl.openwall.com
 Michal Politowski                   mpol@charybda.icm.edu.pl
 Michal Svec                         msvec@suse.cz
 Michal Trunecka                     mtruneck@redhat.com
+Michał Majchrowicz                  mmajchrowicz@afine.com
 Michel Robitaille                   robitail@IRO.UMontreal.CA
 Michiel Bacchiani                   bacchian@raven.bu.edu
 Mike Castle                         dalgoda@ix.netcom.com
diff --git a/src/uniq.c b/src/uniq.c
index 3046359..5834596 100644
--- a/src/uniq.c
+++ b/src/uniq.c
@@ -285,8 +285,8 @@ find_field (struct linebuffer const *line, idx_t *plen)
   else
     {
       char *ep = lp;
-      for (idx_t i = check_chars; 0 < i && lp < lim; i--)
-        ep += mcel_scan (lp, lim).len;
+      for (idx_t i = check_chars; 0 < i && ep < lim; i--)
+        ep += mcel_scan (ep, lim).len;
       len = ep - lp;
     }
 
diff --git a/tests/uniq/uniq.pl b/tests/uniq/uniq.pl
index b558fb3..0df7ec6 100755
--- a/tests/uniq/uniq.pl
+++ b/tests/uniq/uniq.pl
@@ -234,6 +234,9 @@ my @Tests =
         "  - 'separate'\n" .
         "  - 'both'\n" .
         "Try '$prog --help' for more information.\n"}],
+ # Test for read buffer overrun.
+ do { my $longline = "\360\237\230\200" . "A" x 255 . "\n";
+      ['146', '-w256', {IN  => $longline x 2}, {OUT => $longline}] },
 );
 
 # Locale related tests
