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.

RelationshipTransformService.java 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. /* ====================================================================
  16. This product contains an ASLv2 licensed version of the OOXML signer
  17. package from the eID Applet project
  18. http://code.google.com/p/eid-applet/source/browse/trunk/README.txt
  19. Copyright (C) 2008-2014 FedICT.
  20. ================================================================= */
  21. package org.apache.poi.poifs.crypt.dsig.services;
  22. import static org.apache.logging.log4j.util.Unbox.box;
  23. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  24. import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS;
  25. import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_NS;
  26. import java.io.InputStream;
  27. import java.io.OutputStream;
  28. import java.security.InvalidAlgorithmParameterException;
  29. import java.security.Provider;
  30. import java.security.Security;
  31. import java.security.spec.AlgorithmParameterSpec;
  32. import java.util.ArrayList;
  33. import java.util.List;
  34. import java.util.TreeMap;
  35. import javax.xml.crypto.Data;
  36. import javax.xml.crypto.MarshalException;
  37. import javax.xml.crypto.OctetStreamData;
  38. import javax.xml.crypto.XMLCryptoContext;
  39. import javax.xml.crypto.XMLStructure;
  40. import javax.xml.crypto.dom.DOMStructure;
  41. import javax.xml.crypto.dsig.TransformException;
  42. import javax.xml.crypto.dsig.TransformService;
  43. import javax.xml.crypto.dsig.spec.TransformParameterSpec;
  44. import org.apache.jcp.xml.dsig.internal.dom.ApacheNodeSetData;
  45. import org.apache.logging.log4j.LogManager;
  46. import org.apache.logging.log4j.Logger;
  47. import org.apache.poi.ooxml.util.DocumentHelper;
  48. import org.apache.poi.util.SuppressForbidden;
  49. import org.apache.xml.security.signature.XMLSignatureInput;
  50. import org.apache.xmlbeans.XmlException;
  51. import org.apache.xmlbeans.XmlObject;
  52. import org.openxmlformats.schemas.xpackage.x2006.digitalSignature.CTRelationshipReference;
  53. import org.openxmlformats.schemas.xpackage.x2006.digitalSignature.RelationshipReferenceDocument;
  54. import org.w3.x2000.x09.xmldsig.TransformDocument;
  55. import org.w3c.dom.Document;
  56. import org.w3c.dom.Element;
  57. import org.w3c.dom.Node;
  58. import org.w3c.dom.NodeList;
  59. /**
  60. * JSR105 implementation of the RelationshipTransform transformation.
  61. *
  62. * <p>
  63. * Specs: http://openiso.org/Ecma/376/Part2/12.2.4#26
  64. * </p>
  65. */
  66. public class RelationshipTransformService extends TransformService {
  67. public static final String TRANSFORM_URI = "http://schemas.openxmlformats.org/package/2006/RelationshipTransform";
  68. private final List<String> sourceIds;
  69. private static final Logger LOG = LogManager.getLogger(RelationshipTransformService.class);
  70. /**
  71. * Relationship Transform parameter specification class.
  72. */
  73. public static class RelationshipTransformParameterSpec implements TransformParameterSpec {
  74. List<String> sourceIds = new ArrayList<>();
  75. public void addRelationshipReference(String relationshipId) {
  76. sourceIds.add(relationshipId);
  77. }
  78. public boolean hasSourceIds() {
  79. return !sourceIds.isEmpty();
  80. }
  81. }
  82. @SuppressForbidden("new Provider(String,String,String) is not available in Java 8")
  83. private static final class POIXmlDsigProvider extends Provider {
  84. static final long serialVersionUID = 1L;
  85. private static final String NAME = "POIXmlDsigProvider";
  86. private POIXmlDsigProvider() {
  87. super(NAME, 1d, NAME);
  88. put("TransformService." + TRANSFORM_URI, RelationshipTransformService.class.getName());
  89. put("TransformService." + TRANSFORM_URI + " MechanismType", "DOM");
  90. }
  91. }
  92. public RelationshipTransformService() {
  93. super();
  94. LOG.atDebug().log("constructor");
  95. this.sourceIds = new ArrayList<>();
  96. }
  97. /**
  98. * Register the provider for this TransformService
  99. *
  100. * @see TransformService
  101. */
  102. public static synchronized void registerDsigProvider() {
  103. // the xml signature classes will try to find a special TransformerService,
  104. // which is of course unknown to JCE before ...
  105. if (Security.getProvider(POIXmlDsigProvider.NAME) == null) {
  106. Security.addProvider(new POIXmlDsigProvider());
  107. }
  108. }
  109. @Override
  110. public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException {
  111. LOG.atDebug().log("init(params)");
  112. if (!(params instanceof RelationshipTransformParameterSpec)) {
  113. throw new InvalidAlgorithmParameterException();
  114. }
  115. RelationshipTransformParameterSpec relParams = (RelationshipTransformParameterSpec) params;
  116. this.sourceIds.addAll(relParams.sourceIds);
  117. }
  118. @Override
  119. public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException {
  120. LOG.atDebug().log("init(parent,context)");
  121. LOG.atDebug().log("parent java type: {}", parent.getClass().getName());
  122. DOMStructure domParent = (DOMStructure) parent;
  123. Node parentNode = domParent.getNode();
  124. try {
  125. TransformDocument transDoc = TransformDocument.Factory.parse(parentNode, DEFAULT_XML_OPTIONS);
  126. XmlObject[] xoList = transDoc.getTransform().selectChildren(RelationshipReferenceDocument.type.getDocumentElementName());
  127. if (xoList.length == 0) {
  128. LOG.atWarn().log("no RelationshipReference/@SourceId parameters present");
  129. }
  130. for (XmlObject xo : xoList) {
  131. String sourceId = ((CTRelationshipReference)xo).getSourceId();
  132. LOG.atDebug().log("sourceId: {}", sourceId);
  133. this.sourceIds.add(sourceId);
  134. }
  135. } catch (XmlException e) {
  136. throw new InvalidAlgorithmParameterException(e);
  137. }
  138. }
  139. @Override
  140. public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException {
  141. LOG.atDebug().log("marshallParams(parent,context)");
  142. DOMStructure domParent = (DOMStructure) parent;
  143. Element parentNode = (Element)domParent.getNode();
  144. Document doc = parentNode.getOwnerDocument();
  145. for (String sourceId : this.sourceIds) {
  146. Element el = doc.createElementNS(OO_DIGSIG_NS, "mdssi:RelationshipReference");
  147. el.setAttributeNS(XML_NS, "xmlns:mdssi", OO_DIGSIG_NS);
  148. el.setAttribute("SourceId", sourceId);
  149. parentNode.appendChild(el);
  150. }
  151. }
  152. public AlgorithmParameterSpec getParameterSpec() {
  153. LOG.atDebug().log("getParameterSpec");
  154. return null;
  155. }
  156. /**
  157. * The relationships transform takes the XML document from the Relationships part
  158. * and converts it to another XML document.
  159. *
  160. * @see <a href="https://www.ecma-international.org/activities/Office%20Open%20XML%20Formats/Draft%20ECMA-376%203rd%20edition,%20March%202011/Office%20Open%20XML%20Part%202%20-%20Open%20Packaging%20Conventions.pdf">13.2.4.24 Relationships Transform Algorithm</a>
  161. */
  162. public Data transform(Data data, XMLCryptoContext context) throws TransformException {
  163. LOG.atDebug().log("transform(data,context)");
  164. LOG.atDebug().log("data java type: {}", data.getClass().getName());
  165. OctetStreamData octetStreamData = (OctetStreamData) data;
  166. LOG.atDebug().log("URI: {}", octetStreamData.getURI());
  167. InputStream octetStream = octetStreamData.getOctetStream();
  168. Document doc;
  169. try {
  170. doc = DocumentHelper.readDocument(octetStream);
  171. } catch (Exception e) {
  172. throw new TransformException(e.getMessage(), e);
  173. }
  174. // keep only those relationships which id is registered in the sourceIds
  175. Element root = doc.getDocumentElement();
  176. NodeList nl = root.getChildNodes();
  177. TreeMap<String,Element> rsList = new TreeMap<>();
  178. for (int i=nl.getLength()-1; i>=0; i--) {
  179. Node n = nl.item(i);
  180. if ("Relationship".equals(n.getLocalName())) {
  181. Element el = (Element)n;
  182. String id = el.getAttribute("Id");
  183. if (sourceIds.contains(id)) {
  184. String targetMode = el.getAttribute("TargetMode");
  185. if (targetMode == null || targetMode.isEmpty()) {
  186. el.setAttribute("TargetMode", "Internal");
  187. }
  188. rsList.put(id, el);
  189. }
  190. }
  191. root.removeChild(n);
  192. }
  193. for (Element el : rsList.values()) {
  194. root.appendChild(el);
  195. }
  196. LOG.atDebug().log("# Relationship elements: {}", box(rsList.size()));
  197. return new ApacheNodeSetData(new XMLSignatureInput(root));
  198. }
  199. public Data transform(Data data, XMLCryptoContext context, OutputStream os) throws TransformException {
  200. LOG.atDebug().log("transform(data,context,os)");
  201. return null;
  202. }
  203. public boolean isFeatureSupported(String feature) {
  204. LOG.atDebug().log("isFeatureSupported(feature)");
  205. return false;
  206. }
  207. }