This is an automated email from the ASF dual-hosted git repository. garydgregory pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-compress.git
commit dd28f6b83ea8966fcf5d5f02731a1e7dc167d9a6 Author: Gary Gregory <[email protected]> AuthorDate: Thu Dec 3 07:25:19 2026 -0500 Reuse derived AES keys within each SevenZFile Share a bounded 32-entry cache between header and entry decoding. Clear cached keys on eviction, close, and construction failure. Document the capacity rationale and caching limitations. Add regression tests for key reuse, archive isolation, eviction, decoder compatibility, and cleanup. --- src/changes/changes.xml | 3 +- .../archivers/sevenz/AES256SHA256Decoder.java | 32 +- .../archivers/sevenz/AES256SHA256KeyCache.java | 152 +++++++++ .../commons/compress/archivers/sevenz/Coders.java | 5 +- .../compress/archivers/sevenz/SevenZFile.java | 77 +++-- .../archivers/sevenz/AES256SHA256KeyCacheTest.java | 147 +++++++++ .../sevenz/SevenZAES256SHA256DecoderTest.java | 157 +++++++++ .../archivers/sevenz/SevenZKeyCacheTest.java | 366 +++++++++++++++++++++ 8 files changed, 908 insertions(+), 31 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 85fcea613..ebb84ca2f 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -69,7 +69,8 @@ The <action> type attribute can be add,update,fix,remove. <action type="fix" dev="ggregory" due-to="Gary Gregory">[7-Zip] SevenZOutputFile now throws ArchiveException instead of IllegalArgumetException/IllegalStateException.</action> <action type="fix" dev="ggregory" due-to="Claude Security, Gary Gregory">[7-Zip] Correct substream memory accounting, enforce the configured memory limit, and reject missing substream sizes.</action> <action type="fix" dev="ggregory" due-to="Claude Security, Gary Gregory">[7-Zip] Enforce the configured memory limit on decoded header sizes before creating decoders, and close archive channels on I/O failures during construction.</action> - <action type="fix" dev="ggregory">[7-Zip] Use a fresh initialization vector for each encrypted entry and preserve per-entry metadata when entries are renamed.</action> + <action type="fix" dev="ggregory" due-to="Claude Security, Gary Gregory">[7-Zip] Use a fresh initialization vector for each encrypted entry and preserve per-entry metadata when entries are renamed.</action> + <action type="fix" dev="ggregory" due-to="Claude Security, Gary Gregory">[7-Zip] Reuse derived AES keys within each SevenZFile using a bounded cache shared by header and entry decoding, and clear cached keys on eviction and close.</action> <!-- FIX bzip2 --> <action type="fix" dev="ggregory" due-to="Tyler Nighswander, Gary Gregory">[BZip2] BZip2CompressorInputStream now throws CompressorException instead of IllegalArgumetException/IllegalStateException.</action> <action type="fix" dev="pkarwasz" due-to="Tyler Nighswander, Piotr P. Karwasz">[BZip2] BZip2 input streams treat Huffman codes longer than 20 bits as corrupted data, matching the behavior of the reference implementation.</action> diff --git a/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256Decoder.java b/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256Decoder.java index bf0b28fbc..f5e71d767 100644 --- a/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256Decoder.java +++ b/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256Decoder.java @@ -38,6 +38,7 @@ import org.apache.commons.compress.PasswordRequiredException; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.io.IOUtils; +import org.apache.commons.io.function.IOSupplier; final class AES256SHA256Decoder extends AbstractCoder { @@ -55,14 +56,20 @@ private static final class AES256SHA256DecoderInputStream extends InputStream { private final Coder coder; private final String archiveName; private final byte[] passwordBytes; + /** + * The archive-owned cache, or null for uncached decoding. + */ + private final AES256SHA256KeyCache keyCache; private boolean isInitialized; private CipherInputStream cipherInputStream; - private AES256SHA256DecoderInputStream(final InputStream in, final Coder coder, final String archiveName, final byte[] passwordBytes) { + private AES256SHA256DecoderInputStream(final InputStream in, final Coder coder, final String archiveName, final byte[] passwordBytes, + final AES256SHA256KeyCache keyCache) { this.in = in; this.coder = coder; this.archiveName = archiveName; this.passwordBytes = passwordBytes; + this.keyCache = keyCache; } @Override @@ -106,10 +113,11 @@ private CipherInputStream init() throws IOException { System.arraycopy(salt, 0, aesKeyBytes, 0, saltSize); System.arraycopy(passwordBytes, 0, aesKeyBytes, saltSize, Math.min(passwordBytes.length, aesKeyBytes.length - saltSize)); } else { - aesKeyBytes = sha256Password(passwordBytes, numCyclesPower, salt); + final IOSupplier<byte[]> deriveKey = () -> sha256Password(passwordBytes, numCyclesPower, salt); + aesKeyBytes = keyCache == null ? deriveKey.get() : keyCache.getKey(numCyclesPower, salt, deriveKey); } - final SecretKey aesKey = AES256Options.newSecretKeySpec(aesKeyBytes); try { + final SecretKey aesKey = AES256Options.newSecretKeySpec(aesKeyBytes); final Cipher cipher = Cipher.getInstance(AES256Options.TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv)); cipherInputStream = new CipherInputStream(in, cipher); @@ -117,6 +125,8 @@ private CipherInputStream init() throws IOException { return cipherInputStream; } catch (final GeneralSecurityException e) { throw new ArchiveException("Decryption error (Check JCE Unlimited Strength Jurisdiction Policy Files installation).", (Throwable) e); + } finally { + Arrays.fill(aesKeyBytes, (byte) 0); } } @@ -248,7 +258,21 @@ static byte[] utf16Decode(final char[] chars) { @Override InputStream decode(final String archiveName, final InputStream in, final long uncompressedLength, final Coder coder, final byte[] passwordBytes, final int maxMemoryLimitKiB) { - return new AES256SHA256DecoderInputStream(in, coder, archiveName, passwordBytes); + return decode(archiveName, in, coder, passwordBytes, null); + } + + /** + * Creates a decoder using the owning archive's key cache. + * + * @param archiveName the archive name used in error messages. + * @param in the encrypted input. + * @param coder the AES coder properties. + * @param passwordBytes the archive's fixed password, encoded as UTF-16LE, or null if none was supplied. + * @param keyCache the archive's key cache, or null to derive keys without caching. + * @return a stream that initializes decryption on its first read. + */ + InputStream decode(final String archiveName, final InputStream in, final Coder coder, final byte[] passwordBytes, final AES256SHA256KeyCache keyCache) { + return new AES256SHA256DecoderInputStream(in, coder, archiveName, passwordBytes, keyCache); } @Override diff --git a/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256KeyCache.java b/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256KeyCache.java new file mode 100644 index 000000000..7f8bbf73d --- /dev/null +++ b/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256KeyCache.java @@ -0,0 +1,152 @@ +/* + * 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 + * + * https://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.commons.compress.archivers.sevenz; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.commons.compress.archivers.ArchiveException; +import org.apache.commons.io.function.IOSupplier; + +/** + * Caches derived AES keys for the fixed password of one {@link SevenZFile}. + * + * <p> + * Header and entry decoding share at most 32 keys, indexed by salt contents and the base-2 logarithm of the KDF round count. Least recently used keys are + * evicted when the cache is full. Repeated inputs avoid derivation only while their keys remain cached; this does not bound the total derivation work. + * The decoder bypasses this cache for the special {@code 0x3f} key construction, which does not use the iterative KDF. + * </p> + * + * <p> + * Eviction and closure overwrite the cache's key arrays as a best effort to reduce retention. Copies held by callers or cryptographic providers are outside + * this cache's control. Like its owning archive, this class is not thread-safe. + * </p> + */ +final class AES256SHA256KeyCache implements AutoCloseable { + + /** + * Identifies the derivation inputs other than the archive's fixed password. + */ + private static final class Key { + + /** + * The base-2 logarithm of the KDF round count. + */ + private final int numCyclesPower; + + /** + * A private copy of the salt. + */ + private final byte[] salt; + + /** + * Constructs a key from the derivation inputs. + * + * @param numCyclesPower the base-2 logarithm of the KDF round count. + * @param salt the salt to copy. + */ + private Key(final int numCyclesPower, final byte[] salt) { + this.numCyclesPower = numCyclesPower; + this.salt = salt.clone(); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof Key)) { + return false; + } + final Key other = (Key) obj; + return numCyclesPower == other.numCyclesPower && Arrays.equals(salt, other.salt); + } + + @Override + public int hashCode() { + return 31 * numCyclesPower + Arrays.hashCode(salt); + } + } + + /** + * The maximum number of derived keys retained per archive. + * + * <p> + * A fixed capacity of 32 permits reuse across multiple derivation inputs while limiting retained AES-256 key bytes to 1 KiB, excluding salts and object + * overhead. The entry count follows the precedent of 7-Zip's global key cache, although this cache is scoped to one archive. This is a pragmatic cache + * policy choice, not a 7z format requirement or a bound on total derivation work. Revisiting more than 32 inputs can cause repeated eviction and + * derivation. + * </p> + */ + private static final int MAX_ENTRIES = 32; + + /** + * Keys ordered from least to most recently accessed. + */ + private final Map<Key, byte[]> keys = new LinkedHashMap<>(MAX_ENTRIES, 0.75f, true); + + /** + * Whether this cache has been closed. + */ + private boolean closed; + + /** + * Constructs an empty cache. + */ + AES256SHA256KeyCache() { + // No key material is retained until the first derivation. + } + + @Override + public void close() { + closed = true; + keys.values().forEach(key -> Arrays.fill(key, (byte) 0)); + keys.clear(); + } + + /** + * Gets a copy of a cached key, deriving and retaining it on a cache miss. + * + * @param numCyclesPower the base-2 logarithm of the KDF round count. + * @param salt the derivation salt. + * @param deriveKey supplies a newly allocated key for these inputs and the archive's fixed password; ownership of that array transfers to this cache. + * @return a copy of the derived key that the caller may modify. + * @throws IOException if this cache is closed or derivation fails. + */ + byte[] getKey(final int numCyclesPower, final byte[] salt, final IOSupplier<byte[]> deriveKey) throws IOException { + if (closed) { + throw new ArchiveException("AES key cache is closed"); + } + final Key key = new Key(numCyclesPower, salt); + byte[] value = keys.get(key); + if (value == null) { + value = deriveKey.get(); + if (keys.size() == MAX_ENTRIES) { + final Iterator<byte[]> iterator = keys.values().iterator(); + Arrays.fill(iterator.next(), (byte) 0); + iterator.remove(); + } + keys.put(key, value); + } + return value.clone(); + } +} diff --git a/src/main/java/org/apache/commons/compress/archivers/sevenz/Coders.java b/src/main/java/org/apache/commons/compress/archivers/sevenz/Coders.java index 92e20d2dc..453954175 100644 --- a/src/main/java/org/apache/commons/compress/archivers/sevenz/Coders.java +++ b/src/main/java/org/apache/commons/compress/archivers/sevenz/Coders.java @@ -224,11 +224,14 @@ OutputStream encode(final OutputStream out, final Object options) { }; static InputStream addDecoder(final String archiveName, final InputStream is, final long uncompressedLength, final Coder coder, final byte[] password, - final int maxMemoryLimitKiB) throws IOException { + final int maxMemoryLimitKiB, final AES256SHA256KeyCache keyCache) throws IOException { final AbstractCoder cb = findByMethod(SevenZMethod.byId(coder.decompressionMethodId)); if (cb == null) { throw new ArchiveException("Unsupported compression method %s used in '%s'", Arrays.toString(coder.decompressionMethodId), archiveName); } + if (cb instanceof AES256SHA256Decoder) { + return ((AES256SHA256Decoder) cb).decode(archiveName, is, coder, password, keyCache); + } return cb.decode(archiveName, is, uncompressedLength, coder, password, maxMemoryLimitKiB); } diff --git a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java index a04179321..d5ae6b326 100644 --- a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java +++ b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java @@ -50,6 +50,7 @@ import org.apache.commons.io.function.IOStream; import org.apache.commons.io.input.BoundedInputStream; import org.apache.commons.io.input.ChecksumInputStream; +import org.apache.commons.lang3.ArrayFill; import org.apache.commons.lang3.ArrayUtils; /** @@ -623,6 +624,10 @@ private static int toNonNegativeInt(final String description, final long value) private int currentFolderIndex = -1; private InputStream currentFolderInputStream; private byte[] password; + /** + * Derived keys shared by this archive's encrypted header and entries. + */ + private final AES256SHA256KeyCache keyCache; private long compressedBytesReadFromCurrentEntry; private long uncompressedBytesReadFromCurrentEntry; private final ArrayList<InputStream> deferredBlockStreams = new ArrayList<>(); @@ -634,20 +639,36 @@ private static int toNonNegativeInt(final String description, final long value) private final int maxEntryNameLength; private SevenZFile(final Builder builder) throws IOException { - this.channel = builder.getChannel(SeekableByteChannel.class); + this(builder, new AES256SHA256KeyCache()); + } + + /** + * Opens an archive with an empty key cache whose ownership transfers to this archive. + * + * @param builder the source and decoding options. + * @param keyCache the cache shared by header and entry decoding and closed with this archive. + * @throws IOException if opening or reading the archive fails. + */ + SevenZFile(final Builder builder, final AES256SHA256KeyCache keyCache) throws IOException { + this.keyCache = keyCache; try { - this.fileName = builder.getName(); - this.maxEntryNameLength = builder.getMaxEntryNameLength(); - this.maxMemoryLimitKiB = builder.getMemoryLimitKiB(); - this.useDefaultNameForUnnamedEntries = builder.useDefaultNameForUnnamedEntries; - this.tryToRecoverBrokenArchives = builder.tryToRecoverBrokenArchives; - final byte[] password = builder.password; - archive = readHeaders(password); - this.password = password != null ? Arrays.copyOf(password, password.length) : null; - } catch (final IOException e) { - throw IOUtils.closeQuietlySuppress(channel, e); - } catch (final ArithmeticException | IllegalArgumentException e) { - throw IOUtils.closeQuietlySuppress(channel, new ArchiveException(e)); + this.channel = builder.getChannel(SeekableByteChannel.class); + try { + this.fileName = builder.getName(); + this.maxEntryNameLength = builder.getMaxEntryNameLength(); + this.maxMemoryLimitKiB = builder.getMemoryLimitKiB(); + this.useDefaultNameForUnnamedEntries = builder.useDefaultNameForUnnamedEntries; + this.tryToRecoverBrokenArchives = builder.tryToRecoverBrokenArchives; + final byte[] password = builder.password; + this.password = password != null ? Arrays.copyOf(password, password.length) : null; + archive = readHeaders(this.password); + } catch (final ArithmeticException | IllegalArgumentException e) { + // Preserve the channel provider's exception types by translating only failures after opening the source. + throw new ArchiveException(e); + } + } catch (final IOException | RuntimeException | Error e) { + IOUtils.closeQuietlySuppress(this::closeResources, e); + throw e; } } @@ -937,7 +958,7 @@ public int read(final byte[] b, final int off, final int len) throws IOException throw new ArchiveException("Multi input/output stream coders are not yet supported"); } final SevenZMethod method = SevenZMethod.byId(coder.decompressionMethodId); - inputStreamStack = Coders.addDecoder(fileName, inputStreamStack, folder.getUnpackSizeForCoder(coder), coder, password, maxMemoryLimitKiB); + inputStreamStack = Coders.addDecoder(fileName, inputStreamStack, folder.getUnpackSizeForCoder(coder), coder, password, maxMemoryLimitKiB, keyCache); methods.addFirst(new SevenZMethodConfiguration(method, Coders.findByMethod(method).getOptionsFromCoder(coder, inputStreamStack))); } entry.setContentMethods(methods); @@ -1085,16 +1106,22 @@ private void calculateStreamMap(final Archive archive) throws CompressException */ @Override public void close() throws IOException { - if (channel != null) { - try { - channel.close(); - } finally { - channel = null; - if (password != null) { - Arrays.fill(password, (byte) 0); - } - password = null; - } + closeResources(); + } + + /** + * Closes the channel and clears owned key material, including when construction fails. + * + * @throws IOException if closing the channel fails. + */ + private void closeResources() throws IOException { + try { + IOUtils.close(channel); + } finally { + channel = null; + ArrayFill.clear(password); + password = null; + keyCache.close(); } } @@ -1434,7 +1461,7 @@ private ByteBuffer readEncodedHeader(final ByteBuffer header, final Archive arch throw new ArchiveException("Multi input/output stream coders are not yet supported"); } inputStreamStack = Coders.addDecoder(fileName, inputStreamStack, // NOSONAR - folder.getUnpackSizeForCoder(coder), coder, password, maxMemoryLimitKiB); + folder.getUnpackSizeForCoder(coder), coder, password, maxMemoryLimitKiB, keyCache); } if (folder.hasCrc) { // @formatter:off diff --git a/src/test/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256KeyCacheTest.java b/src/test/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256KeyCacheTest.java new file mode 100644 index 000000000..6e8de1dd8 --- /dev/null +++ b/src/test/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256KeyCacheTest.java @@ -0,0 +1,147 @@ +/* + * 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 + * + * https://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.commons.compress.archivers.sevenz; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.commons.compress.archivers.ArchiveException; +import org.apache.commons.io.function.IOSupplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Tests bounded key reuse, defensive copies, and explicit key cleanup. + */ +class AES256SHA256KeyCacheTest { + + @Test + void testCloseClearsOwnedKeysAndPreventsReuse() throws IOException { + final byte[] owned = {1, 2, 3}; + final AES256SHA256KeyCache cache = new AES256SHA256KeyCache(); + final byte[] copy = cache.getKey(1, new byte[0], () -> owned); + cache.close(); + cache.close(); + assertArrayEquals(new byte[owned.length], owned); + assertArrayEquals(new byte[] {1, 2, 3}, copy); + assertThrows(ArchiveException.class, () -> cache.getKey(1, new byte[0], () -> fail("Must not derive after close"))); + } + + @Test + void testCyclingMoreTuplesThanCapacity() throws IOException { + final AtomicInteger derivations = new AtomicInteger(); + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + for (int i = 0; i < 99; i++) { + cache.getKey(1, new byte[] {(byte) (i % 33)}, () -> { + derivations.incrementAndGet(); + return new byte[32]; + }); + } + assertEquals(99, derivations.get()); + } + } + + @Test + void testDistinctInputsAndSaltCopy() throws IOException { + final AtomicInteger derivations = new AtomicInteger(); + final IOSupplier<byte[]> derive = () -> new byte[] {(byte) derivations.incrementAndGet()}; + final byte[] salt = {0, 31}; + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + assertArrayEquals(new byte[] {1}, cache.getKey(1, salt, derive)); + salt[0] = 1; + salt[1] = 0; // Same Arrays.hashCode as {0, 31}, but a different salt. + assertArrayEquals(new byte[] {2}, cache.getKey(1, salt, derive)); + assertArrayEquals(new byte[] {3}, cache.getKey(2, salt, derive)); + assertArrayEquals(new byte[] {1}, cache.getKey(1, new byte[] {0, 31}, derive)); + assertEquals(3, derivations.get()); + } + } + + @Test + void testEvictionClearsLeastRecentlyUsedKey() throws IOException { + final List<byte[]> owned = new ArrayList<>(); + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + for (int i = 0; i < 32; i++) { + final byte[] value = {(byte) (i + 1)}; + owned.add(value); + cache.getKey(1, new byte[] {(byte) i}, () -> value); + } + final byte[] firstCopy = cache.getKey(1, new byte[] {0}, () -> fail("Expected cache hit")); + cache.getKey(1, new byte[] {32}, () -> new byte[] {33}); + assertArrayEquals(new byte[] {0}, owned.get(1)); + assertArrayEquals(new byte[] {1}, owned.get(0)); + assertArrayEquals(new byte[] {1}, firstCopy); + assertArrayEquals(new byte[] {99}, cache.getKey(1, new byte[] {1}, () -> new byte[] {99})); + assertArrayEquals(new byte[] {0}, owned.get(2)); + } + for (final byte[] value : owned) { + assertArrayEquals(new byte[value.length], value); + } + } + + @ParameterizedTest + @ValueSource(ints = {0, 32}) + void testFailedDerivationDoesNotEvictOrCache(final int initialSize) throws IOException { + final IOException failure = new IOException("Derivation failed"); + final List<byte[]> owned = new ArrayList<>(); + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + for (int i = 0; i < initialSize; i++) { + final byte[] value = {(byte) (i + 1)}; + owned.add(value); + cache.getKey(1, new byte[] {(byte) i}, () -> value); + } + assertSame(failure, assertThrows(IOException.class, () -> cache.getKey(1, new byte[] {32}, () -> { + throw failure; + }))); + for (int i = 0; i < initialSize; i++) { + assertArrayEquals(new byte[] {(byte) (i + 1)}, owned.get(i)); + assertArrayEquals(owned.get(i), cache.getKey(1, new byte[] {(byte) i}, () -> fail("Failed derivation must not evict existing keys"))); + } + assertArrayEquals(new byte[] {42}, cache.getKey(1, new byte[] {32}, () -> new byte[] {42})); + } + } + + @Test + void testIdenticalInputsDeriveOnceAndReturnCopies() throws IOException { + final AtomicInteger derivations = new AtomicInteger(); + final IOSupplier<byte[]> derive = () -> { + derivations.incrementAndGet(); + return new byte[] {42}; + }; + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + final byte[] first = cache.getKey(19, new byte[] {1}, derive); + first[0] = 0; + for (int i = 0; i < 50; i++) { + final byte[] copy = cache.getKey(19, new byte[] {1}, derive); + assertArrayEquals(new byte[] {42}, copy); + copy[0] = 0; + } + assertEquals(1, derivations.get()); + } + } +} diff --git a/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZAES256SHA256DecoderTest.java b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZAES256SHA256DecoderTest.java index e9f9a0d68..8dc0bd345 100644 --- a/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZAES256SHA256DecoderTest.java +++ b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZAES256SHA256DecoderTest.java @@ -19,16 +19,28 @@ package org.apache.commons.compress.archivers.sevenz; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicInteger; +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; + +import org.apache.commons.compress.PasswordRequiredException; import org.apache.commons.compress.archivers.ArchiveException; +import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Tests for class {@link AES256SHA256Decoder}. @@ -37,6 +49,94 @@ **/ class SevenZAES256SHA256DecoderTest { + /** + * Creates AES properties with a one-byte salt and an implicit zero IV. + * + * @param numCyclesPower the encoded base-2 logarithm of the KDF round count, or {@code 0x3f} for the special construction. + * @return the coder. + */ + private static Coder coder(final int numCyclesPower) { + return coder(numCyclesPower, new byte[] {42}, new byte[0]); + } + + /** + * Creates AES properties for the given derivation inputs and IV. + * + * @param numCyclesPower the encoded base-2 logarithm of the KDF round count, or {@code 0x3f} for the special construction. + * @param salt the salt, at most 16 bytes. + * @param iv the IV, at most 16 bytes. + * @return the coder. + */ + private static Coder coder(final int numCyclesPower, final byte[] salt, final byte[] iv) { + final byte[] properties = new byte[2 + salt.length + iv.length]; + properties[0] = (byte) (numCyclesPower | (salt.length == 0 ? 0 : 0x80) | (iv.length == 0 ? 0 : 0x40)); + properties[1] = (byte) ((salt.length == 0 ? 0 : (salt.length - 1) << 4) | (iv.length == 0 ? 0 : iv.length - 1)); + System.arraycopy(salt, 0, properties, 2, salt.length); + System.arraycopy(iv, 0, properties, 2 + salt.length, iv.length); + return new Coder(SevenZMethod.AES256SHA256.getId(), 1, 1, properties); + } + + /** + * Encrypts one block with a known key for decoder comparisons. + * + * @param key the AES key. + * @param iv the full 16-byte IV. + * @return the encrypted block. + * @throws GeneralSecurityException if encryption fails. + */ + private static byte[] encrypt(final byte[] key, final byte[] iv) throws GeneralSecurityException { + final Cipher cipher = Cipher.getInstance(AES256Options.TRANSFORMATION); + cipher.init(Cipher.ENCRYPT_MODE, AES256Options.newSecretKeySpec(key), new IvParameterSpec(iv)); + return cipher.doFinal(new byte[16]); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 19, 24}) + void testCachedDerivationMatchesUncached(final int numCyclesPower) throws Exception { + final byte[] password = {1, 2, 3}; + final byte[] expected = AES256SHA256Decoder.sha256Password(password, numCyclesPower, new byte[] {42}); + final byte[] encrypted = encrypt(expected, new byte[16]); + final AES256SHA256Decoder decoder = new AES256SHA256Decoder(); + try (InputStream in = decoder.decode("test", new ByteArrayInputStream(encrypted), 16, coder(numCyclesPower), password, Integer.MAX_VALUE)) { + assertArrayEquals(new byte[16], IOUtils.toByteArray(in)); + } + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + for (int i = 0; i < 2; i++) { + try (InputStream in = decoder.decode("test", new ByteArrayInputStream(encrypted), coder(numCyclesPower), password, cache)) { + assertArrayEquals(new byte[16], IOUtils.toByteArray(in)); + } + } + assertArrayEquals(expected, cache.getKey(numCyclesPower, new byte[] {42}, () -> { + throw new IOException("Expected a cache hit"); + })); + } + } + + @Test + void testCacheSeparatesDerivationInputs() throws Exception { + final byte[] password = {1, 2, 3}; + final byte[][] salts = {{}, {42}, {43}, new byte[16]}; + final byte[][] ivs = {{}, {7}, new byte[16]}; + Arrays.fill(ivs[2], (byte) 7); + final AES256SHA256Decoder decoder = new AES256SHA256Decoder(); + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + for (int repeat = 0; repeat < 2; repeat++) { + for (final byte[] salt : salts) { + for (final int numCyclesPower : new int[] {1, 2}) { + final byte[] key = AES256SHA256Decoder.sha256Password(password, numCyclesPower, salt); + for (final byte[] iv : ivs) { + final byte[] encrypted = encrypt(key, Arrays.copyOf(iv, 16)); + final Coder coder = coder(numCyclesPower, salt, iv); + try (InputStream in = decoder.decode("test", new ByteArrayInputStream(encrypted), coder, password, cache)) { + assertArrayEquals(new byte[16], IOUtils.toByteArray(in)); + } + } + } + } + } + } + } + @Test void testDecodeWithNonEmptyString() throws IOException { final AES256SHA256Decoder aES256SHA256Decoder = new AES256SHA256Decoder(); @@ -52,4 +152,61 @@ void testDecodeWithNonEmptyString() throws IOException { } } } + + @Test + void testMalformedProperties() throws IOException { + final AES256SHA256Decoder decoder = new AES256SHA256Decoder(); + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + for (final byte[] properties : new byte[][] {null, {}, {0}, {(byte) 0x80, 0}}) { + final Coder coder = new Coder(SevenZMethod.AES256SHA256.getId(), 1, 1, properties); + try (InputStream in = decoder.decode("test", new ByteArrayInputStream(new byte[0]), coder, new byte[] {1}, cache)) { + assertThrows(ArchiveException.class, in::read); + } + } + } + } + + @Test + void testMissingPasswordCannotUseCachedKey() throws IOException { + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + cache.getKey(1, new byte[] {42}, () -> new byte[32]); + final AES256SHA256Decoder decoder = new AES256SHA256Decoder(); + try (InputStream in = decoder.decode("test", new ByteArrayInputStream(new byte[0]), coder(1), null, cache)) { + assertThrows(PasswordRequiredException.class, in::read); + } + } + } + + @Test + void testSpecialDerivationBypassesCache() throws Exception { + final byte[] password = {1, 2, 3}; + final byte[] expected = new byte[32]; + expected[0] = 42; + System.arraycopy(password, 0, expected, 1, password.length); + final byte[] encrypted = encrypt(expected, new byte[16]); + final AtomicInteger derivations = new AtomicInteger(); + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + final AES256SHA256Decoder decoder = new AES256SHA256Decoder(); + try (InputStream in = decoder.decode("test", new ByteArrayInputStream(encrypted), coder(0x3f), password, cache)) { + assertArrayEquals(new byte[16], IOUtils.toByteArray(in)); + } + cache.getKey(0x3f, new byte[] {42}, () -> { + derivations.incrementAndGet(); + return expected; + }); + assertEquals(1, derivations.get()); + } + } + + @ParameterizedTest + @ValueSource(ints = {25, 32, 62}) + void testUnsupportedCyclesRejectedBeforeDerivation(final int numCyclesPower) throws IOException { + try (AES256SHA256KeyCache cache = new AES256SHA256KeyCache()) { + final AES256SHA256Decoder decoder = new AES256SHA256Decoder(); + try (InputStream in = decoder.decode("test", new ByteArrayInputStream(new byte[0]), coder(numCyclesPower), new byte[] {1}, cache)) { + final ArchiveException exception = assertThrows(ArchiveException.class, in::read); + assertEquals("numCyclesPower " + numCyclesPower + " exceeds supported limit (24) in 'test'", exception.getMessage()); + } + } + } } diff --git a/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZKeyCacheTest.java b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZKeyCacheTest.java new file mode 100644 index 000000000..d255566b2 --- /dev/null +++ b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZKeyCacheTest.java @@ -0,0 +1,366 @@ +/* + * 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 + * + * https://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.commons.compress.archivers.sevenz; + +import static org.apache.commons.lang3.reflect.FieldUtils.readDeclaredField; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.channels.Channel; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; + +import org.apache.commons.compress.AbstractTest; +import org.apache.commons.compress.archivers.ArchiveException; +import org.apache.commons.io.channels.ByteArraySeekableByteChannel; +import org.apache.commons.io.channels.FilterSeekableByteChannel; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Tests archive ownership, header and entry key reuse, and cleanup on success and failure. + */ +class SevenZKeyCacheTest extends AbstractTest { + + /** + * Gets the cache of an open archive. + * + * @param file the archive. + * @return the archive's cache. + * @throws IllegalAccessException if the test cannot access the field. + */ + private static AES256SHA256KeyCache cache(final SevenZFile file) throws IllegalAccessException { + return (AES256SHA256KeyCache) readDeclaredField(file, "keyCache", true); + } + + /** + * Gets the cache's owned arrays for testing their lifecycle. + * + * @param cache the cache. + * @return the map retaining the derived keys. + * @throws IllegalAccessException if the test cannot access the field. + */ + private static Map<?, ?> keys(final AES256SHA256KeyCache cache) throws IllegalAccessException { + return (Map<?, ?>) readDeclaredField(cache, "keys", true); + } + + /** + * Supplies failures that can occur after header key derivation. + * + * @return the failures to inject. + */ + static Stream<Throwable> constructionFailures() { + return Stream.of(new IOException("read"), new ArithmeticException("read"), new IllegalArgumentException("read"), + new IllegalStateException("read"), new AssertionError("read")); + } + + /** + * Supplies channel-opening failures that must retain their original exception types. + * + * @return the failures to inject. + */ + static Stream<RuntimeException> channelAcquisitionFailures() { + return Stream.of(new IllegalArgumentException("open"), new ArithmeticException("open")); + } + + /** + * Reads the current entry completely, including checksum verification. + * + * @param file the archive positioned at the entry. + * @return the entry contents. + * @throws IOException if reading or checksum verification fails. + */ + private static byte[] readEntry(final SevenZFile file) throws IOException { + final UnsynchronizedByteArrayOutputStream out = UnsynchronizedByteArrayOutputStream.builder().get(); + final byte[] buffer = new byte[128]; + int count; + while ((count = file.read(buffer)) != -1) { + out.write(buffer, 0, count); + } + return out.toByteArray(); + } + + @Test + void testBuilderReuseKeepsArchivesIndependent() throws Exception { + final SevenZFile.Builder builder = SevenZFile.builder().setPath(getPath("bla.encrypted.7z")).setPassword("foo"); + final byte[] builderPassword = (byte[]) readDeclaredField(builder, "password", true); + final byte[] expectedPassword = builderPassword.clone(); + try (SevenZFile first = builder.get(); SevenZFile second = builder.get()) { + final AES256SHA256KeyCache firstCache = cache(first); + final AES256SHA256KeyCache secondCache = cache(second); + assertNotSame(firstCache, secondCache); + final byte[] firstKey = (byte[]) keys(firstCache).values().iterator().next(); + final byte[] secondKey = (byte[]) keys(secondCache).values().iterator().next(); + assertNotSame(firstKey, secondKey); + assertArrayEquals(firstKey, secondKey); + first.close(); + assertArrayEquals(new byte[firstKey.length], firstKey); + assertFalse(Arrays.equals(new byte[secondKey.length], secondKey)); + assertNotNull(second.getNextEntry()); + assertTrue(readEntry(second).length > 0); + } + assertArrayEquals(expectedPassword, builderPassword); + } + + @ParameterizedTest + @MethodSource("channelAcquisitionFailures") + void testChannelAcquisitionFailureClosesCache(final RuntimeException failure) throws IOException { + final AES256SHA256KeyCache cache = new AES256SHA256KeyCache(); + final SevenZFile.Builder builder = new SevenZFile.Builder() { + @Override + public <C extends Channel> C getChannel(final Class<C> channelType) { + throw failure; + } + }; + assertSame(failure, assertThrows(failure.getClass(), () -> new SevenZFile(builder, cache).close())); + assertThrows(ArchiveException.class, () -> cache.getKey(19, new byte[0], () -> fail("Failed opening must close its cache"))); + } + + @Test + void testInvalidOpenOptionsPreserveExceptionType() throws IOException { + final Path path = writeArchive("invalid-options.7z", "foo", 1); + assertThrows(IllegalArgumentException.class, () -> SevenZFile.builder().setPath(path) + .setOpenOptions(StandardOpenOption.READ, StandardOpenOption.APPEND).get().close()); + } + + @Test + void testCloseFailureStillClearsPasswordAndKeys() throws Exception { + final IOException closeFailure = new IOException("close"); + final ByteArraySeekableByteChannel delegate = ByteArraySeekableByteChannel.wrap(readAllBytes("bla.encrypted.7z")); + final FilterSeekableByteChannel<ByteArraySeekableByteChannel> channel = new FilterSeekableByteChannel<ByteArraySeekableByteChannel>(delegate) { + @Override + public void close() throws IOException { + super.close(); + throw closeFailure; + } + }; + final SevenZFile file = SevenZFile.builder().setChannel(channel).setPassword("foo").get(); + final AES256SHA256KeyCache cache = cache(file); + final byte[] password = (byte[]) readDeclaredField(file, "password", true); + final byte[] key = (byte[]) keys(cache).values().iterator().next(); + assertSame(closeFailure, assertThrows(IOException.class, file::close)); + file.close(); + assertFalse(delegate.isOpen()); + assertNull(readDeclaredField(file, "password", true)); + assertArrayEquals(new byte[password.length], password); + assertArrayEquals(new byte[key.length], key); + assertTrue(keys(cache).isEmpty()); + assertThrows(ArchiveException.class, () -> cache.getKey(19, new byte[0], () -> fail("Closed cache must not derive"))); + } + + @ParameterizedTest + @MethodSource("constructionFailures") + void testConstructionFailureClearsDerivedKeys(final Throwable failure) throws Exception { + final AES256SHA256KeyCache cache = new AES256SHA256KeyCache(); + final Map<?, ?> keys = keys(cache); + final AtomicReference<byte[]> retained = new AtomicReference<>(); + final IOException closeFailure = new IOException("close"); + final ByteArraySeekableByteChannel delegate = ByteArraySeekableByteChannel.wrap(readAllBytes("bla.encrypted.7z")); + final FilterSeekableByteChannel<ByteArraySeekableByteChannel> channel = new FilterSeekableByteChannel<ByteArraySeekableByteChannel>(delegate) { + @Override + public void close() throws IOException { + super.close(); + throw closeFailure; + } + + @Override + public int read(final ByteBuffer dst) throws IOException { + if (!keys.isEmpty()) { + retained.set((byte[]) keys.values().iterator().next()); + if (failure instanceof IOException) { + throw (IOException) failure; + } + if (failure instanceof RuntimeException) { + throw (RuntimeException) failure; + } + throw (Error) failure; + } + return super.read(dst); + } + }; + final SevenZFile.Builder builder = SevenZFile.builder().setChannel(channel).setPassword("foo"); + final byte[] builderPassword = ((byte[]) readDeclaredField(builder, "password", true)).clone(); + final Class<? extends Throwable> expected = failure instanceof ArithmeticException || failure instanceof IllegalArgumentException + ? ArchiveException.class : failure.getClass(); + final Throwable thrown = assertThrows(expected, () -> new SevenZFile(builder, cache) { + @Override + public void close() { + fail("Constructor cleanup must not call an override on a partially constructed archive"); + } + }.close()); + if (expected == ArchiveException.class) { + assertSame(failure, thrown.getCause()); + } else { + assertSame(failure, thrown); + } + assertEquals(1, thrown.getSuppressed().length); + assertSame(closeFailure, thrown.getSuppressed()[0]); + assertNotNull(retained.get(), "Failure must occur after key derivation"); + assertArrayEquals(new byte[retained.get().length], retained.get()); + assertTrue(keys.isEmpty()); + assertFalse(delegate.isOpen()); + assertArrayEquals(builderPassword, (byte[]) readDeclaredField(builder, "password", true)); + assertThrows(ArchiveException.class, () -> cache.getKey(19, new byte[0], () -> fail("Failed archive must close its cache"))); + } + + @Test + void testEncryptedHeaderAndEntriesShareKey() throws Exception { + final SevenZFile.Builder builder = SevenZFile.builder().setPath(getPath("bla.encrypted.7z")).setPassword("foo"); + final AES256SHA256KeyCache cache = new AES256SHA256KeyCache(); + final byte[] key; + try (SevenZFile file = new SevenZFile(builder, cache)) { + final Map<?, ?> keys = keys(cache); + assertEquals(1, keys.size()); + key = (byte[]) keys.values().iterator().next(); + while (file.getNextEntry() != null) { + readEntry(file); + assertEquals(1, keys.size()); + assertSame(key, keys.values().iterator().next(), "Matching entry inputs must reuse the header's derived key"); + } + } + assertArrayEquals(new byte[key.length], key); + assertTrue(keys(cache).isEmpty()); + } + + @Test + void testFiftyFoldersShareKey() throws Exception { + final Path path = writeArchive("cached-keys.7z", "foo", 50); + final byte[] data = {1, 2, 3}; + try (SevenZFile file = SevenZFile.builder().setPath(path).setPassword("foo").get()) { + final Map<?, ?> keys = keys(cache(file)); + assertTrue(keys.isEmpty()); + byte[] key = null; + for (int i = 0; i < 50; i++) { + assertNotNull(file.getNextEntry()); + assertArrayEquals(data, readEntry(file)); + assertEquals(1, keys.size()); + final byte[] current = (byte[]) keys.values().iterator().next(); + if (key == null) { + key = current; + } else { + assertSame(key, current); + } + } + assertNull(file.getNextEntry()); + } + } + + @Test + void testIndependentArchivesReadConcurrently() throws Exception { + final ExecutorService executor = Executors.newFixedThreadPool(4); + try { + final List<Callable<byte[]>> readers = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + final String password = "password-" + i; + final Path path = writeArchive("concurrent-" + i + ".7z", password, 1); + readers.add(() -> { + try (SevenZFile file = SevenZFile.builder().setPath(path).setPassword(password).get()) { + assertNotNull(file.getNextEntry()); + return readEntry(file); + } + }); + } + final List<Future<byte[]>> results = executor.invokeAll(readers, 10, TimeUnit.SECONDS); + for (final Future<byte[]> result : results) { + assertArrayEquals(new byte[] {1, 2, 3}, result.get()); + } + } finally { + executor.shutdownNow(); + } + } + + @Test + void testClosedArchiveCannotPopulateCache() throws Exception { + final Path path = writeArchive("closed.7z", "foo", 1); + try (SevenZFile file = SevenZFile.builder().setPath(path).setPassword("foo").get()) { + final Map<?, ?> keys = keys(cache(file)); + final SevenZArchiveEntry entry = file.getNextEntry(); + try (InputStream in = file.getInputStream(entry)) { + assertTrue(keys.isEmpty()); + file.close(); + assertThrows(IOException.class, in::read); + assertTrue(keys.isEmpty()); + } + } + } + + @Test + void testWrongPasswordCannotReuseAnotherArchivesKey() throws Exception { + final SevenZFile.Builder builder = SevenZFile.builder().setPath(getPath("bla.encrypted.7z")).setPassword("foo"); + try (SevenZFile file = builder.get()) { + assertNotNull(file.getNextEntry()); + assertTrue(readEntry(file).length > 0); + } + builder.setPassword("wrong"); + assertThrows(IOException.class, () -> builder.get().close()); + builder.setPassword("foo"); + try (SevenZFile file = builder.get()) { + assertNotNull(file.getNextEntry()); + assertTrue(readEntry(file).length > 0); + } + } + + /** + * Writes independently encrypted folders sharing derivation inputs. + * + * @param name the archive file name. + * @param password the password. + * @param count the number of folders. + * @return the archive path. + * @throws IOException if writing fails. + */ + private Path writeArchive(final String name, final String password, final int count) throws IOException { + final Path path = newTempPath(name); + try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), password.toCharArray())) { + out.setContentCompression(SevenZMethod.COPY); + for (int i = 0; i < count; i++) { + final SevenZArchiveEntry entry = new SevenZArchiveEntry(); + entry.setName("entry-" + i); + out.putArchiveEntry(entry); + out.write(new byte[] {1, 2, 3}); + out.closeArchiveEntry(); + } + } + return path; + } +}
