您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

XAdESXLSignatureFacet.java 17KB

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