Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

OOXMLSignatureAspect.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. * Based on the eID Applet Project code.
  17. * Original Copyright (C) 2008-2009 FedICT.
  18. */
  19. package org.apache.poi.ooxml.signature.service.signer.ooxml;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.net.URL;
  23. import java.security.InvalidAlgorithmParameterException;
  24. import java.security.NoSuchAlgorithmException;
  25. import java.util.Calendar;
  26. import java.util.LinkedList;
  27. import java.util.List;
  28. import java.util.TimeZone;
  29. import java.util.UUID;
  30. import java.util.zip.ZipEntry;
  31. import java.util.zip.ZipInputStream;
  32. import javax.xml.crypto.XMLStructure;
  33. import javax.xml.crypto.dom.DOMStructure;
  34. import javax.xml.crypto.dsig.DigestMethod;
  35. import javax.xml.crypto.dsig.Manifest;
  36. import javax.xml.crypto.dsig.Reference;
  37. import javax.xml.crypto.dsig.SignatureProperties;
  38. import javax.xml.crypto.dsig.SignatureProperty;
  39. import javax.xml.crypto.dsig.Transform;
  40. import javax.xml.crypto.dsig.XMLObject;
  41. import javax.xml.crypto.dsig.XMLSignatureFactory;
  42. import javax.xml.crypto.dsig.spec.TransformParameterSpec;
  43. import javax.xml.parsers.DocumentBuilder;
  44. import javax.xml.parsers.DocumentBuilderFactory;
  45. import javax.xml.parsers.ParserConfigurationException;
  46. import javax.xml.transform.TransformerException;
  47. import org.apache.commons.logging.Log;
  48. import org.apache.commons.logging.LogFactory;
  49. import org.apache.poi.ooxml.signature.service.signer.NoCloseInputStream;
  50. import org.apache.poi.ooxml.signature.service.signer.SignatureAspect;
  51. import org.apache.xml.security.utils.Constants;
  52. import org.apache.xpath.XPathAPI;
  53. import org.w3c.dom.Document;
  54. import org.w3c.dom.Element;
  55. import org.w3c.dom.Node;
  56. import org.w3c.dom.NodeList;
  57. import org.xml.sax.InputSource;
  58. import org.xml.sax.SAXException;
  59. /**
  60. * Office OpenXML Signature Aspect implementation.
  61. */
  62. final class OOXMLSignatureAspect implements SignatureAspect {
  63. private static final Log LOG = LogFactory.getLog(OOXMLSignatureAspect.class);
  64. private final AbstractOOXMLSignatureService _signatureService;
  65. public OOXMLSignatureAspect(AbstractOOXMLSignatureService signatureService) {
  66. _signatureService = signatureService;
  67. }
  68. public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<Reference> references, List<XMLObject> objects)
  69. throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
  70. LOG.debug("pre sign");
  71. addManifestObject(signatureFactory, document, signatureId, references, objects);
  72. addSignatureInfo(signatureFactory, document, signatureId, references, objects);
  73. }
  74. private void addManifestObject(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<Reference> references,
  75. List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
  76. Manifest manifest = constructManifest(signatureFactory);
  77. String objectId = "idPackageObject"; // really has to be this value.
  78. List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
  79. objectContent.add(manifest);
  80. addSignatureTime(signatureFactory, document, signatureId, objectContent);
  81. objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));
  82. DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
  83. Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null, "http://www.w3.org/2000/09/xmldsig#Object", null);
  84. references.add(reference);
  85. }
  86. private Manifest constructManifest(XMLSignatureFactory signatureFactory) throws NoSuchAlgorithmException,
  87. InvalidAlgorithmParameterException {
  88. List<Reference> manifestReferences = new LinkedList<Reference>();
  89. try {
  90. addRelationshipsReferences(signatureFactory, manifestReferences);
  91. } catch (Exception e) {
  92. throw new RuntimeException("error: " + e.getMessage(), e);
  93. }
  94. /*
  95. * Word
  96. */
  97. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", manifestReferences);
  98. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", manifestReferences);
  99. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", manifestReferences);
  100. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", manifestReferences);
  101. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.theme+xml", manifestReferences);
  102. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml", manifestReferences);
  103. /*
  104. * Powerpoint
  105. */
  106. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", manifestReferences);
  107. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml", manifestReferences);
  108. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml", manifestReferences);
  109. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", manifestReferences);
  110. addParts(signatureFactory, "application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml", manifestReferences);
  111. Manifest manifest = signatureFactory.newManifest(manifestReferences);
  112. return manifest;
  113. }
  114. private static void addSignatureTime(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<XMLStructure> objectContent) {
  115. /*
  116. * SignatureTime
  117. */
  118. Element signatureTimeElement = document.createElementNS("http://schemas.openxmlformats.org/package/2006/digital-signature", "mdssi:SignatureTime");
  119. signatureTimeElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:mdssi", "http://schemas.openxmlformats.org/package/2006/digital-signature");
  120. Element formatElement = document.createElementNS("http://schemas.openxmlformats.org/package/2006/digital-signature", "mdssi:Format");
  121. formatElement.setTextContent("YYYY-MM-DDThh:mm:ssTZD");
  122. signatureTimeElement.appendChild(formatElement);
  123. Element valueElement = document.createElementNS("http://schemas.openxmlformats.org/package/2006/digital-signature", "mdssi:Value");
  124. String now = formatTimestampAsISO8601(System.currentTimeMillis());
  125. LOG.debug("now: " + now);
  126. valueElement.setTextContent(now);
  127. signatureTimeElement.appendChild(valueElement);
  128. List<XMLStructure> signatureTimeContent = new LinkedList<XMLStructure>();
  129. signatureTimeContent.add(new DOMStructure(signatureTimeElement));
  130. SignatureProperty signatureTimeSignatureProperty = signatureFactory.newSignatureProperty(signatureTimeContent, "#" + signatureId, "idSignatureTime");
  131. List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>();
  132. signaturePropertyContent.add(signatureTimeSignatureProperty);
  133. SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent, "id-signature-time-"
  134. + UUID.randomUUID().toString());
  135. objectContent.add(signatureProperties);
  136. }
  137. /**
  138. * @return text formatted "YYYY-MM-DDThh:mm:ssTZD"
  139. */
  140. static String formatTimestampAsISO8601(long ts) {
  141. Calendar c = Calendar.getInstance();
  142. c.setTimeInMillis(ts);
  143. c.setTimeZone(TimeZone.getTimeZone("UTC"));
  144. char[] buf = "yyyy-mm-ddThh:mm:ssZ".toCharArray();
  145. itoa(buf, 0, 4, c.get(Calendar.YEAR));
  146. itoa(buf, 5, 2, c.get(Calendar.MONTH)+1);
  147. itoa(buf, 8, 2, c.get(Calendar.DAY_OF_MONTH));
  148. itoa(buf, 11, 2, c.get(Calendar.HOUR_OF_DAY));
  149. itoa(buf, 14, 2, c.get(Calendar.MINUTE));
  150. itoa(buf, 17, 2, c.get(Calendar.SECOND));
  151. return new String(buf);
  152. }
  153. private static void itoa(char[] buf, int start, int len, int value) {
  154. int acc = value;
  155. int i=start+len-1;
  156. while (i>=start) {
  157. int d = acc % 10;
  158. acc /= 10;
  159. buf[i] = (char) ('0' + d);
  160. i--;
  161. }
  162. }
  163. private void addSignatureInfo(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<Reference> references,
  164. List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
  165. List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
  166. Element signatureInfoElement = document.createElementNS("http://schemas.microsoft.com/office/2006/digsig", "SignatureInfoV1");
  167. signatureInfoElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "http://schemas.microsoft.com/office/2006/digsig");
  168. Element manifestHashAlgorithmElement = document.createElementNS("http://schemas.microsoft.com/office/2006/digsig", "ManifestHashAlgorithm");
  169. manifestHashAlgorithmElement.setTextContent("http://www.w3.org/2000/09/xmldsig#sha1");
  170. signatureInfoElement.appendChild(manifestHashAlgorithmElement);
  171. List<XMLStructure> signatureInfoContent = new LinkedList<XMLStructure>();
  172. signatureInfoContent.add(new DOMStructure(signatureInfoElement));
  173. SignatureProperty signatureInfoSignatureProperty = signatureFactory.newSignatureProperty(signatureInfoContent, "#" + signatureId, "idOfficeV1Details");
  174. List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>();
  175. signaturePropertyContent.add(signatureInfoSignatureProperty);
  176. SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent, null);
  177. objectContent.add(signatureProperties);
  178. String objectId = "idOfficeObject";
  179. objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));
  180. DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
  181. Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null, "http://www.w3.org/2000/09/xmldsig#Object", null);
  182. references.add(reference);
  183. }
  184. private void addRelationshipsReferences(XMLSignatureFactory signatureFactory, List<Reference> manifestReferences) throws IOException,
  185. ParserConfigurationException, SAXException, NoSuchAlgorithmException,
  186. InvalidAlgorithmParameterException {
  187. URL ooxmlUrl = _signatureService.getOfficeOpenXMLDocumentURL();
  188. InputStream inputStream = ooxmlUrl.openStream();
  189. ZipInputStream zipInputStream = new ZipInputStream(inputStream);
  190. ZipEntry zipEntry;
  191. while (null != (zipEntry = zipInputStream.getNextEntry())) {
  192. if (false == zipEntry.getName().endsWith(".rels")) {
  193. continue;
  194. }
  195. Document relsDocument = loadDocumentNoClose(zipInputStream);
  196. addRelationshipsReference(signatureFactory, zipEntry.getName(), relsDocument, manifestReferences);
  197. }
  198. }
  199. private void addRelationshipsReference(XMLSignatureFactory signatureFactory, String zipEntryName, Document relsDocument,
  200. List<Reference> manifestReferences) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
  201. LOG.debug("relationships: " + zipEntryName);
  202. RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec();
  203. NodeList nodeList = relsDocument.getDocumentElement().getChildNodes();
  204. for (int nodeIdx = 0; nodeIdx < nodeList.getLength(); nodeIdx++) {
  205. Node node = nodeList.item(nodeIdx);
  206. if (node.getNodeType() != Node.ELEMENT_NODE) {
  207. continue;
  208. }
  209. Element element = (Element) node;
  210. String relationshipType = element.getAttribute("Type");
  211. /*
  212. * We skip some relationship types.
  213. */
  214. if ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties".equals(relationshipType)) {
  215. continue;
  216. }
  217. if ("http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties".equals(relationshipType)) {
  218. continue;
  219. }
  220. if ("http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin".equals(relationshipType)) {
  221. continue;
  222. }
  223. if ("http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail".equals(relationshipType)) {
  224. continue;
  225. }
  226. if ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/presProps".equals(relationshipType)) {
  227. continue;
  228. }
  229. if ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/viewProps".equals(relationshipType)) {
  230. continue;
  231. }
  232. String relationshipId = element.getAttribute("Id");
  233. parameterSpec.addRelationshipReference(relationshipId);
  234. }
  235. List<Transform> transforms = new LinkedList<Transform>();
  236. transforms.add(signatureFactory.newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec));
  237. transforms.add(signatureFactory.newTransform("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", (TransformParameterSpec) null));
  238. DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
  239. Reference reference = signatureFactory.newReference("/" + zipEntryName + "?ContentType=application/vnd.openxmlformats-package.relationships+xml",
  240. digestMethod, transforms, null, null);
  241. manifestReferences.add(reference);
  242. }
  243. private void addParts(XMLSignatureFactory signatureFactory, String contentType, List<Reference> references) throws NoSuchAlgorithmException,
  244. InvalidAlgorithmParameterException {
  245. List<String> documentResourceNames;
  246. try {
  247. documentResourceNames = getResourceNames(_signatureService.getOfficeOpenXMLDocumentURL(), contentType);
  248. } catch (Exception e) {
  249. throw new RuntimeException(e);
  250. }
  251. DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
  252. for (String documentResourceName : documentResourceNames) {
  253. LOG.debug("document resource: " + documentResourceName);
  254. Reference reference = signatureFactory.newReference("/" + documentResourceName + "?ContentType=" + contentType, digestMethod);
  255. references.add(reference);
  256. }
  257. }
  258. private List<String> getResourceNames(URL url, String contentType) throws IOException, ParserConfigurationException, SAXException, TransformerException {
  259. List<String> signatureResourceNames = new LinkedList<String>();
  260. if (null == url) {
  261. throw new RuntimeException("OOXML URL is null");
  262. }
  263. InputStream inputStream = url.openStream();
  264. ZipInputStream zipInputStream = new ZipInputStream(inputStream);
  265. ZipEntry zipEntry;
  266. while (null != (zipEntry = zipInputStream.getNextEntry())) {
  267. if (false == "[Content_Types].xml".equals(zipEntry.getName())) {
  268. continue;
  269. }
  270. Document contentTypesDocument = loadDocument(zipInputStream);
  271. Element nsElement = contentTypesDocument.createElement("ns");
  272. nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "http://schemas.openxmlformats.org/package/2006/content-types");
  273. NodeList nodeList = XPathAPI.selectNodeList(contentTypesDocument, "/tns:Types/tns:Override[@ContentType='" + contentType + "']/@PartName",
  274. nsElement);
  275. for (int nodeIdx = 0; nodeIdx < nodeList.getLength(); nodeIdx++) {
  276. String partName = nodeList.item(nodeIdx).getTextContent();
  277. LOG.debug("part name: " + partName);
  278. partName = partName.substring(1); // remove '/'
  279. signatureResourceNames.add(partName);
  280. }
  281. break;
  282. }
  283. return signatureResourceNames;
  284. }
  285. protected Document loadDocument(String zipEntryName) throws IOException, ParserConfigurationException, SAXException {
  286. Document document = findDocument(zipEntryName);
  287. if (null != document) {
  288. return document;
  289. }
  290. throw new RuntimeException("ZIP entry not found: " + zipEntryName);
  291. }
  292. protected Document findDocument(String zipEntryName) throws IOException, ParserConfigurationException, SAXException {
  293. URL ooxmlUrl = _signatureService.getOfficeOpenXMLDocumentURL();
  294. InputStream inputStream = ooxmlUrl.openStream();
  295. ZipInputStream zipInputStream = new ZipInputStream(inputStream);
  296. ZipEntry zipEntry;
  297. while (null != (zipEntry = zipInputStream.getNextEntry())) {
  298. if (false == zipEntryName.equals(zipEntry.getName())) {
  299. continue;
  300. }
  301. Document document = loadDocument(zipInputStream);
  302. return document;
  303. }
  304. return null;
  305. }
  306. private Document loadDocumentNoClose(InputStream documentInputStream) throws ParserConfigurationException, SAXException, IOException {
  307. NoCloseInputStream noCloseInputStream = new NoCloseInputStream(documentInputStream);
  308. InputSource inputSource = new InputSource(noCloseInputStream);
  309. DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  310. documentBuilderFactory.setNamespaceAware(true);
  311. DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  312. Document document = documentBuilder.parse(inputSource);
  313. return document;
  314. }
  315. private Document loadDocument(InputStream documentInputStream) throws ParserConfigurationException, SAXException, IOException {
  316. InputSource inputSource = new InputSource(documentInputStream);
  317. DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  318. documentBuilderFactory.setNamespaceAware(true);
  319. DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  320. Document document = documentBuilder.parse(inputSource);
  321. return document;
  322. }
  323. }