diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfStringsSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfStringsSerDe.java index 1afba2a3c..de341a595 100644 --- a/src/main/java/org/apache/datasketches/common/ArrayOfStringsSerDe.java +++ b/src/main/java/org/apache/datasketches/common/ArrayOfStringsSerDe.java @@ -84,14 +84,15 @@ public String[] deserializeFromMemory(final Memory mem, final int numItems) { public String[] deserializeFromMemory(final Memory mem, final long offsetBytes, final int numItems) { Objects.requireNonNull(mem, "Memory must not be null"); if (numItems <= 0) { return new String[0]; } + Util.checkBounds(offsetBytes, (long) numItems * Integer.BYTES, mem.getCapacity()); final String[] array = new String[numItems]; long offset = offsetBytes; for (int i = 0; i < numItems; i++) { Util.checkBounds(offset, Integer.BYTES, mem.getCapacity()); final int strLength = mem.getInt(offset); offset += Integer.BYTES; - final byte[] utf8Bytes = new byte[strLength]; Util.checkBounds(offset, strLength, mem.getCapacity()); + final byte[] utf8Bytes = new byte[strLength]; mem.getByteArray(offset, utf8Bytes, 0, strLength); offset += strLength; array[i] = new String(utf8Bytes, StandardCharsets.UTF_8); diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.java index 2ed1b316e..220955b0a 100644 --- a/src/main/java/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.java +++ b/src/main/java/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.java @@ -80,14 +80,15 @@ public String[] deserializeFromMemory(final Memory mem, final int numItems) { public String[] deserializeFromMemory(final Memory mem, final long offsetBytes, final int numItems) { Objects.requireNonNull(mem, "Memory must not be null"); if (numItems <= 0) { return new String[0]; } + Util.checkBounds(offsetBytes, (long) numItems * Integer.BYTES, mem.getCapacity()); final String[] array = new String[numItems]; long offset = offsetBytes; for (int i = 0; i < numItems; i++) { Util.checkBounds(offset, Integer.BYTES, mem.getCapacity()); final int strLength = mem.getInt(offset); offset += Integer.BYTES; - final byte[] utf16Bytes = new byte[strLength]; Util.checkBounds(offset, strLength, mem.getCapacity()); + final byte[] utf16Bytes = new byte[strLength]; mem.getByteArray(offset, utf16Bytes, 0, strLength); offset += strLength; array[i] = new String(utf16Bytes, StandardCharsets.UTF_16); diff --git a/src/main/java/org/apache/datasketches/frequencies/LongsSketch.java b/src/main/java/org/apache/datasketches/frequencies/LongsSketch.java index 7d1990b62..044ada922 100644 --- a/src/main/java/org/apache/datasketches/frequencies/LongsSketch.java +++ b/src/main/java/org/apache/datasketches/frequencies/LongsSketch.java @@ -255,6 +255,16 @@ public static LongsSketch getInstance(final Memory srcMem) { throw new SketchesArgumentException( "Possible Corruption: (PreLongs == 1) ^ Empty == True."); } + if (lgCurMapSize < LG_MIN_MAP_SIZE) { //Byte 4 + throw new SketchesArgumentException( + "Possible Corruption: LgCurMapSize must be at least " + LG_MIN_MAP_SIZE + ": " + + lgCurMapSize); + } + if (lgCurMapSize > lgMaxMapSize) { //Byte 4 and Byte 3 + throw new SketchesArgumentException( + "Possible Corruption: LgCurMapSize must not exceed LgMaxMapSize: " + + lgCurMapSize + " > " + lgMaxMapSize); + } if (empty) { return new LongsSketch(lgMaxMapSize, LG_MIN_MAP_SIZE); @@ -328,6 +338,21 @@ public static LongsSketch getInstance(final String string) { "Possible Corruption: Incorrect # of tokens: " + numTokens + ", numActive: " + numActive); } + if (lgCur < LG_MIN_MAP_SIZE) { + throw new SketchesArgumentException( + "Possible Corruption: Map length must be at least " + (1 << LG_MIN_MAP_SIZE) + ": " + + tokens[STR_PREAMBLE_TOKENS + 1]); + } + if (lgCur > lgMax) { + throw new SketchesArgumentException( + "Possible Corruption: Map length must not exceed max map length " + (1L << lgMax) + ": " + + tokens[STR_PREAMBLE_TOKENS + 1]); + } + final long maxActive = (long) ((1L << lgCur) * ReversePurgeLongHashMap.getLoadFactor()); + if ((numActive < 0) || (numActive > maxActive)) { + throw new SketchesArgumentException( + "Possible Corruption: numActive exceeds map capacity: " + numActive); + } final LongsSketch sketch = new LongsSketch(lgMax, lgCur); sketch.streamWeight = streamWt; diff --git a/src/main/java/org/apache/datasketches/theta/CompactOperations.java b/src/main/java/org/apache/datasketches/theta/CompactOperations.java index a8066314d..4fa734e54 100644 --- a/src/main/java/org/apache/datasketches/theta/CompactOperations.java +++ b/src/main/java/org/apache/datasketches/theta/CompactOperations.java @@ -50,6 +50,7 @@ import org.apache.datasketches.common.SketchesStateException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.WritableMemory; +import org.apache.datasketches.thetacommon.ThetaUtil; /** * @author Lee Rhodes @@ -171,9 +172,15 @@ static CompactSketch memoryToCompact( //extract hashArr > 1 final long[] hashArr; if (srcCompactFlag) { + PreambleUtil.checkCompactImage(srcMem); hashArr = new long[curCount]; srcMem.getLongArray(srcPreLongs << 3, hashArr, 0, curCount); } else { //update sketch, thus hashTable form + if ((srcLgArrLongs > (ThetaUtil.MAX_LG_NOM_LONGS + 1)) + || (srcMem.getCapacity() < (((long) srcPreLongs << 3) + (8L << srcLgArrLongs)))) { + throw new SketchesArgumentException("Possible corruption: lgArrLongs " + srcLgArrLongs + + " is too large for the Memory size " + srcMem.getCapacity()); + } final int srcCacheLen = 1 << srcLgArrLongs; final long[] tempHashArr = new long[srcCacheLen]; srcMem.getLongArray(srcPreLongs << 3, tempHashArr, 0, srcCacheLen); diff --git a/src/main/java/org/apache/datasketches/theta/CompactSketch.java b/src/main/java/org/apache/datasketches/theta/CompactSketch.java index 1426368f1..fb8246d65 100644 --- a/src/main/java/org/apache/datasketches/theta/CompactSketch.java +++ b/src/main/java/org/apache/datasketches/theta/CompactSketch.java @@ -340,6 +340,7 @@ private static CompactSketch heapifyV4(final Memory srcMem, final long seed, fin final short seedHash = (short) extractSeedHash(srcMem); final boolean isEmpty = (flags & EMPTY_FLAG_MASK) > 0; if (enforceSeed && !isEmpty) { PreambleUtil.checkMemorySeedHash(srcMem, seed); } + PreambleUtil.checkCompressedImage(srcMem); int offsetBytes = 8; long theta = Long.MAX_VALUE; if (preLongs > 1) { diff --git a/src/main/java/org/apache/datasketches/theta/DirectCompactSketch.java b/src/main/java/org/apache/datasketches/theta/DirectCompactSketch.java index 0f69ec3c2..31d482a7c 100644 --- a/src/main/java/org/apache/datasketches/theta/DirectCompactSketch.java +++ b/src/main/java/org/apache/datasketches/theta/DirectCompactSketch.java @@ -66,6 +66,7 @@ class DirectCompactSketch extends CompactSketch { */ static DirectCompactSketch wrapInstance(final Memory srcMem, final short seedHash) { ThetaUtil.checkSeedHashes((short) extractSeedHash(srcMem), seedHash); + PreambleUtil.checkCompactImage(srcMem); return new DirectCompactSketch(srcMem); } diff --git a/src/main/java/org/apache/datasketches/theta/ForwardCompatibility.java b/src/main/java/org/apache/datasketches/theta/ForwardCompatibility.java index 16172d247..7cd0ed990 100644 --- a/src/main/java/org/apache/datasketches/theta/ForwardCompatibility.java +++ b/src/main/java/org/apache/datasketches/theta/ForwardCompatibility.java @@ -68,7 +68,8 @@ static final CompactSketch heapify1to3(final Memory srcMem, final short seedHash return EmptyCompactSketch.getInstance(); } - final int reqCap = (curCount + preLongs) << 3; + checkCurCount(curCount); + final long reqCap = ((long) curCount + preLongs) << 3; validateInputSize(reqCap, memCap); if ((thetaLong == Long.MAX_VALUE) && (curCount == 1)) { @@ -98,7 +99,7 @@ static final CompactSketch heapify2to3(final Memory srcMem, final short seedHash if ((familyId < 1) || (familyId > 4)) { throw new SketchesArgumentException("Family (Sketch Type) must be 1 to 4: " + familyId); } - int reqBytesIn = 8; + long reqBytesIn = 8; int curCount = 0; long thetaLong = Long.MAX_VALUE; if (preLongs == 1) { @@ -120,7 +121,8 @@ static final CompactSketch heapify2to3(final Memory srcMem, final short seedHash return new SingleItemSketch(hash, seedHash); } //curCount > 1 - reqBytesIn = (curCount + preLongs) << 3; + checkCurCount(curCount); + reqBytesIn = ((long) curCount + preLongs) << 3; validateInputSize(reqBytesIn, memCap); final long[] compactOrderedCache = new long[curCount]; srcMem.getLongArray(preLongs << 3, compactOrderedCache, 0, curCount); @@ -141,7 +143,8 @@ static final CompactSketch heapify2to3(final Memory srcMem, final short seedHash return new SingleItemSketch(hash, seedHash); } //curCount > 1 and/or theta < 1.0 - reqBytesIn = (curCount + preLongs) << 3; + checkCurCount(curCount); + reqBytesIn = ((long) curCount + preLongs) << 3; validateInputSize(reqBytesIn, memCap); final long[] compactOrderedCache = new long[curCount]; srcMem.getLongArray(preLongs << 3, compactOrderedCache, 0, curCount); @@ -150,7 +153,13 @@ static final CompactSketch heapify2to3(final Memory srcMem, final short seedHash throw new SketchesArgumentException("PreLongs must be 1,2, or 3: " + preLongs); } - private static final void validateInputSize(final int reqBytesIn, final int memCap) { + private static final void checkCurCount(final int curCount) { + if (curCount < 0) { + throw new SketchesArgumentException("Possible corruption: negative curCount: " + curCount); + } + } + + private static final void validateInputSize(final long reqBytesIn, final long memCap) { if (reqBytesIn > memCap) { throw new SketchesArgumentException( "Input Memory or byte[] size is too small: Required Bytes: " + reqBytesIn diff --git a/src/main/java/org/apache/datasketches/theta/Intersection.java b/src/main/java/org/apache/datasketches/theta/Intersection.java index 111a9ce55..4bcb94208 100644 --- a/src/main/java/org/apache/datasketches/theta/Intersection.java +++ b/src/main/java/org/apache/datasketches/theta/Intersection.java @@ -25,6 +25,7 @@ import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; import static org.apache.datasketches.theta.PreambleUtil.extractFlags; +import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs; import static org.apache.datasketches.theta.PreambleUtil.extractPreLongs; import static org.apache.datasketches.theta.PreambleUtil.extractSerVer; @@ -216,6 +217,21 @@ protected static void memChecks(final Memory srcMem) { } //empty = true AND curCount_ = 0: OK } //else empty = false, curCount could be anything + //The hash table holds curCount entries and is no larger than for the largest nominal entries. + //A curCount of -1 means the intersection has no result yet. + final int lgArrLongs = extractLgArrLongs(srcMem); + if ((lgArrLongs < 0) || (lgArrLongs > (ThetaUtil.MAX_LG_NOM_LONGS + 1)) + || (curCount < -1) || (curCount > (1 << lgArrLongs))) { + throw new SketchesArgumentException("Possible corruption: lgArrLongs: " + lgArrLongs + + ", curCount: " + curCount); + } + if (curCount > 0) { //the image must hold the hash table + final long reqBytes = ((long) CONST_PREAMBLE_LONGS << 3) + (8L << lgArrLongs); + if (srcMem.getCapacity() < reqBytes) { + throw new SketchesArgumentException("Possible corruption: Memory size " + srcMem.getCapacity() + + " < required " + reqBytes); + } + } } } diff --git a/src/main/java/org/apache/datasketches/theta/PreambleUtil.java b/src/main/java/org/apache/datasketches/theta/PreambleUtil.java index e1d9262e6..1f8b72dbb 100644 --- a/src/main/java/org/apache/datasketches/theta/PreambleUtil.java +++ b/src/main/java/org/apache/datasketches/theta/PreambleUtil.java @@ -347,6 +347,67 @@ else if (preLongs == 3) { //@formatter:on + /** + * Checks that the Memory holds the preamble longs it declares, and returns them. + * @param mem the sketch image + * @return the number of preamble longs + * @throws SketchesArgumentException if the Memory is smaller than the preamble + */ + static int checkMemPreambleCap(final Memory mem) { + Util.checkBounds(0, 8, mem.getCapacity()); + final int preLongs = extractPreLongs(mem); + final long reqBytes = (long) preLongs << 3; + if (mem.getCapacity() < reqBytes) { + throw new SketchesArgumentException("Possible corruption: preLongs " + preLongs + + " needs " + reqBytes + " bytes, Memory has " + mem.getCapacity()); + } + return preLongs; + } + + /** + * Checks that a serial version 3 compact image, which is not empty and not a single item, holds the + * number of hashes it declares, before anything is allocated or read from it. + * @param mem the compact image + * @throws SketchesArgumentException if the image is too small or the count is invalid + */ + static void checkCompactImage(final Memory mem) { + final int preLongs = checkMemPreambleCap(mem); + final int curCount = (preLongs > 1) ? extractCurCount(mem) : 1; + final long reqBytes = ((long) preLongs << 3) + ((long) curCount << 3); + if ((curCount < 0) || (mem.getCapacity() < reqBytes)) { + throw new SketchesArgumentException("Possible corruption: curCount " + curCount + + " needs " + reqBytes + " bytes, Memory has " + mem.getCapacity()); + } + } + + /** + * Checks that a serial version 4 (compressed) compact image holds the number of entries it + * declares, before anything is allocated or read from it. + * @param mem the compressed compact image + * @throws SketchesArgumentException if the image is too small or its fields are invalid + */ + static void checkCompressedImage(final Memory mem) { + final int preLongs = checkMemPreambleCap(mem); + final int entryBits = extractEntryBitsV4(mem); + final int numEntriesBytes = extractNumEntriesBytesV4(mem); + if ((preLongs < 1) || (preLongs > 2) || (entryBits < 1) || (entryBits > 63) + || (numEntriesBytes < 1) || (numEntriesBytes > 4)) { + throw new SketchesArgumentException("Possible corruption: preLongs: " + preLongs + + ", entryBits: " + entryBits + ", numEntriesBytes: " + numEntriesBytes); + } + final int offsetBytes = preLongs << 3; + Util.checkBounds(0, offsetBytes + numEntriesBytes, mem.getCapacity()); + long numEntries = 0; + for (int i = 0; i < numEntriesBytes; i++) { + numEntries |= (long) Byte.toUnsignedInt(mem.getByte(offsetBytes + i)) << (i << 3); + } + if (numEntries > Integer.MAX_VALUE) { + throw new SketchesArgumentException("Possible corruption: numEntries: " + numEntries); + } + final long packedBytes = ((numEntries * entryBits) + 7) >>> 3; + Util.checkBounds(offsetBytes + numEntriesBytes, packedBytes, mem.getCapacity()); + } + static int extractPreLongs(final Memory mem) { return mem.getByte(PREAMBLE_LONGS_BYTE) & 0X3F; } diff --git a/src/main/java/org/apache/datasketches/theta/UpdateSketch.java b/src/main/java/org/apache/datasketches/theta/UpdateSketch.java index cb6854b02..a2b336e5c 100644 --- a/src/main/java/org/apache/datasketches/theta/UpdateSketch.java +++ b/src/main/java/org/apache/datasketches/theta/UpdateSketch.java @@ -33,13 +33,13 @@ import static org.apache.datasketches.theta.PreambleUtil.SER_VER; import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE; import static org.apache.datasketches.theta.PreambleUtil.checkMemorySeedHash; +import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; import static org.apache.datasketches.theta.PreambleUtil.extractFlags; import static org.apache.datasketches.theta.PreambleUtil.extractLgResizeFactor; import static org.apache.datasketches.theta.PreambleUtil.extractP; import static org.apache.datasketches.theta.PreambleUtil.extractSerVer; import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.getMemBytes; import static org.apache.datasketches.theta.UpdateReturnState.RejectedNullOrEmpty; import java.nio.ByteBuffer; @@ -430,9 +430,19 @@ static void checkMemIntegrity(final Memory srcMem, final long expectedSeed, fina final short seedHash = checkMemorySeedHash(srcMem, expectedSeed); //byte 6,7 ThetaUtil.checkSeedHashes(seedHash, ThetaUtil.computeSeedHash(expectedSeed)); - //Check mem capacity, lgArrLongs + //Check lgNomLongs, lgArrLongs and curCount. The hash table grows to at most twice the nominal entries. + if ((lgNomLongs > ThetaUtil.MAX_LG_NOM_LONGS) || (lgArrLongs < 0) || (lgArrLongs > (lgNomLongs + 1))) { + throw new SketchesArgumentException("Possible corruption: lgNomLongs: " + lgNomLongs + + ", lgArrLongs: " + lgArrLongs); + } + final int curCount = extractCurCount(srcMem); + if ((curCount < 0) || (curCount > (1 << lgArrLongs))) { + throw new SketchesArgumentException("Possible corruption: invalid curCount: " + curCount); + } + + //Check mem capacity, computed in long arithmetic so that it cannot overflow final long curCapBytes = srcMem.getCapacity(); - final int minReqBytes = getMemBytes(lgArrLongs, preambleLongs); + final long minReqBytes = (8L << lgArrLongs) + ((long) preambleLongs << 3); if (curCapBytes < minReqBytes) { throw new SketchesArgumentException( "Possible corruption: Current Memory size < min required size: " diff --git a/src/test/java/org/apache/datasketches/common/StringSerDeBoundsTest.java b/src/test/java/org/apache/datasketches/common/StringSerDeBoundsTest.java new file mode 100644 index 000000000..4e931f474 --- /dev/null +++ b/src/test/java/org/apache/datasketches/common/StringSerDeBoundsTest.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.datasketches.common; + +import static org.apache.datasketches.common.ByteArrayUtil.putIntLE; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.expectThrows; + +import java.util.Arrays; + +import org.apache.datasketches.memory.Memory; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class StringSerDeBoundsTest { + @DataProvider(name = "stringSerDes") + public Object[][] stringSerDes() { + return new Object[][] { + {new ArrayOfStringsSerDe()}, + {new ArrayOfUtf16StringsSerDe()} + }; + } + + @Test(dataProvider = "stringSerDes") + public void rejectInvalidLengthsBeforeAllocation(final ArrayOfItemsSerDe serDe) { + for (final int length : new int[] {-1, Integer.MAX_VALUE, 5}) { + final byte[] bytes = new byte[Integer.BYTES]; + putIntLE(bytes, 0, length); + final Memory mem = Memory.wrap(bytes); + expectThrows(SketchesArgumentException.class, + () -> serDe.deserializeFromMemory(mem, 1)); + expectThrows(SketchesArgumentException.class, () -> serDe.sizeOf(mem, 0, 1)); + } + } + + @Test(dataProvider = "stringSerDes") + public void rejectImpossibleCountsBeforeAllocation(final ArrayOfItemsSerDe serDe) { + final Memory mem = Memory.wrap(new byte[Integer.BYTES]); + expectThrows(SketchesArgumentException.class, + () -> serDe.deserializeFromMemory(mem, Integer.MAX_VALUE)); + expectThrows(SketchesArgumentException.class, + () -> serDe.deserializeFromMemory(mem, 2)); + } + + @Test(dataProvider = "stringSerDes") + public void rejectInvalidOffsetsAndTruncatedPrefixes(final ArrayOfItemsSerDe serDe) { + final Memory mem = Memory.wrap(new byte[Integer.BYTES]); + for (final long offset : new long[] {-1, Long.MAX_VALUE, 1, 4}) { + expectThrows(SketchesArgumentException.class, + () -> serDe.deserializeFromMemory(mem, offset, 1)); + } + } + + @Test(dataProvider = "stringSerDes") + public void preserveValidOffsetUnicodeAndOwnership(final ArrayOfItemsSerDe serDe) { + final String[] expected = {"", "hello", "\u65e5\u672c\u8a9e", "\ud83d\ude00", "a\u0000b"}; + final byte[] encoded = serDe.serializeToByteArray(expected); + final byte[] padded = new byte[3 + encoded.length + 1]; + System.arraycopy(encoded, 0, padded, 3, encoded.length); + final Memory mem = Memory.wrap(padded); + final String[] actual = serDe.deserializeFromMemory(mem, 3, expected.length); + assertEquals(actual, expected); + assertEquals(serDe.sizeOf(mem, 3, expected.length), encoded.length); + Arrays.fill(padded, (byte) 0); + assertEquals(actual, expected); + } + + @Test(dataProvider = "stringSerDes") + public void preserveEmptyCount(final ArrayOfItemsSerDe serDe) { + assertEquals(serDe.deserializeFromMemory(Memory.wrap(new byte[0]), 0).length, 0); + } +} diff --git a/src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.java b/src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.java index ad396e9e8..dd17c61a9 100644 --- a/src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.java +++ b/src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.java @@ -23,6 +23,8 @@ import static org.apache.datasketches.frequencies.DistTest.randomGeometricDist; import static org.apache.datasketches.frequencies.PreambleUtil.FAMILY_BYTE; import static org.apache.datasketches.frequencies.PreambleUtil.FLAGS_BYTE; +import static org.apache.datasketches.frequencies.PreambleUtil.LG_CUR_MAP_SIZE_BYTE; +import static org.apache.datasketches.frequencies.PreambleUtil.LG_MAX_MAP_SIZE_BYTE; import static org.apache.datasketches.frequencies.PreambleUtil.PREAMBLE_LONGS_BYTE; import static org.apache.datasketches.frequencies.PreambleUtil.SER_VER_BYTE; import static org.apache.datasketches.frequencies.Util.LG_MIN_MAP_SIZE; @@ -545,6 +547,68 @@ public void checkStringDeserEmptyCorrupt() { LongsSketch.getInstance(s); } + @Test(expectedExceptions = SketchesArgumentException.class, timeOut = 5000) + public void checkStringDeserMapLengthTooSmall() { + final String s = "1," //serVer + + "10," //FamID + + "3," //lgMaxMapSz + + "5," //Empty Flag + + "0," //stream Len: empty + + "0," //error offset + + "0," //numActive + + "2,"; //curMapLen ... corrupted, below the minimum of 8 + final LongsSketch fls = LongsSketch.getInstance(s); + fls.update(1); + fls.update(2); + fls.update(3); + } + + @Test(expectedExceptions = SketchesArgumentException.class, timeOut = 5000) + public void checkStringDeserNumActiveExceedsMapCapacity() { + final StringBuilder sb = new StringBuilder(); + sb.append("1,") //serVer + .append("10,") //FamID + .append("3,") //lgMaxMapSz + .append("0,") //Empty Flag = false + .append("9,") //stream Len + .append("0,") //error offset + .append("9,") //numActive ... corrupted, more than the map can hold + .append("8,"); //curMapLen + for (int i = 1; i <= 9; i++) { sb.append(i).append(",1,"); } + LongsSketch.getInstance(sb.toString()); + } + + @Test(expectedExceptions = SketchesArgumentException.class, timeOut = 5000) + public void checkStringDeserMapLengthExceedsMax() { + final String s = "1," //serVer + + "10," //FamID + + "3," //lgMaxMapSz + + "5," //Empty Flag + + "0," //stream Len: empty + + "0," //error offset + + "0," //numActive + + "16,"; //curMapLen ... corrupted, above the max of 8 + LongsSketch.getInstance(s); + } + + @Test(expectedExceptions = SketchesArgumentException.class, timeOut = 5000) + public void checkMemDeserLgCurMapSizeTooSmall() { + final LongsSketch sk = new LongsSketch(1 << 8); + sk.update(1); + final byte[] bytes = sk.toByteArray(); + bytes[LG_CUR_MAP_SIZE_BYTE] = (byte) (LG_MIN_MAP_SIZE - 1); //corrupted, below the minimum + LongsSketch.getInstance(Memory.wrap(bytes)); + } + + @Test(expectedExceptions = SketchesArgumentException.class, timeOut = 5000) + public void checkMemDeserLgCurMapSizeExceedsLgMax() { + final LongsSketch sk = new LongsSketch(1 << 8); + sk.update(1); + final byte[] bytes = sk.toByteArray(); + bytes[LG_CUR_MAP_SIZE_BYTE] = (byte) (bytes[LG_MAX_MAP_SIZE_BYTE] + 1); //corrupted, above max + LongsSketch.getInstance(Memory.wrap(bytes)); + } + @Test public void checkGetEpsilon() { assertEquals(LongsSketch.getEpsilon(1024), 3.5 / 1024, 0.0); diff --git a/src/test/java/org/apache/datasketches/theta/ThetaCorruptImageTest.java b/src/test/java/org/apache/datasketches/theta/ThetaCorruptImageTest.java new file mode 100644 index 000000000..388ad9768 --- /dev/null +++ b/src/test/java/org/apache/datasketches/theta/ThetaCorruptImageTest.java @@ -0,0 +1,160 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.datasketches.theta; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.expectThrows; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.function.Function; + +import org.apache.datasketches.common.ByteArrayUtil; +import org.apache.datasketches.common.SketchesArgumentException; +import org.apache.datasketches.memory.Memory; +import org.apache.datasketches.memory.WritableMemory; +import org.testng.annotations.Test; + +/** + * Checks that corrupt theta sketch, union and intersection images are rejected with a + * SketchesArgumentException before any large allocation (CVE-2026-122096). + * Ported from ThetaCorruptImageTest in 9.1.0, plus checks for the serial version 1 and 2 + * images that 7.x still reads. + */ +public class ThetaCorruptImageTest { + private static final int LG_ARR_BYTE = 4; + private static final int CUR_COUNT_INT = 8; + + private static UpdateSketch sketch(final int n) { + final UpdateSketch sk = UpdateSketch.builder().build(); + for (int i = 0; i < n; i++) { sk.update(i); } + return sk; + } + + private static void checkRejected(final byte[] bytes, final Function deser) { + expectThrows(SketchesArgumentException.class, () -> deser.apply(Memory.wrap(bytes))); + } + + @Test + public void checkValidImagesStillWork() { + final UpdateSketch sk = sketch(1000); + final byte[] c = sk.compact().toByteArray(); + assertEquals(CompactSketch.heapify(Memory.wrap(c)).getRetainedEntries(), 1000); + assertEquals(CompactSketch.wrap(Memory.wrap(c)).getRetainedEntries(), 1000); + assertEquals(Sketch.heapify(Memory.wrap(c)).getRetainedEntries(), 1000); + final byte[] z = sk.compact().toByteArrayCompressed(); + assertEquals(CompactSketch.heapify(Memory.wrap(z)).getRetainedEntries(), 1000); + assertEquals(CompactSketch.wrap(Memory.wrap(z)).getRetainedEntries(), 1000); + assertEquals(Sketches.heapifyUpdateSketch(Memory.wrap(sk.toByteArray())).getRetainedEntries(), 1000); + assertEquals(Sketch.heapify(Memory.wrap(sk.toByteArray())).getRetainedEntries(), 1000); + assertEquals(Sketch.wrap(Memory.wrap(sk.toByteArray())).getRetainedEntries(), 1000); + final Union union = SetOperation.builder().buildUnion(); + union.union(sk); + assertEquals(((Union) SetOperation.heapify(Memory.wrap(union.toByteArray()))) + .getResult().getRetainedEntries(), 1000); + final Intersection inter = SetOperation.builder().buildIntersection(); + inter.intersect(sk); + assertEquals(((Intersection) SetOperation.heapify(Memory.wrap(inter.toByteArray()))) + .getResult().getRetainedEntries(), 1000); + //empty and single-item compact images + assertEquals(Sketch.heapify(Memory.wrap(UpdateSketch.builder().build().compact().toByteArray())) + .getRetainedEntries(), 0); + assertEquals(Sketch.heapify(Memory.wrap(sketch(1).compact().toByteArray())).getRetainedEntries(), 1); + } + + @Test + public void checkCompactCountBeyondImage() { + final byte[] bytes = sketch(100).compact().toByteArray(); + ByteArrayUtil.putIntLE(bytes, CUR_COUNT_INT, 1 << 28); + checkRejected(bytes, CompactSketch::heapify); + checkRejected(bytes, Sketch::heapify); + checkRejected(bytes, mem -> CompactSketch.wrap(mem).getCache()); + final byte[] negative = sketch(100).compact().toByteArray(); + ByteArrayUtil.putIntLE(negative, CUR_COUNT_INT, -1); + checkRejected(negative, CompactSketch::heapify); + } + + @Test + public void checkCompressedCountBeyondImage() { + final byte[] bytes = sketch(100).compact().toByteArrayCompressed(); + final int numEntriesBytes = bytes[PreambleUtil.NUM_ENTRIES_BYTES_BYTE_V4]; + final int offset = (bytes[0] & 0x3F) << 3; + for (int i = 0; i < numEntriesBytes; i++) { bytes[offset + i] = (byte) 0xFF; } + checkRejected(bytes, CompactSketch::heapify); + checkRejected(bytes, Sketch::heapify); + checkRejected(bytes, mem -> CompactSketch.wrap(mem).getCache()); + final byte[] badBits = sketch(100).compact().toByteArrayCompressed(); + badBits[PreambleUtil.ENTRY_BITS_BYTE_V4] = 0; + checkRejected(badBits, CompactSketch::heapify); + } + + @Test + public void checkUpdatableLargeTable() { + for (final int lgArr : new int[] {28, 29, 30}) { //(8 << lgArr) overflows int + final byte[] bytes = sketch(100).toByteArray(); + bytes[LG_ARR_BYTE] = (byte) lgArr; + checkRejected(bytes, Sketches::heapifyUpdateSketch); + checkRejected(bytes, Sketch::heapify); + checkRejected(bytes, Sketch::wrap); + checkRejected(bytes, mem -> Sketches.wrapUpdateSketch(WritableMemory.writableWrap(bytes))); + } + final byte[] count = sketch(100).toByteArray(); + ByteArrayUtil.putIntLE(count, CUR_COUNT_INT, 1 << 28); + checkRejected(count, Sketches::heapifyUpdateSketch); + } + + @Test + public void checkUnionLargeTable() { + final Union union = SetOperation.builder().buildUnion(); + union.union(sketch(100)); + final byte[] bytes = union.toByteArray(); + bytes[LG_ARR_BYTE] = 30; + checkRejected(bytes, SetOperation::heapify); + checkRejected(bytes, mem -> Sketches.wrapUnion(mem).getResult()); + } + + @Test + public void checkIntersectionLargeTable() { + final Intersection inter = SetOperation.builder().buildIntersection(); + inter.intersect(sketch(100)); + final byte[] bytes = inter.toByteArray(); + bytes[LG_ARR_BYTE] = 30; + checkRejected(bytes, SetOperation::heapify); + checkRejected(bytes, mem -> Sketches.wrapIntersection(mem).getResult()); + final byte[] count = inter.toByteArray(); + ByteArrayUtil.putIntLE(count, CUR_COUNT_INT, 1 << 20); //more than the table holds + checkRejected(count, SetOperation::heapify); + } + + @Test + public void checkLegacySerVer1And2CountOverflow() { + //7.x only: (curCount + preLongs) << 3 overflowed int, so the size check passed + for (final int serVer : new int[] {1, 2}) { + final byte[] bytes = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN) + .put((byte) 3).put((byte) serVer).put((byte) 3).put(new byte[5]) + .putInt(0x1FFFFFFF).putInt(0).putLong(Long.MAX_VALUE / 2).array(); + checkRejected(bytes, CompactSketch::heapify); + checkRejected(bytes, Sketch::heapify); + final byte[] negative = bytes.clone(); + ByteArrayUtil.putIntLE(negative, CUR_COUNT_INT, -1); + checkRejected(negative, CompactSketch::heapify); + } + } +}