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 54f9dbe289 RelationshipTransformService: don't drop duplicate 
relationship ids from the digest (#1467)
54f9dbe289 is described below

commit 54f9dbe28933947d545ccae23b9aea449aa1ece6
Author: Nayyar <[email protected]>
AuthorDate: Sun Oct 25 03:58:58 2026 +0530

    RelationshipTransformService: don't drop duplicate relationship ids from 
the digest (#1467)
    
    keep duplicate relationship ids in the relationship transform digest
---
 .../services/RelationshipTransformService.java     | 37 ++++++++-------
 .../poi/poifs/crypt/dsig/TestSignatureInfo.java    | 55 ++++++++++++++++++++++
 2 files changed, 75 insertions(+), 17 deletions(-)

diff --git 
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java
 
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java
index 9a4f93b733..0307de7878 100644
--- 
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java
+++ 
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java
@@ -36,8 +36,8 @@ import java.security.Provider;
 import java.security.Security;
 import java.security.spec.AlgorithmParameterSpec;
 import java.util.ArrayList;
+import java.util.Comparator;
 import java.util.List;
-import java.util.TreeMap;
 
 import javax.xml.crypto.Data;
 import javax.xml.crypto.MarshalException;
@@ -203,27 +203,30 @@ public class RelationshipTransformService extends 
TransformService {
             throw new TransformException(e.getMessage(), e);
         }
 
-        // keep only those relationships which id is registered in the 
sourceIds
+        // keep only those relationships which id is registered in the 
sourceIds - all of them,
+        // at any depth: the package model also reads nested elements and 
resolves a duplicated
+        // id to the last one, so dropping one here would leave an unsigned 
target out of the digest
         Element root = doc.getDocumentElement();
-        NodeList nl = root.getChildNodes();
-        TreeMap<String,Element> rsList = new TreeMap<>();
-        for (int i=nl.getLength()-1; i>=0; i--) {
-            Node n = nl.item(i);
-            if ("Relationship".equals(n.getLocalName())) {
-                Element el = (Element)n;
-                String id = el.getAttribute("Id");
-                if (sourceIds.contains(id)) {
-                    String targetMode = el.getAttribute("TargetMode");
-                    if (targetMode == null || targetMode.isEmpty()) {
-                        el.setAttribute("TargetMode", "Internal");
-                    }
-                    rsList.put(id, el);
+        NodeList nl = root.getElementsByTagNameNS("*", "Relationship");
+        List<Element> rsList = new ArrayList<>();
+        for (int i=0; i<nl.getLength(); i++) {
+            Element el = (Element)nl.item(i);
+            String id = el.getAttribute("Id");
+            if (sourceIds.contains(id)) {
+                String targetMode = el.getAttribute("TargetMode");
+                if (targetMode == null || targetMode.isEmpty()) {
+                    el.setAttribute("TargetMode", "Internal");
                 }
+                rsList.add(el);
             }
-            root.removeChild(n);
         }
 
-        for (Element el : rsList.values()) {
+        while (root.hasChildNodes()) {
+            root.removeChild(root.getFirstChild());
+        }
+
+        rsList.sort(Comparator.comparing(el -> el.getAttribute("Id")));
+        for (Element el : rsList) {
             root.appendChild(el);
         }
 
diff --git 
a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
 
b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
index 5596f99541..2ebed5771a 100644
--- 
a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
+++ 
b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
@@ -45,6 +45,7 @@ import java.net.SocketTimeoutException;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URL;
+import java.nio.charset.StandardCharsets;
 import java.security.GeneralSecurityException;
 import java.security.KeyStoreException;
 import java.security.cert.X509CRL;
@@ -53,8 +54,10 @@ import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Calendar;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Locale;
 import java.util.function.BiFunction;
 import java.util.function.Supplier;
 
@@ -64,6 +67,9 @@ import javax.xml.crypto.dsig.CanonicalizationMethod;
 import javax.xml.crypto.dsig.XMLSignatureException;
 import javax.xml.crypto.dsig.dom.DOMSignContext;
 
+import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
+import org.apache.commons.compress.archivers.zip.ZipFile;
 import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
 import org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo;
 import org.apache.logging.log4j.Logger;
@@ -103,6 +109,7 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
 import org.apache.poi.xwpf.usermodel.XWPFDocument;
 import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun;
+import org.apache.poi.xwpf.usermodel.XWPFRelation;
 import org.apache.poi.xwpf.usermodel.XWPFSignatureLine;
 import org.apache.xmlbeans.SystemProperties;
 import org.apache.xmlbeans.XmlCursor;
@@ -418,6 +425,54 @@ class TestSignatureInfo {
         }
     }
 
+    @ParameterizedTest
+    @ValueSource(strings = {"%s", "<x:wrap xmlns:x=\"urn:x\">%s</x:wrap>"})
+    void testDuplicateRelationshipId(String wrapper) throws Exception {
+        // add a second officeDocument relationship reusing the signed Id 
"rId1",
+        // pointing to an unsigned part - the package model resolves rId1 to 
this one
+        String rel = String.format(Locale.ROOT, wrapper, "<Relationship 
Id=\"rId1\" Type=\"" +
+            PackageRelationshipTypes.CORE_DOCUMENT + "\" 
Target=\"word/tampered.xml\"/>");
+        UnsynchronizedByteArrayOutputStream bos = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        try (ZipFile zf = 
ZipFile.builder().setFile(testdata.getFile("hello-world-signed.docx")).get();
+             ZipArchiveOutputStream zos = new ZipArchiveOutputStream(bos)) {
+            String document = null;
+            for (ZipArchiveEntry ze : Collections.list(zf.getEntries())) {
+                byte[] data;
+                try (InputStream is = zf.getInputStream(ze)) {
+                    data = IOUtils.toByteArray(is);
+                }
+                String name = ze.getName();
+                if ("[Content_Types].xml".equals(name)) {
+                    data = new String(data, 
StandardCharsets.UTF_8).replace("</Types>",
+                        "<Override PartName=\"/word/tampered.xml\" 
ContentType=\"" +
+                        XWPFRelation.DOCUMENT.getContentType() + 
"\"/></Types>").getBytes(StandardCharsets.UTF_8);
+                } else if ("_rels/.rels".equals(name)) {
+                    data = new String(data, 
StandardCharsets.UTF_8).replace("</Relationships>",
+                        rel + 
"</Relationships>").getBytes(StandardCharsets.UTF_8);
+                } else if ("word/document.xml".equals(name)) {
+                    document = new String(data, StandardCharsets.UTF_8);
+                }
+                zos.putArchiveEntry(new ZipArchiveEntry(name));
+                zos.write(data);
+                zos.closeArchiveEntry();
+            }
+            assertNotNull(document);
+            zos.putArchiveEntry(new ZipArchiveEntry("word/tampered.xml"));
+            zos.write(document.replace("Hello world", 
"Tampered").getBytes(StandardCharsets.UTF_8));
+            zos.closeArchiveEntry();
+        }
+
+        try (OPCPackage pkg = OPCPackage.open(bos.toInputStream());
+             XWPFDocument doc = new XWPFDocument(pkg)) {
+            assertEquals("Tampered", doc.getParagraphs().get(0).getText());
+
+            SignatureInfo si = new SignatureInfo();
+            si.setOpcPackage(pkg);
+            si.setSignatureConfig(new SignatureConfig());
+            assertFalse(si.verifySignature(), "signature must not cover the 
substituted main part");
+        }
+    }
+
     @Test
     void testSignSpreadsheetWithSignatureInfo() throws Exception {
         String testFile = "hello-world-unsigned.xlsx";


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

Reply via email to