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 19KB

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