This is an automated email from the ASF dual-hosted git repository.

pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git


The following commit(s) were added to refs/heads/trunk by this push:
     new d1d3f6b102 AgileDecryptor: allow decrypting a package whose integrity 
check fails (#1474)
d1d3f6b102 is described below

commit d1d3f6b1026279d487a8d36ce029bf34664d6910
Author: PJ Fanning <[email protected]>
AuthorDate: Sat Oct 24 23:40:46 2026 +0100

    AgileDecryptor: allow decrypting a package whose integrity check fails 
(#1474)
    
    Follow-up to #1465. A DataIntegrity HMAC mismatch still fails by default,
    but AgileDecryptor.setFailOnIntegrityError(false) logs a warning and
    decrypts the package anyway. Excel for the web flags such a file but still
    shows it in read-only mode, so read-only consumers can get the content too.
    
    Also document the exception on getDataStream, name the setting in the
    exception message, and test a file where only the HMAC value is altered.
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../poi/poifs/crypt/agile/AgileDecryptor.java      | 44 ++++++++++++++++++--
 .../poi/poifs/crypt/agile/TestAgileDecryptor.java  | 48 ++++++++++++++++++++++
 2 files changed, 89 insertions(+), 3 deletions(-)

diff --git 
a/poi/src/main/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java 
b/poi/src/main/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java
index 05927b135b..b5c1d769e0 100644
--- a/poi/src/main/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java
+++ b/poi/src/main/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java
@@ -38,7 +38,9 @@ import javax.crypto.spec.IvParameterSpec;
 import javax.crypto.spec.RC2ParameterSpec;
 import javax.crypto.spec.SecretKeySpec;
 
+import org.apache.logging.log4j.Logger;
 import org.apache.poi.EncryptedDocumentException;
+import org.apache.poi.logging.PoiLogManager;
 import org.apache.poi.poifs.crypt.ChainingMode;
 import org.apache.poi.poifs.crypt.ChunkedCipherInputStream;
 import org.apache.poi.poifs.crypt.CipherAlgorithm;
@@ -56,14 +58,40 @@ import org.apache.poi.util.MathUtil;
  * Decryptor implementation for Agile Encryption
  */
 public class AgileDecryptor extends Decryptor {
+    private static final Logger LOG = 
PoiLogManager.getLogger(AgileDecryptor.class);
+
     static final byte[] kVerifierInputBlock = longToBytes(0xfea7d2763b4b9e79L);
     static final byte[] kHashedVerifierBlock = 
longToBytes(0xd7aa0f6d3061344eL);
     static final byte[] kCryptoKeyBlock = longToBytes(0x146e0be7abacd0d6L);
     static final byte[] kIntegrityKeyBlock = longToBytes(0x5fb2ad010cb9e1f6L);
     static final byte[] kIntegrityValueBlock = 
longToBytes(0xa0677f02b22c8433L);
 
+    private static boolean FAIL_ON_INTEGRITY_ERROR = true;
+
     private long _length = -1;
 
+    /**
+     * Whether {@link #getDataStream(DirectoryNode)} fails when the 
DataIntegrity HMAC of the
+     * encrypted package does not match. Defaults to {@code true}.
+     * @since 6.0.1
+     */
+    public static boolean isFailOnIntegrityError() {
+        return FAIL_ON_INTEGRITY_ERROR;
+    }
+
+    /**
+     * Whether {@link #getDataStream(DirectoryNode)} fails when the 
DataIntegrity HMAC of the
+     * encrypted package does not match. Defaults to {@code true}.
+     * <p>
+     * Set it to {@code false} to only log a warning and decrypt the package 
anyway, e.g. to
+     * extract the content of a file whose HMAC was written incorrectly. Excel 
for the web shows such
+     * files, but only in read-only mode.
+     * @since 6.0.1
+     */
+    public static void setFailOnIntegrityError(final boolean 
failOnIntegrityError) {
+        FAIL_ON_INTEGRITY_ERROR = failOnIntegrityError;
+    }
+
     protected AgileDecryptor() {
     }
 
@@ -211,6 +239,12 @@ public class AgileDecryptor extends Decryptor {
         }
     }
 
+    /**
+     * {@inheritDoc}
+     *
+     * @throws EncryptedDocumentException if the password was not verified, or 
if the DataIntegrity HMAC
+     *         does not match and {@link #isFailOnIntegrityError()} is {@code 
true}
+     */
     @SuppressWarnings({"java:S2095"})
     @Override
     public InputStream getDataStream(DirectoryNode dir) throws IOException, 
GeneralSecurityException {
@@ -222,7 +256,7 @@ public class AgileDecryptor extends Decryptor {
 
     /**
      * 2.3.4.14 DataIntegrity Generation (Agile Encryption)
-     *
+     * <p>
      * Verifies the HMAC of the entire EncryptedPackage stream, including the 
StreamSize field,
      * against the decrypted encryptedHmacValue, so modifications of the 
encrypted data are
      * detected before any of it is decrypted.
@@ -231,7 +265,7 @@ public class AgileDecryptor extends Decryptor {
         byte[] hmacKey = getIntegrityHmacKey();
         byte[] hmacValue = getIntegrityHmacValue();
         if (hmacKey == null || hmacValue == null) {
-            throw new EncryptedDocumentException("The password needs to be 
verified before the data stream can be accessed");
+            throw new EncryptedDocumentException("The password needs to be 
verified successfully before the data stream can be accessed");
         }
 
         HashAlgorithm hashAlgo = 
getEncryptionInfo().getHeader().getHashAlgorithm();
@@ -247,7 +281,11 @@ public class AgileDecryptor extends Decryptor {
         }
 
         if (!MessageDigest.isEqual(hmacValue, integrityMD.doFinal())) {
-            throw new EncryptedDocumentException("The data integrity check of 
the encrypted package failed");
+            if (FAIL_ON_INTEGRITY_ERROR) {
+                throw new EncryptedDocumentException("The data integrity check 
of the encrypted package failed - "
+                        + "call AgileDecryptor.setFailOnIntegrityError(false) 
to decrypt it anyway");
+            }
+            LOG.atWarn().log("The data integrity check of the encrypted 
package failed, decrypting it anyway");
         }
     }
 
diff --git 
a/poi/src/test/java/org/apache/poi/poifs/crypt/agile/TestAgileDecryptor.java 
b/poi/src/test/java/org/apache/poi/poifs/crypt/agile/TestAgileDecryptor.java
index 9e4be0cc84..45c5c28b19 100644
--- a/poi/src/test/java/org/apache/poi/poifs/crypt/agile/TestAgileDecryptor.java
+++ b/poi/src/test/java/org/apache/poi/poifs/crypt/agile/TestAgileDecryptor.java
@@ -18,6 +18,8 @@
 package org.apache.poi.poifs.crypt.agile;
 
 import static org.apache.poi.poifs.crypt.Decryptor.DEFAULT_POIFS_ENTRY;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -27,6 +29,7 @@ import java.io.InputStream;
 import java.io.OutputStream;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.stream.Stream;
 
@@ -174,4 +177,49 @@ class TestAgileDecryptor {
             assertThrows(EncryptedDocumentException.class, () -> 
dec.getDataStream(fs));
         }
     }
+
+    @Test
+    void testTamperedHmacValue() throws Exception {
+        byte[] plain = new byte[3000];
+        Arrays.fill(plain, (byte) 'x');
+
+        EncryptionInfo infoEnc = new EncryptionInfo(EncryptionMode.agile);
+        Encryptor enc = infoEnc.getEncryptor();
+        enc.confirmPassword("test");
+
+        byte[] encData;
+        try (POIFSFileSystem fsEnc = new POIFSFileSystem()) {
+            try (OutputStream os = enc.getDataStream(fsEnc)) {
+                os.write(plain);
+            }
+            UnsynchronizedByteArrayOutputStream bos = 
UnsynchronizedByteArrayOutputStream.builder().get();
+            fsEnc.writeFilesystem(bos);
+            encData = bos.toByteArray();
+        }
+
+        try (POIFSFileSystem fs = new POIFSFileSystem(new 
ByteArrayInputStream(encData))) {
+            // change one character of the encryptedHmacValue, so the 
encrypted data is intact but the HMAC does not match
+            byte[] encInfoBytes;
+            try (DocumentInputStream dis = 
fs.getRoot().createDocumentInputStream(EncryptionInfo.ENCRYPTION_INFO_ENTRY)) {
+                encInfoBytes = IOUtils.toByteArray(dis);
+            }
+            String encInfo = new String(encInfoBytes, 
StandardCharsets.ISO_8859_1);
+            int pos = encInfo.indexOf("encryptedHmacValue=\"") + 
"encryptedHmacValue=\"".length();
+            encInfoBytes[pos] = (byte) (encInfoBytes[pos] == 'A' ? 'B' : 'A');
+            fs.createOrUpdateDocument(new ByteArrayInputStream(encInfoBytes), 
EncryptionInfo.ENCRYPTION_INFO_ENTRY);
+
+            Decryptor dec = new EncryptionInfo(fs).getDecryptor();
+            assertTrue(dec.verifyPassword("test"));
+            EncryptedDocumentException e = 
assertThrows(EncryptedDocumentException.class, () -> dec.getDataStream(fs));
+            assertThat(e.getMessage(), 
containsString("setFailOnIntegrityError(false)"));
+
+            // Excel for the web shows such a file in read-only mode, so it 
can be decrypted anyway
+            AgileDecryptor.setFailOnIntegrityError(false);
+            try (InputStream is = dec.getDataStream(fs)) {
+                assertArrayEquals(plain, IOUtils.toByteArray(is));
+            } finally {
+                AgileDecryptor.setFailOnIntegrityError(true);
+            }
+        }
+    }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to