You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SignaturePart.java 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.poifs.crypt.dsig;
  16. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.MS_DIGSIG_NS;
  18. import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_DIGSIG_NS;
  19. import java.io.IOException;
  20. import java.security.cert.X509Certificate;
  21. import java.util.HashMap;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.function.Consumer;
  26. import javax.xml.crypto.MarshalException;
  27. import javax.xml.crypto.dsig.XMLSignature;
  28. import javax.xml.crypto.dsig.XMLSignatureException;
  29. import javax.xml.crypto.dsig.XMLSignatureFactory;
  30. import javax.xml.crypto.dsig.dom.DOMValidateContext;
  31. import javax.xml.namespace.NamespaceContext;
  32. import javax.xml.xpath.XPath;
  33. import javax.xml.xpath.XPathConstants;
  34. import javax.xml.xpath.XPathExpressionException;
  35. import javax.xml.xpath.XPathFactory;
  36. import org.apache.poi.EncryptedDocumentException;
  37. import org.apache.poi.ooxml.util.DocumentHelper;
  38. import org.apache.poi.openxml4j.opc.PackagePart;
  39. import org.apache.poi.util.POILogFactory;
  40. import org.apache.poi.util.POILogger;
  41. import org.apache.xmlbeans.XmlException;
  42. import org.w3.x2000.x09.xmldsig.SignatureDocument;
  43. import org.w3c.dom.Document;
  44. import org.w3c.dom.Element;
  45. import org.w3c.dom.NodeList;
  46. import org.xml.sax.SAXException;
  47. public class SignaturePart {
  48. private static final POILogger LOG = POILogFactory.getLogger(SignaturePart.class);
  49. private static final String XMLSEC_VALIDATE_MANIFEST = "org.jcp.xml.dsig.validateManifests";
  50. private final PackagePart signaturePart;
  51. private final SignatureConfig signatureConfig;
  52. private X509Certificate signer;
  53. private List<X509Certificate> certChain;
  54. /* package */ SignaturePart(final PackagePart signaturePart, final SignatureConfig signatureConfig) {
  55. this.signaturePart = signaturePart;
  56. this.signatureConfig = signatureConfig;
  57. }
  58. /**
  59. * @return the package part containing the signature
  60. */
  61. public PackagePart getPackagePart() {
  62. return signaturePart;
  63. }
  64. /**
  65. * @return the signer certificate
  66. */
  67. public X509Certificate getSigner() {
  68. return signer;
  69. }
  70. /**
  71. * @return the certificate chain of the signer
  72. */
  73. public List<X509Certificate> getCertChain() {
  74. return certChain;
  75. }
  76. /**
  77. * Helper method for examining the xml signature
  78. *
  79. * @return the xml signature document
  80. * @throws IOException if the xml signature doesn't exist or can't be read
  81. * @throws XmlException if the xml signature is malformed
  82. */
  83. public SignatureDocument getSignatureDocument() throws IOException, XmlException {
  84. // TODO: check for XXE
  85. return SignatureDocument.Factory.parse(signaturePart.getInputStream(), DEFAULT_XML_OPTIONS);
  86. }
  87. /**
  88. * @return true, when the xml signature is valid, false otherwise
  89. *
  90. * @throws EncryptedDocumentException if the signature can't be extracted or if its malformed
  91. */
  92. public boolean validate() {
  93. KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
  94. XPath xpath = XPathFactory.newInstance().newXPath();
  95. xpath.setNamespaceContext(new XPathNSContext());
  96. try {
  97. Document doc = DocumentHelper.readDocument(signaturePart.getInputStream());
  98. NodeList nl = (NodeList)xpath.compile("//*[@Id]").evaluate(doc, XPathConstants.NODESET);
  99. final int length = nl.getLength();
  100. for (int i=0; i<length; i++) {
  101. ((Element)nl.item(i)).setIdAttribute("Id", true);
  102. }
  103. DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, doc);
  104. domValidateContext.setProperty(XMLSEC_VALIDATE_MANIFEST, Boolean.TRUE);
  105. domValidateContext.setURIDereferencer(signatureConfig.getUriDereferencer());
  106. XMLSignatureFactory xmlSignatureFactory = signatureConfig.getSignatureFactory();
  107. XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
  108. boolean valid = xmlSignature.validate(domValidateContext);
  109. if (valid) {
  110. signer = keySelector.getSigner();
  111. certChain = keySelector.getCertChain();
  112. extractConfig(doc, xmlSignature);
  113. }
  114. return valid;
  115. } catch (IOException e) {
  116. String s = "error in reading document";
  117. LOG.log(POILogger.ERROR, s, e);
  118. throw new EncryptedDocumentException(s, e);
  119. } catch (SAXException e) {
  120. String s = "error in parsing document";
  121. LOG.log(POILogger.ERROR, s, e);
  122. throw new EncryptedDocumentException(s, e);
  123. } catch (XPathExpressionException e) {
  124. String s = "error in searching document with xpath expression";
  125. LOG.log(POILogger.ERROR, s, e);
  126. throw new EncryptedDocumentException(s, e);
  127. } catch (MarshalException e) {
  128. String s = "error in unmarshalling the signature";
  129. LOG.log(POILogger.ERROR, s, e);
  130. throw new EncryptedDocumentException(s, e);
  131. } catch (XMLSignatureException e) {
  132. String s = "error in validating the signature";
  133. LOG.log(POILogger.ERROR, s, e);
  134. throw new EncryptedDocumentException(s, e);
  135. }
  136. }
  137. private void extractConfig(final Document doc, final XMLSignature xmlSignature) throws XPathExpressionException {
  138. if (!signatureConfig.isUpdateConfigOnValidate()) {
  139. return;
  140. }
  141. signatureConfig.setSigningCertificateChain(certChain);
  142. signatureConfig.setSignatureMethodFromUri(xmlSignature.getSignedInfo().getSignatureMethod().getAlgorithm());
  143. final XPath xpath = XPathFactory.newInstance().newXPath();
  144. xpath.setNamespaceContext(new XPathNSContext());
  145. final Map<String,Consumer<String>> m = new HashMap();
  146. m.put("//mdssi:SignatureTime/mdssi:Value", signatureConfig::setExecutionTime);
  147. m.put("//xd:ClaimedRole", signatureConfig::setXadesRole);
  148. m.put("//dsss:SignatureComments", signatureConfig::setSignatureDescription);
  149. m.put("//xd:QualifyingProperties//xd:SignedSignatureProperties//ds:DigestMethod/@Algorithm", signatureConfig::setXadesDigestAlgo);
  150. m.put("//ds:CanonicalizationMethod", signatureConfig::setCanonicalizationMethod);
  151. for (Map.Entry<String,Consumer<String>> me : m.entrySet()) {
  152. String val = (String)xpath.compile(me.getKey()).evaluate(doc, XPathConstants.STRING);
  153. me.getValue().accept(val);
  154. }
  155. }
  156. private class XPathNSContext implements NamespaceContext {
  157. final Map<String,String> nsMap = new HashMap<>();
  158. {
  159. signatureConfig.getNamespacePrefixes().forEach((k,v) -> nsMap.put(v,k));
  160. nsMap.put("dsss", MS_DIGSIG_NS);
  161. nsMap.put("ds", XML_DIGSIG_NS);
  162. }
  163. public String getNamespaceURI(String prefix) {
  164. return nsMap.get(prefix);
  165. }
  166. public Iterator getPrefixes(String val) {
  167. return null;
  168. }
  169. public String getPrefix(String uri) {
  170. return null;
  171. }
  172. }
  173. }