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 4f3c255639 SignaturePart: stricter checks of what a signature covers
(#1477)
4f3c255639 is described below
commit 4f3c25563919e7efa4a75feccf6cef1ac3d05a04
Author: PJ Fanning <[email protected]>
AuthorDate: Sun Oct 25 00:14:15 2026 +0100
SignaturePart: stricter checks of what a signature covers (#1477)
* RelationshipTransformService: only treat relationships-namespace elements
as relationships
Follow-up to #1467. The transform matched Relationship elements in any
namespace, but PackageRelationshipCollection only reads those in the
relationships namespace, as the spec defines them. A foreign element named
Relationship with a signed Id changed the digest, so a valid signature
failed to verify. Also make the comment say which case keeping all elements
covers, and share the signed-docx rewriting between the tests.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* SignaturePart: check that relationships of signed types are covered by
the signature
When verifying, also check each relationships part of the package: a
relationship that the signature doesn't cover must not have the same type
as a relationship from the same source that it does cover. Relationship
types a signer leaves out entirely (e.g. customXml in Office signatures)
are unaffected.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* SignaturePart: report a content type mismatch as an invalid signature
Follow-up to #1472. A part whose content type differs from the one a
signature reference was made for made verifySignature() throw an
EncryptedDocumentException. It now returns false, as for other changes
made after signing. The dereferencer throws a package-private
URIReferenceException subclass, which SignaturePart.validate() recognises.
The tests share a rewriteSignedDocx helper, and the content type test no
longer depends on how xmlsec wraps exceptions.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* Use a Hamcrest matcher in testAddedRelationshipIsNotSigned
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* Use assertFalse with a failure message in testAddedRelationshipIsNotSigned
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* Use assertFalse with a failure message in
contentTypeChangeInvalidatesSignature
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../poi/poifs/crypt/dsig/OOXMLURIDereferencer.java | 16 ++-
.../apache/poi/poifs/crypt/dsig/SignaturePart.java | 90 ++++++++++++++++-
.../poi/poifs/crypt/dsig/TestSignatureInfo.java | 112 +++++++++++----------
3 files changed, 163 insertions(+), 55 deletions(-)
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java
index ae57aa41ca..f11ed57e21 100644
---
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java
+++
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java
@@ -90,12 +90,13 @@ public class OOXMLURIDereferencer implements
URIDereferencer {
}
// [Content_Types].xml is not signed, so a signed reference carries
the content type of
- // the part in its query - the signature only covers the part if the
content type matches
+ // the part in its query - the signature only covers the part if the
content type matches.
+ // Office and POI write the content type as the only query parameter
String query = uri.getQuery();
if (query != null && query.startsWith(CONTENT_TYPE_QUERY)) {
String signedContentType =
query.substring(CONTENT_TYPE_QUERY.length());
if (!signedContentType.equalsIgnoreCase(part.getContentType())) {
- throw new URIReferenceException("content type of " +
part.getPartName() + " is " +
+ throw new ContentTypeMismatchException("content type of " +
part.getPartName() + " is " +
part.getContentType() + ", but the signature references "
+ signedContentType);
}
}
@@ -142,4 +143,15 @@ public class OOXMLURIDereferencer implements
URIDereferencer {
return null;
}
}
+
+ /**
+ * The content type of a part differs from the one the signature
references, i.e. the signature is invalid
+ */
+ static final class ContentTypeMismatchException extends
URIReferenceException {
+ private static final long serialVersionUID = 1L;
+
+ ContentTypeMismatchException(String message) {
+ super(message);
+ }
+ }
}
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignaturePart.java
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignaturePart.java
index b8991e80b0..29b97b7258 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignaturePart.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/SignaturePart.java
@@ -19,19 +19,24 @@ package org.apache.poi.poifs.crypt.dsig;
import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
import static
org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.MS_DIGSIG_NS;
+import static
org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS;
import static
org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_DIGSIG_NS;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.X509Certificate;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import java.util.function.Consumer;
import javax.xml.crypto.MarshalException;
import javax.xml.crypto.URIDereferencer;
+import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.crypto.dsig.XMLSignatureFactory;
@@ -46,7 +51,12 @@ import org.apache.poi.logging.PoiLogManager;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ooxml.util.DocumentHelper;
import org.apache.poi.ooxml.util.XPathHelper;
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.opc.ContentTypes;
import org.apache.poi.openxml4j.opc.PackagePart;
+import org.apache.poi.openxml4j.opc.PackageRelationship;
+import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
+import org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService;
import org.apache.xmlbeans.XmlException;
import org.w3.x2000.x09.xmldsig.SignatureDocument;
import org.w3c.dom.Document;
@@ -136,7 +146,7 @@ public class SignaturePart {
XMLSignatureFactory xmlSignatureFactory =
signatureInfo.getSignatureFactory();
XMLSignature xmlSignature =
xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
- boolean valid = xmlSignature.validate(domValidateContext);
+ boolean valid = xmlSignature.validate(domValidateContext) &&
hasSignedRelationships(doc, xmlSignature);
if (valid) {
signer = keySelector.getSigner();
@@ -162,12 +172,90 @@ public class SignaturePart {
LOG.atError().withThrowable(e).log(s);
throw new EncryptedDocumentException(s, e);
} catch (XMLSignatureException e) {
+ for (Throwable t = e; t != null; t = t.getCause()) {
+ if (t instanceof
OOXMLURIDereferencer.ContentTypeMismatchException) {
+ LOG.atWarn().log("the signature is invalid: {}",
t.getMessage());
+ return false;
+ }
+ }
String s = "error in validating the signature";
LOG.atError().withThrowable(e).log(s);
throw new EncryptedDocumentException(s, e);
}
}
+ /**
+ * Checks that no relationship which is not covered by the signature has
the same type as a
+ * signed relationship of the same source, as the package could resolve
that type to it
+ */
+ private boolean hasSignedRelationships(Document doc, XMLSignature
xmlSignature) throws XMLSignatureException {
+ // the relationship ids and types per relationships part, which are
listed in the transforms
+ // of the manifests in the objects referenced by the (validated)
SignedInfo
+ Map<String,Set<String>> signedIds = new HashMap<>();
+ Map<String,Set<String>> signedTypes = new HashMap<>();
+ for (Reference ref : xmlSignature.getSignedInfo().getReferences()) {
+ String uri = ref.getURI();
+ Element obj = (uri == null || !uri.startsWith("#")) ? null :
doc.getElementById(uri.substring(1));
+ if (obj == null) {
+ continue;
+ }
+ NodeList refs = obj.getElementsByTagNameNS(XML_DIGSIG_NS,
"Reference");
+ for (int i=0; i<refs.getLength(); i++) {
+ Element manifestRef = (Element)refs.item(i);
+ if
(!"Manifest".equals(manifestRef.getParentNode().getLocalName()) ||
!hasRelationshipTransform(manifestRef)) {
+ continue;
+ }
+ String partName =
manifestRef.getAttribute("URI").replaceFirst("\\?.*",
"").toLowerCase(Locale.ROOT);
+ addAttributes(manifestRef, "RelationshipReference",
"SourceId", signedIds.computeIfAbsent(partName, k -> new HashSet<>()));
+ addAttributes(manifestRef, "RelationshipsGroupReference",
"SourceType", signedTypes.computeIfAbsent(partName, k -> new HashSet<>()));
+ }
+ }
+
+ for (PackagePart pp :
signatureInfo.getOpcPackage().getPartsByContentType(ContentTypes.RELATIONSHIPS_PART))
{
+ String partName =
pp.getPartName().getName().toLowerCase(Locale.ROOT);
+ PackageRelationshipCollection prc;
+ try {
+ prc = new
PackageRelationshipCollection(signatureInfo.getOpcPackage());
+ prc.parseRelationshipsPart(pp);
+ } catch (InvalidFormatException e) {
+ throw new XMLSignatureException("Invalid relationship
descriptor: " + pp.getPartName().getName(), e);
+ }
+ Set<String> ids = signedIds.getOrDefault(partName, Set.of());
+ Set<String> groupTypes = signedTypes.getOrDefault(partName,
Set.of());
+ Set<String> types = new HashSet<>();
+ for (PackageRelationship rel : prc) {
+ if (ids.contains(rel.getId())) {
+ types.add(rel.getRelationshipType());
+ }
+ }
+ for (PackageRelationship rel : prc) {
+ String type = rel.getRelationshipType();
+ if (!ids.contains(rel.getId()) && !groupTypes.contains(type)
&& types.contains(type)) {
+ LOG.atWarn().log("relationship {} in {} is not covered by
the signature", rel.getId(), pp.getPartName().getName());
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ private static boolean hasRelationshipTransform(Element manifestRef) {
+ NodeList transforms =
manifestRef.getElementsByTagNameNS(XML_DIGSIG_NS, "Transform");
+ for (int i=0; i<transforms.getLength(); i++) {
+ if
(RelationshipTransformService.TRANSFORM_URI.equals(((Element)transforms.item(i)).getAttribute("Algorithm")))
{
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static void addAttributes(Element manifestRef, String localName,
String attribute, Set<String> values) {
+ NodeList nl = manifestRef.getElementsByTagNameNS(OO_DIGSIG_NS,
localName);
+ for (int i=0; i<nl.getLength(); i++) {
+ values.add(((Element)nl.item(i)).getAttribute(attribute));
+ }
+ }
+
private void extractConfig(final Document doc, final XMLSignature
xmlSignature) throws XPathExpressionException {
SignatureConfig signatureConfig = signatureInfo.getSignatureConfig();
if (!signatureConfig.isUpdateConfigOnValidate()) {
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 63cb6c32eb..9cb911ef5c 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
@@ -23,12 +23,12 @@
================================================================= */
package org.apache.poi.poifs.crypt.dsig;
+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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
@@ -58,17 +58,16 @@ import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
+import java.util.Map;
import java.util.function.BiFunction;
+import java.util.function.Consumer;
import java.util.function.Supplier;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
import javax.security.auth.x500.X500Principal;
import javax.xml.crypto.MarshalException;
-import javax.xml.crypto.URIReferenceException;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.crypto.dsig.dom.DOMSignContext;
@@ -363,33 +362,20 @@ class TestSignatureInfo {
void contentTypeChangeInvalidatesSignature() throws Exception {
// the signed references carry the part content type as
"?ContentType=...", because
// [Content_Types].xml itself is not signed
- final String docType =
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
- final String macroType =
"application/vnd.ms-word.document.macroEnabled.main+xml";
-
- final UnsynchronizedByteArrayOutputStream bos =
UnsynchronizedByteArrayOutputStream.builder().get();
- try (InputStream is =
testdata.openResourceAsStream("hello-world-signed.docx");
- ZipInputStream zis = new ZipInputStream(is);
- ZipOutputStream zos = new ZipOutputStream(bos)) {
- for (ZipEntry ze; (ze = zis.getNextEntry()) != null; ) {
- byte[] data = IOUtils.toByteArray(zis);
- if ("[Content_Types].xml".equals(ze.getName())) {
- String types = new String(data, StandardCharsets.UTF_8);
- assertTrue(types.contains(docType));
- data = types.replace(docType,
macroType).getBytes(StandardCharsets.UTF_8);
- }
- zos.putNextEntry(new ZipEntry(ze.getName()));
- zos.write(data);
- zos.closeEntry();
- }
- }
+ final String docType = XWPFRelation.DOCUMENT.getContentType();
+ final String macroType = XWPFRelation.MACRO_DOCUMENT.getContentType();
- try (OPCPackage pkg = OPCPackage.open(bos.toInputStream())) {
+ InputStream modified = rewriteSignedDocx(entries -> {
+ assertThat(new String(entries.get("[Content_Types].xml"),
StandardCharsets.UTF_8), containsString(docType));
+ entries.put("[Content_Types].xml",
replace(entries.get("[Content_Types].xml"), docType, macroType));
+ });
+
+ try (OPCPackage pkg = OPCPackage.open(modified)) {
assertEquals(macroType,
pkg.getPart(PackagingURIHelper.createPartName("/word/document.xml")).getContentType());
SignatureInfo si = new SignatureInfo();
si.setOpcPackage(pkg);
si.setSignatureConfig(new SignatureConfig());
- EncryptedDocumentException ex =
assertThrows(EncryptedDocumentException.class, si::verifySignature);
- assertInstanceOf(URIReferenceException.class,
ex.getCause().getCause());
+ assertFalse(si.verifySignature(), "a changed content type must
invalidate the signature");
}
}
@@ -485,6 +471,20 @@ class TestSignatureInfo {
}
}
+ @Test
+ void testAddedRelationshipIsNotSigned() throws Exception {
+ // a second officeDocument relationship with a new Id, added after
signing
+ String rel = "<Relationship Id=\"rId0\" Type=\"" +
PackageRelationshipTypes.CORE_DOCUMENT +
+ "\" Target=\"word/tampered.xml\"/>";
+
+ try (OPCPackage pkg = OPCPackage.open(modifySignedDocx(rel, true))) {
+ SignatureInfo si = new SignatureInfo();
+ si.setOpcPackage(pkg);
+ si.setSignatureConfig(new SignatureConfig());
+ assertFalse(si.verifySignature(), "a relationship added after
signing must invalidate the signature");
+ }
+ }
+
@Test
void testForeignRelationshipElementIsIgnored() throws Exception {
// an element named Relationship in another namespace is not a
relationship,
@@ -507,40 +507,48 @@ class TestSignatureInfo {
* is set, a word/tampered.xml main part which says "Tampered" instead of
"Hello world"
*/
private static InputStream modifySignedDocx(String rel, boolean
addTamperedPart) throws IOException {
- 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;
+ return rewriteSignedDocx(entries -> {
+ entries.put("_rels/.rels", replace(entries.get("_rels/.rels"),
"</Relationships>", rel + "</Relationships>"));
+ if (addTamperedPart) {
+ entries.put("[Content_Types].xml",
replace(entries.get("[Content_Types].xml"), "</Types>",
+ "<Override PartName=\"/word/tampered.xml\" ContentType=\""
+
+ XWPFRelation.DOCUMENT.getContentType() + "\"/></Types>"));
+ byte[] document = entries.get("word/document.xml");
+ assertNotNull(document);
+ entries.put("word/tampered.xml", replace(document, "Hello
world", "Tampered"));
+ }
+ });
+ }
+
+ /**
+ * 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 {
+ Map<String, byte[]> entries = new LinkedHashMap<>();
+ try (ZipFile zf =
ZipFile.builder().setFile(testdata.getFile("hello-world-signed.docx")).get()) {
for (ZipArchiveEntry ze : Collections.list(zf.getEntries())) {
- byte[] data;
try (InputStream is = zf.getInputStream(ze)) {
- data = IOUtils.toByteArray(is);
- }
- String name = ze.getName();
- if (addTamperedPart && "[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);
+ entries.put(ze.getName(), IOUtils.toByteArray(is));
}
- zos.putArchiveEntry(new ZipArchiveEntry(name));
- zos.write(data);
- zos.closeArchiveEntry();
}
- assertNotNull(document);
- if (addTamperedPart) {
- zos.putArchiveEntry(new ZipArchiveEntry("word/tampered.xml"));
- zos.write(document.replace("Hello world",
"Tampered").getBytes(StandardCharsets.UTF_8));
+ }
+ modifier.accept(entries);
+
+ UnsynchronizedByteArrayOutputStream bos =
UnsynchronizedByteArrayOutputStream.builder().get();
+ try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(bos)) {
+ for (Map.Entry<String, byte[]> me : entries.entrySet()) {
+ zos.putArchiveEntry(new ZipArchiveEntry(me.getKey()));
+ zos.write(me.getValue());
zos.closeArchiveEntry();
}
}
return bos.toInputStream();
}
+ private static byte[] replace(byte[] data, String target, String
replacement) {
+ return new String(data, StandardCharsets.UTF_8).replace(target,
replacement).getBytes(StandardCharsets.UTF_8);
+ }
+
@Test
void testSignSpreadsheetWithSignatureInfo() throws Exception {
String testFile = "hello-world-unsigned.xlsx";
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]