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 6966eb7d54 RelationshipTransformService: digest relationships selected 
by type (#1510)
6966eb7d54 is described below

commit 6966eb7d546fe0dc8ae4bd0132e0ea7fa4389c62
Author: Nayyar <[email protected]>
AuthorDate: Tue Nov 3 14:59:03 2026 +0530

    RelationshipTransformService: digest relationships selected by type (#1510)
    
    The transform only read RelationshipReference/@SourceId parameters and
    ignored RelationshipsGroupReference/@SourceType (ECMA-376 Part 2,
    13.2.4.24), so relationships selected by type never reached the digest,
    while SignaturePart.hasSignedRelationships treats them as covered. A
    relationship of a group-signed type added after signing left
    verifySignature() returning true.
    
    Parse, marshal and apply SourceType next to SourceId. Signatures without
    group references produce the same transform output as before.
---
 .../services/RelationshipTransformService.java     | 39 +++++++++--
 .../poi/poifs/crypt/dsig/TestSignatureInfo.java    | 77 +++++++++++++++++++++-
 2 files changed, 110 insertions(+), 6 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 4133180690..5c5a1829fa 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
@@ -80,6 +80,8 @@ public class RelationshipTransformService extends 
TransformService {
 
     private final List<String> sourceIds;
 
+    private final List<String> sourceTypes;
+
     private static final Logger LOG = 
PoiLogManager.getLogger(RelationshipTransformService.class);
 
     /**
@@ -87,9 +89,18 @@ public class RelationshipTransformService extends 
TransformService {
      */
     public static class RelationshipTransformParameterSpec implements 
TransformParameterSpec {
         List<String> sourceIds = new ArrayList<>();
+        List<String> sourceTypes = new ArrayList<>();
         public void addRelationshipReference(String relationshipId) {
                 sourceIds.add(relationshipId);
         }
+        /**
+         * Adds a RelationshipsGroupReference, i.e. signs all relationships of 
the given type
+         *
+         * @since 6.0.1
+         */
+        public void addRelationshipGroupReference(String relationshipType) {
+            sourceTypes.add(relationshipType);
+        }
         public boolean hasSourceIds() {
             return !sourceIds.isEmpty();
         }
@@ -112,6 +123,7 @@ public class RelationshipTransformService extends 
TransformService {
         super();
         LOG.atDebug().log("constructor");
         this.sourceIds = new ArrayList<>();
+        this.sourceTypes = new ArrayList<>();
     }
 
     /**
@@ -140,6 +152,7 @@ public class RelationshipTransformService extends 
TransformService {
             throw new InvalidAlgorithmParameterException();
         }
         this.sourceIds.addAll(relParams.sourceIds);
+        this.sourceTypes.addAll(relParams.sourceTypes);
     }
 
     @Override
@@ -152,14 +165,23 @@ public class RelationshipTransformService extends 
TransformService {
         try {
             TransformDocument transDoc = 
TransformDocument.Factory.parse(parentNode, DEFAULT_XML_OPTIONS);
             XmlObject[] xoList = 
transDoc.getTransform().selectChildren(RelationshipReferenceDocument.type.getDocumentElementName());
-            if (xoList.length == 0) {
-                LOG.atWarn().log("no RelationshipReference/@SourceId 
parameters present");
-            }
             for (XmlObject xo : xoList) {
                 String sourceId = ((CTRelationshipReference)xo).getSourceId();
                 LOG.atDebug().log("sourceId: {}", sourceId);
                 this.sourceIds.add(sourceId);
             }
+            // RelationshipsGroupReference selects all relationships of a type 
(13.2.4.24)
+            for (Node n = parentNode.getFirstChild(); n != null; n = 
n.getNextSibling()) {
+                if (n instanceof Element && 
OO_DIGSIG_NS.equals(n.getNamespaceURI())
+                    && "RelationshipsGroupReference".equals(n.getLocalName())) 
{
+                    String sourceType = 
((Element)n).getAttribute("SourceType");
+                    LOG.atDebug().log("sourceType: {}", sourceType);
+                    this.sourceTypes.add(sourceType);
+                }
+            }
+            if (sourceIds.isEmpty() && sourceTypes.isEmpty()) {
+                LOG.atWarn().log("no RelationshipReference/@SourceId or 
RelationshipsGroupReference/@SourceType parameters present");
+            }
         } catch (XmlException e) {
             throw new InvalidAlgorithmParameterException(e);
         }
@@ -178,6 +200,12 @@ public class RelationshipTransformService extends 
TransformService {
             el.setAttribute("SourceId", sourceId);
             parentNode.appendChild(el);
         }
+        for (String sourceType : this.sourceTypes) {
+            Element el = doc.createElementNS(OO_DIGSIG_NS, 
"mdssi:RelationshipsGroupReference");
+            el.setAttributeNS(XML_NS, "xmlns:mdssi", OO_DIGSIG_NS);
+            el.setAttribute("SourceType", sourceType);
+            parentNode.appendChild(el);
+        }
     }
 
     public AlgorithmParameterSpec getParameterSpec() {
@@ -205,7 +233,8 @@ public class RelationshipTransformService extends 
TransformService {
             throw new TransformException(e.getMessage(), e);
         }
 
-        // keep only those relationships which id is registered in the 
sourceIds - all of them,
+        // keep only those relationships which id is registered in the 
sourceIds, or which type is
+        // registered in the sourceTypes (RelationshipsGroupReference) - all 
of them,
         // at any depth: the package model also reads nested elements and 
resolves a duplicated
         // id to the last one, so dropping a duplicate of a signed id here 
would leave its target
         // out of the digest. Only elements in the relationships namespace are 
relationships,
@@ -216,7 +245,7 @@ public class RelationshipTransformService extends 
TransformService {
         for (int i=0; i<nl.getLength(); i++) {
             Element el = (Element)nl.item(i);
             String id = el.getAttribute("Id");
-            if (sourceIds.contains(id)) {
+            if (sourceIds.contains(id) || 
sourceTypes.contains(el.getAttribute("Type"))) {
                 // the default applies to an absent attribute only: the 
package model reads a
                 // present TargetMode with any value other than "Internal" as 
an external
                 // relationship, so an empty one has to be digested as what it 
is
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 6ad61e434d..5145786ff7 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
@@ -70,8 +70,13 @@ import java.util.function.Supplier;
 import javax.security.auth.x500.X500Principal;
 import javax.xml.crypto.MarshalException;
 import javax.xml.crypto.dsig.CanonicalizationMethod;
+import javax.xml.crypto.dsig.DigestMethod;
+import javax.xml.crypto.dsig.Reference;
+import javax.xml.crypto.dsig.Transform;
 import javax.xml.crypto.dsig.XMLSignatureException;
+import javax.xml.crypto.dsig.XMLSignatureFactory;
 import javax.xml.crypto.dsig.dom.DOMSignContext;
+import javax.xml.crypto.dsig.spec.TransformParameterSpec;
 
 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
 import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
@@ -100,6 +105,8 @@ import 
org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet;
 import org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet;
 import org.apache.poi.poifs.crypt.dsig.facets.XAdESXLSignatureFacet;
 import org.apache.poi.poifs.crypt.dsig.services.RevocationData;
+import org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService;
+import 
org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService.RelationshipTransformParameterSpec;
 import org.apache.poi.poifs.crypt.dsig.services.RevocationDataService;
 import org.apache.poi.poifs.crypt.dsig.services.TimeStampService;
 import org.apache.poi.poifs.crypt.dsig.services.TimeStampServiceValidator;
@@ -574,6 +581,67 @@ class TestSignatureInfo {
         }
     }
 
+    @Test
+    void testRelationshipsGroupReference() throws Exception {
+        // sign with an additional reference to the document relationships, 
which signs all
+        // attachedTemplate relationships as a group - there is none of them 
when signing
+        String templateType = 
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate";;
+        String relsName = "word/_rels/document.xml.rels";
+
+        DummyKeystore ks = new DummyKeystore(STORE_PASS);
+        KeyCertPair certPair = ks.createDummyKey();
+        SignatureConfig sic = new SignatureConfig();
+        sic.setKey(certPair.getKey());
+        sic.setSigningCertificateChain(certPair.getX509Chain());
+        sic.setSignatureFacets(Arrays.asList(new OOXMLSignatureFacet() {
+            @Override
+            protected void addManifestReferences(SignatureInfo signatureInfo, 
List<Reference> manifestReferences)
+            throws XMLSignatureException {
+                super.addManifestReferences(signatureInfo, manifestReferences);
+                RelationshipTransformParameterSpec parameterSpec = new 
RelationshipTransformParameterSpec();
+                parameterSpec.addRelationshipGroupReference(templateType);
+                XMLSignatureFactory sigFac = 
signatureInfo.getSignatureFactory();
+                try {
+                    List<Transform> transforms = Arrays.asList(
+                        
sigFac.newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec),
+                        sigFac.newTransform(CanonicalizationMethod.INCLUSIVE, 
(TransformParameterSpec)null));
+                    DigestMethod digestMethod = 
sigFac.newDigestMethod(signatureInfo.getSignatureConfig().getDigestMethodUri(), 
null);
+                    manifestReferences.add(sigFac.newReference("/" + relsName +
+                        
"?ContentType=application/vnd.openxmlformats-package.relationships+xml", 
digestMethod, transforms, null, null));
+                } catch (GeneralSecurityException e) {
+                    throw new XMLSignatureException(e);
+                }
+            }
+        }, new KeyInfoSignatureFacet()));
+
+        File signed = copy(testdata.getFile("hello-world-unsigned.docx"));
+        try (OPCPackage pkg = OPCPackage.open(signed, 
PackageAccess.READ_WRITE)) {
+            SignatureInfo si = new SignatureInfo();
+            si.setOpcPackage(pkg);
+            si.setSignatureConfig(sic);
+            si.confirmSignature();
+        }
+
+        try (OPCPackage pkg = OPCPackage.open(signed, PackageAccess.READ)) {
+            SignatureInfo si = new SignatureInfo();
+            si.setOpcPackage(pkg);
+            si.setSignatureConfig(new SignatureConfig());
+            assertTrue(si.verifySignature());
+        }
+
+        // a template relationship added after signing is one of the 
relationships signed as a group
+        String rel = "<Relationship Id=\"rId99\" Type=\"" + templateType +
+            "\" Target=\"https://example.com/template.dotm\"; 
TargetMode=\"External\"/>";
+        InputStream tampered = rewriteDocx(signed, entries -> 
entries.put(relsName,
+            replace(entries.get(relsName), "</Relationships>", rel + 
"</Relationships>")));
+        try (OPCPackage pkg = OPCPackage.open(tampered)) {
+            SignatureInfo si = new SignatureInfo();
+            si.setOpcPackage(pkg);
+            si.setSignatureConfig(new SignatureConfig());
+            assertFalse(si.verifySignature(), "a relationship of a type signed 
as a group must be covered by the digest");
+        }
+    }
+
     /**
      * Copies hello-world-signed.docx, adding {@code rel} to _rels/.rels and, 
if {@code addTamperedPart}
      * is set, a word/tampered.xml main part which says "Tampered" instead of 
"Hello world"
@@ -596,8 +664,15 @@ class TestSignatureInfo {
      * Copies hello-world-signed.docx, letting {@code modifier} change, add or 
remove entries by name
      */
     private static InputStream rewriteSignedDocx(Consumer<Map<String, byte[]>> 
modifier) throws IOException {
+        return rewriteDocx(testdata.getFile("hello-world-signed.docx"), 
modifier);
+    }
+
+    /**
+     * Copies {@code file}, letting {@code modifier} change, add or remove 
entries by name
+     */
+    private static InputStream rewriteDocx(File file, Consumer<Map<String, 
byte[]>> modifier) throws IOException {
         Map<String, byte[]> entries = new LinkedHashMap<>();
-        try (ZipFile zf = 
ZipFile.builder().setFile(testdata.getFile("hello-world-signed.docx")).get()) {
+        try (ZipFile zf = ZipFile.builder().setFile(file).get()) {
             for (ZipArchiveEntry ze : Collections.list(zf.getEntries())) {
                 try (InputStream is = zf.getInputStream(ze)) {
                     entries.put(ze.getName(), IOUtils.toByteArray(is));


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

Reply via email to