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.

XAdESXLSignatureFacet.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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.facets;
  22. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  23. import static org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet.insertXChild;
  24. import java.io.ByteArrayInputStream;
  25. import java.io.ByteArrayOutputStream;
  26. import java.io.IOException;
  27. import java.math.BigInteger;
  28. import java.security.cert.CRLException;
  29. import java.security.cert.CertificateEncodingException;
  30. import java.security.cert.CertificateException;
  31. import java.security.cert.CertificateFactory;
  32. import java.security.cert.X509CRL;
  33. import java.security.cert.X509Certificate;
  34. import java.util.ArrayList;
  35. import java.util.Calendar;
  36. import java.util.Collections;
  37. import java.util.List;
  38. import java.util.Locale;
  39. import java.util.TimeZone;
  40. import java.util.UUID;
  41. import javax.xml.crypto.MarshalException;
  42. import org.apache.poi.poifs.crypt.dsig.SignatureConfig;
  43. import org.apache.poi.poifs.crypt.dsig.SignatureInfo;
  44. import org.apache.poi.poifs.crypt.dsig.services.RevocationData;
  45. import org.apache.poi.util.IOUtils;
  46. import org.apache.poi.util.POILogFactory;
  47. import org.apache.poi.util.POILogger;
  48. import org.apache.xml.security.c14n.Canonicalizer;
  49. import org.apache.xmlbeans.XmlException;
  50. import org.bouncycastle.asn1.ASN1InputStream;
  51. import org.bouncycastle.asn1.ASN1Integer;
  52. import org.bouncycastle.asn1.ASN1OctetString;
  53. import org.bouncycastle.asn1.DERTaggedObject;
  54. import org.bouncycastle.asn1.ocsp.ResponderID;
  55. import org.bouncycastle.asn1.x500.X500Name;
  56. import org.bouncycastle.asn1.x509.Extension;
  57. import org.bouncycastle.cert.ocsp.BasicOCSPResp;
  58. import org.bouncycastle.cert.ocsp.OCSPResp;
  59. import org.bouncycastle.cert.ocsp.RespID;
  60. import org.etsi.uri.x01903.v13.*;
  61. import org.etsi.uri.x01903.v14.ValidationDataType;
  62. import org.w3.x2000.x09.xmldsig.CanonicalizationMethodType;
  63. import org.w3c.dom.Document;
  64. import org.w3c.dom.Node;
  65. import org.w3c.dom.NodeList;
  66. /**
  67. * XAdES-X-L v1.4.1 signature facet. This signature facet implementation will
  68. * upgrade a given XAdES-BES/EPES signature to XAdES-X-L.
  69. *
  70. * We don't inherit from XAdESSignatureFacet as we also want to be able to use
  71. * this facet out of the context of a signature creation. This signature facet
  72. * assumes that the signature is already XAdES-BES/EPES compliant.
  73. *
  74. * This implementation has been tested against an implementation that
  75. * participated multiple ETSI XAdES plugtests.
  76. *
  77. * @author Frank Cornelis
  78. * @see XAdESSignatureFacet
  79. */
  80. public class XAdESXLSignatureFacet implements SignatureFacet {
  81. private static final POILogger LOG = POILogFactory.getLogger(XAdESXLSignatureFacet.class);
  82. private final CertificateFactory certificateFactory;
  83. public XAdESXLSignatureFacet() {
  84. try {
  85. this.certificateFactory = CertificateFactory.getInstance("X.509");
  86. } catch (CertificateException e) {
  87. throw new RuntimeException("X509 JCA error: " + e.getMessage(), e);
  88. }
  89. }
  90. @Override
  91. public void postSign(SignatureInfo signatureInfo, Document document) throws MarshalException {
  92. LOG.log(POILogger.DEBUG, "XAdES-X-L post sign phase");
  93. SignatureConfig signatureConfig = signatureInfo.getSignatureConfig();
  94. QualifyingPropertiesDocument qualDoc = null;
  95. QualifyingPropertiesType qualProps = null;
  96. // check for XAdES-BES
  97. NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");
  98. if (qualNl.getLength() == 1) {
  99. try {
  100. qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0), DEFAULT_XML_OPTIONS);
  101. } catch (XmlException e) {
  102. throw new MarshalException(e);
  103. }
  104. qualProps = qualDoc.getQualifyingProperties();
  105. } else {
  106. throw new MarshalException("no XAdES-BES extension present");
  107. }
  108. // create basic XML container structure
  109. UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties();
  110. if (unsignedProps == null) {
  111. unsignedProps = qualProps.addNewUnsignedProperties();
  112. }
  113. UnsignedSignaturePropertiesType unsignedSigProps = unsignedProps.getUnsignedSignatureProperties();
  114. if (unsignedSigProps == null) {
  115. unsignedSigProps = unsignedProps.addNewUnsignedSignatureProperties();
  116. }
  117. // create the XAdES-T time-stamp
  118. NodeList nlSigVal = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue");
  119. if (nlSigVal.getLength() != 1) {
  120. throw new IllegalArgumentException("SignatureValue is not set.");
  121. }
  122. RevocationData tsaRevocationDataXadesT = new RevocationData();
  123. LOG.log(POILogger.DEBUG, "creating XAdES-T time-stamp");
  124. XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp
  125. (signatureInfo, Collections.singletonList(nlSigVal.item(0)), tsaRevocationDataXadesT);
  126. // marshal the XAdES-T extension
  127. unsignedSigProps.addNewSignatureTimeStamp().set(signatureTimeStamp);
  128. // xadesv141::TimeStampValidationData
  129. if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
  130. ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
  131. insertXChild(unsignedSigProps, validationData);
  132. }
  133. if (signatureConfig.getRevocationDataService() == null) {
  134. /*
  135. * Without revocation data service we cannot construct the XAdES-C
  136. * extension.
  137. */
  138. return;
  139. }
  140. // XAdES-C: complete certificate refs
  141. CompleteCertificateRefsType completeCertificateRefs =
  142. unsignedSigProps.addNewCompleteCertificateRefs();
  143. CertIDListType certIdList = completeCertificateRefs.addNewCertRefs();
  144. /*
  145. * We skip the signing certificate itself according to section
  146. * 4.4.3.2 of the XAdES 1.4.1 specification.
  147. */
  148. List<X509Certificate> certChain = signatureConfig.getSigningCertificateChain();
  149. int chainSize = certChain.size();
  150. if (chainSize > 1) {
  151. for (X509Certificate cert : certChain.subList(1, chainSize)) {
  152. CertIDType certId = certIdList.addNewCert();
  153. XAdESSignatureFacet.setCertID(certId, signatureConfig, false, cert);
  154. }
  155. }
  156. // XAdES-C: complete revocation refs
  157. CompleteRevocationRefsType completeRevocationRefs =
  158. unsignedSigProps.addNewCompleteRevocationRefs();
  159. RevocationData revocationData = signatureConfig.getRevocationDataService()
  160. .getRevocationData(certChain);
  161. if (revocationData.hasCRLs()) {
  162. CRLRefsType crlRefs = completeRevocationRefs.addNewCRLRefs();
  163. completeRevocationRefs.setCRLRefs(crlRefs);
  164. for (byte[] encodedCrl : revocationData.getCRLs()) {
  165. CRLRefType crlRef = crlRefs.addNewCRLRef();
  166. X509CRL crl;
  167. try {
  168. crl = (X509CRL) this.certificateFactory
  169. .generateCRL(new ByteArrayInputStream(encodedCrl));
  170. } catch (CRLException e) {
  171. throw new RuntimeException("CRL parse error: "
  172. + e.getMessage(), e);
  173. }
  174. CRLIdentifierType crlIdentifier = crlRef.addNewCRLIdentifier();
  175. String issuerName = crl.getIssuerDN().getName().replace(",", ", ");
  176. crlIdentifier.setIssuer(issuerName);
  177. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
  178. cal.setTime(crl.getThisUpdate());
  179. crlIdentifier.setIssueTime(cal);
  180. crlIdentifier.setNumber(getCrlNumber(crl));
  181. DigestAlgAndValueType digestAlgAndValue = crlRef.addNewDigestAlgAndValue();
  182. XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, encodedCrl, signatureConfig.getDigestAlgo());
  183. }
  184. }
  185. if (revocationData.hasOCSPs()) {
  186. OCSPRefsType ocspRefs = completeRevocationRefs.addNewOCSPRefs();
  187. for (byte[] ocsp : revocationData.getOCSPs()) {
  188. try {
  189. OCSPRefType ocspRef = ocspRefs.addNewOCSPRef();
  190. DigestAlgAndValueType digestAlgAndValue = ocspRef.addNewDigestAlgAndValue();
  191. XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, ocsp, signatureConfig.getDigestAlgo());
  192. OCSPIdentifierType ocspIdentifier = ocspRef.addNewOCSPIdentifier();
  193. OCSPResp ocspResp = new OCSPResp(ocsp);
  194. BasicOCSPResp basicOcspResp = (BasicOCSPResp)ocspResp.getResponseObject();
  195. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
  196. cal.setTime(basicOcspResp.getProducedAt());
  197. ocspIdentifier.setProducedAt(cal);
  198. ResponderIDType responderId = ocspIdentifier.addNewResponderID();
  199. RespID respId = basicOcspResp.getResponderId();
  200. ResponderID ocspResponderId = respId.toASN1Primitive();
  201. DERTaggedObject derTaggedObject = (DERTaggedObject)ocspResponderId.toASN1Primitive();
  202. if (2 == derTaggedObject.getTagNo()) {
  203. ASN1OctetString keyHashOctetString = (ASN1OctetString)derTaggedObject.getObject();
  204. byte[] key = keyHashOctetString.getOctets();
  205. responderId.setByKey(key);
  206. } else {
  207. X500Name name = X500Name.getInstance(derTaggedObject.getObject());
  208. String nameStr = name.toString();
  209. responderId.setByName(nameStr);
  210. }
  211. } catch (Exception e) {
  212. throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
  213. }
  214. }
  215. }
  216. // marshal XAdES-C
  217. // XAdES-X Type 1 timestamp
  218. List<Node> timeStampNodesXadesX1 = new ArrayList<>();
  219. timeStampNodesXadesX1.add(nlSigVal.item(0));
  220. timeStampNodesXadesX1.add(signatureTimeStamp.getDomNode());
  221. timeStampNodesXadesX1.add(completeCertificateRefs.getDomNode());
  222. timeStampNodesXadesX1.add(completeRevocationRefs.getDomNode());
  223. RevocationData tsaRevocationDataXadesX1 = new RevocationData();
  224. LOG.log(POILogger.DEBUG, "creating XAdES-X time-stamp");
  225. XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp
  226. (signatureInfo, timeStampNodesXadesX1, tsaRevocationDataXadesX1);
  227. if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
  228. ValidationDataType timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
  229. insertXChild(unsignedSigProps, timeStampXadesX1ValidationData);
  230. }
  231. // marshal XAdES-X
  232. unsignedSigProps.addNewSigAndRefsTimeStamp().set(timeStampXadesX1);
  233. // XAdES-X-L
  234. CertificateValuesType certificateValues = unsignedSigProps.addNewCertificateValues();
  235. for (X509Certificate certificate : certChain) {
  236. EncapsulatedPKIDataType encapsulatedPKIDataType = certificateValues.addNewEncapsulatedX509Certificate();
  237. try {
  238. encapsulatedPKIDataType.setByteArrayValue(certificate.getEncoded());
  239. } catch (CertificateEncodingException e) {
  240. throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
  241. }
  242. }
  243. RevocationValuesType revocationValues = unsignedSigProps.addNewRevocationValues();
  244. createRevocationValues(revocationValues, revocationData);
  245. // marshal XAdES-X-L
  246. Node n = document.importNode(qualProps.getDomNode(), true);
  247. qualNl.item(0).getParentNode().replaceChild(n, qualNl.item(0));
  248. }
  249. public static byte[] getC14nValue(List<Node> nodeList, String c14nAlgoId) {
  250. ByteArrayOutputStream c14nValue = new ByteArrayOutputStream();
  251. try {
  252. for (Node node : nodeList) {
  253. /*
  254. * Re-initialize the c14n else the namespaces will get cached
  255. * and will be missing from the c14n resulting nodes.
  256. */
  257. Canonicalizer c14n = Canonicalizer.getInstance(c14nAlgoId);
  258. c14n.canonicalizeSubtree(node, c14nValue);
  259. }
  260. } catch (RuntimeException e) {
  261. throw e;
  262. } catch (Exception e) {
  263. throw new RuntimeException("c14n error: " + e.getMessage(), e);
  264. }
  265. return c14nValue.toByteArray();
  266. }
  267. private BigInteger getCrlNumber(X509CRL crl) {
  268. byte[] crlNumberExtensionValue = crl.getExtensionValue(Extension.cRLNumber.getId());
  269. if (null == crlNumberExtensionValue) {
  270. return null;
  271. }
  272. try {
  273. ASN1InputStream asn1IS1 = null, asn1IS2 = null;
  274. try {
  275. asn1IS1 = new ASN1InputStream(crlNumberExtensionValue);
  276. ASN1OctetString octetString = (ASN1OctetString)asn1IS1.readObject();
  277. byte[] octets = octetString.getOctets();
  278. asn1IS2 = new ASN1InputStream(octets);
  279. ASN1Integer integer = (ASN1Integer)asn1IS2.readObject();
  280. return integer.getPositiveValue();
  281. } finally {
  282. IOUtils.closeQuietly(asn1IS2);
  283. IOUtils.closeQuietly(asn1IS1);
  284. }
  285. } catch (IOException e) {
  286. throw new RuntimeException("I/O error: " + e.getMessage(), e);
  287. }
  288. }
  289. private XAdESTimeStampType createXAdESTimeStamp(
  290. SignatureInfo signatureInfo,
  291. List<Node> nodeList,
  292. RevocationData revocationData) {
  293. SignatureConfig signatureConfig = signatureInfo.getSignatureConfig();
  294. byte[] c14nSignatureValueElement = getC14nValue(nodeList, signatureConfig.getXadesCanonicalizationMethod());
  295. return createXAdESTimeStamp(signatureInfo, c14nSignatureValueElement, revocationData);
  296. }
  297. private XAdESTimeStampType createXAdESTimeStamp(SignatureInfo signatureInfo, byte[] data, RevocationData revocationData) {
  298. SignatureConfig signatureConfig = signatureInfo.getSignatureConfig();
  299. // create the time-stamp
  300. byte[] timeStampToken;
  301. try {
  302. timeStampToken = signatureConfig.getTspService().timeStamp(signatureInfo, data, revocationData);
  303. } catch (Exception e) {
  304. throw new RuntimeException("error while creating a time-stamp: "
  305. + e.getMessage(), e);
  306. }
  307. // create a XAdES time-stamp container
  308. XAdESTimeStampType xadesTimeStamp = XAdESTimeStampType.Factory.newInstance();
  309. xadesTimeStamp.setId("time-stamp-" + UUID.randomUUID());
  310. CanonicalizationMethodType c14nMethod = xadesTimeStamp.addNewCanonicalizationMethod();
  311. c14nMethod.setAlgorithm(signatureConfig.getXadesCanonicalizationMethod());
  312. // embed the time-stamp
  313. EncapsulatedPKIDataType encapsulatedTimeStamp = xadesTimeStamp.addNewEncapsulatedTimeStamp();
  314. encapsulatedTimeStamp.setByteArrayValue(timeStampToken);
  315. encapsulatedTimeStamp.setId("time-stamp-token-" + UUID.randomUUID());
  316. return xadesTimeStamp;
  317. }
  318. private ValidationDataType createValidationData(
  319. RevocationData revocationData) {
  320. ValidationDataType validationData = ValidationDataType.Factory.newInstance();
  321. RevocationValuesType revocationValues = validationData.addNewRevocationValues();
  322. createRevocationValues(revocationValues, revocationData);
  323. return validationData;
  324. }
  325. private void createRevocationValues(
  326. RevocationValuesType revocationValues, RevocationData revocationData) {
  327. if (revocationData.hasCRLs()) {
  328. CRLValuesType crlValues = revocationValues.addNewCRLValues();
  329. for (byte[] crl : revocationData.getCRLs()) {
  330. EncapsulatedPKIDataType encapsulatedCrlValue = crlValues.addNewEncapsulatedCRLValue();
  331. encapsulatedCrlValue.setByteArrayValue(crl);
  332. }
  333. }
  334. if (revocationData.hasOCSPs()) {
  335. OCSPValuesType ocspValues = revocationValues.addNewOCSPValues();
  336. for (byte[] ocsp : revocationData.getOCSPs()) {
  337. EncapsulatedPKIDataType encapsulatedOcspValue = ocspValues.addNewEncapsulatedOCSPValue();
  338. encapsulatedOcspValue.setByteArrayValue(ocsp);
  339. }
  340. }
  341. }
  342. }