From 2045a5018b079d956176e7677bfab9d1fd63dae5 Mon Sep 17 00:00:00 2001 From: Michal <18419007+m-rola@users.noreply.github.com> Date: Tue, 15 Sep 2026 10:32:31 +0200 Subject: [PATCH] fix(issue-732): Add bounds check before native compress to prevent buffer overflow (#732) --- src/main/java/org/xerial/snappy/Snappy.java | 7 +++++++ src/test/java/org/xerial/snappy/SnappyTest.java | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/main/java/org/xerial/snappy/Snappy.java b/src/main/java/org/xerial/snappy/Snappy.java index 14d17964..7613e7f7 100755 --- a/src/main/java/org/xerial/snappy/Snappy.java +++ b/src/main/java/org/xerial/snappy/Snappy.java @@ -150,6 +150,13 @@ public static int compress(ByteBuffer uncompressed, ByteBuffer compressed) int uPos = uncompressed.position(); int uLen = uncompressed.remaining(); int cPos = compressed.position(); + + int requiredCapacity = maxCompressedLength(uLen); + if (compressed.remaining() < requiredCapacity) { + throw new IllegalArgumentException("not enough space for output: need " + requiredCapacity + + " bytes, but only " + compressed.remaining() + " remaining"); + } + int compressedSize = impl.rawCompress(uncompressed, uPos, uLen, compressed, cPos); diff --git a/src/test/java/org/xerial/snappy/SnappyTest.java b/src/test/java/org/xerial/snappy/SnappyTest.java index 52c3a005..34bd8e4d 100755 --- a/src/test/java/org/xerial/snappy/SnappyTest.java +++ b/src/test/java/org/xerial/snappy/SnappyTest.java @@ -527,6 +527,21 @@ public void isTooLargeShortArrayInputLengthForBitShuffleShuffle() throws Excepti BitShuffle.shuffle(new short[Integer.MAX_VALUE / 2 + 1]); } + @Test(expected = IllegalArgumentException.class) + public void testCompressWithInsufficientBuffer() throws Exception { + byte[] incompressible = new byte[1024 * 1024]; + new java.util.Random(42).nextBytes(incompressible); + + ByteBuffer src = ByteBuffer.allocateDirect(incompressible.length); + src.put(incompressible); + src.flip(); + + ByteBuffer dest = ByteBuffer.allocateDirect(64); + + Snappy.compress(src, dest); + fail("Expected IllegalArgumentException but method completed normally"); +} + private void assumingCIIsFalse() { if (System.getenv("CI") == null) return;