List of usage examples for javax.xml.crypto.dsig XMLSignature getId
String getId();
XMLSignature
. From source file:be.fedict.eid.dss.document.ooxml.OOXMLDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception { if (null != originalDocument) { throw new IllegalArgumentException("cannot perform original document verifications"); }//from w w w .j a va2 s . c o m OOXMLSignatureVerifier ooxmlSignatureVerifier = new OOXMLSignatureVerifier(); List<String> signatureResourceNames = ooxmlSignatureVerifier.getSignatureResourceNames(document); List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); XAdESValidation xadesValidation = new XAdESValidation(this.documentContext); for (String signatureResourceName : signatureResourceNames) { LOG.debug("signatureResourceName: " + signatureResourceName); Document signatureDocument = ooxmlSignatureVerifier .getSignatureDocument(new ByteArrayInputStream(document), signatureResourceName); if (null == signatureDocument) { continue; } NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { continue; } Element signatureElement = (Element) signatureNodeList.item(0); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); LOG.debug("validating signature: " + xmlSignature.getId()); boolean valid = xmlSignature.validate(domValidateContext); LOG.debug("signature valid: " + valid); if (!valid) { LOG.error("signature invalid"); continue; } // check OOXML's XML DSig/XAdES requirements if (!ooxmlSignatureVerifier.isValidOOXMLSignature(xmlSignature, document)) { LOG.error("Invalid OOXML Signature"); continue; } X509Certificate signingCertificate = keySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(signatureDocument, xmlSignature, signatureElement, signingCertificate); signatureInfos.add(signatureInfo); } return signatureInfos; }
From source file:be.fedict.eid.dss.document.xml.XMLDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] documentData, byte[] originalDocument) throws Exception { Document document = this.documentBuilder.parse(new ByteArrayInputStream(documentData)); List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { LOG.debug("no XML signature found"); return signatureInfos; }//w w w. ja v a2 s .c o m XAdESValidation xadesValidation = new XAdESValidation(this.context); for (int signatureNodeIdx = 0; signatureNodeIdx < signatureNodeList.getLength(); signatureNodeIdx++) { /* * Check signature. */ Element signatureElement = (Element) signatureNodeList.item(signatureNodeIdx); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keyInfoKeySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keyInfoKeySelector, signatureElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI()); XMLSignature xmlSignature; try { xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); } catch (MarshalException e) { LOG.error("XML signature marshalling error: " + e.getMessage(), e); continue; } LOG.debug("validating signature: " + xmlSignature.getId()); boolean signatureValid = xmlSignature.validate(domValidateContext); LOG.debug("signature valid: " + signatureValid); if (!signatureValid) { LOG.error("invalid signature"); throw new RuntimeException("invalid signature"); } if (null != originalDocument) { Document originalDomDocument = XAdESUtils.loadDocument(originalDocument); LOG.debug("performing original document verification"); verifyCoSignatureReference(xmlSignature, originalDomDocument); LOG.debug("original document verified"); } else { /* * We can still check whether the co-signature ds:Reference is * indeed doing a co-signature. */ verifyCoSignatureReference(xmlSignature, document); } X509Certificate signingCertificate = keyInfoKeySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(document, xmlSignature, signatureElement, signingCertificate); signatureInfos.add(signatureInfo); } return signatureInfos; }
From source file:be.fedict.eid.dss.spi.utils.XAdESValidation.java
public SignatureInfo validate(Document document, XMLSignature xmlSignature, Element signatureElement, X509Certificate signingCertificate) throws XAdESValidationException { try {/*from w ww . j a v a 2 s .com*/ /* * Get signing time from XAdES-BES extension. */ Element nsElement = getNsElement(document); Element qualifyingPropertiesElement = XAdESUtils.findQualifyingPropertiesElement(nsElement, xmlSignature, signatureElement); if (null == qualifyingPropertiesElement) { throw new XAdESValidationException("no matching xades:QualifyingProperties present"); } QualifyingPropertiesType qualifyingProperties = XAdESUtils.unmarshall(qualifyingPropertiesElement, QualifyingPropertiesType.class); if (false == qualifyingProperties.getTarget().equals("#" + xmlSignature.getId())) { throw new XAdESValidationException("xades:QualifyingProperties/@Target incorrect"); } SignedPropertiesType signedProperties = qualifyingProperties.getSignedProperties(); SignedSignaturePropertiesType signedSignatureProperties = signedProperties .getSignedSignatureProperties(); XMLGregorianCalendar signingTimeXMLGregorianCalendar = signedSignatureProperties.getSigningTime(); DateTime signingTime = new DateTime(signingTimeXMLGregorianCalendar.toGregorianCalendar().getTime()); LOG.debug("XAdES signing time: " + signingTime); /* * Check the XAdES signing certificate */ XAdESUtils.checkSigningCertificate(signingCertificate, signedSignatureProperties); /* * Get XAdES ClaimedRole. */ String role = null; SignerRoleType signerRole = signedSignatureProperties.getSignerRole(); if (null != signerRole) { ClaimedRolesListType claimedRolesList = signerRole.getClaimedRoles(); if (null != claimedRolesList) { List<AnyType> claimedRoles = claimedRolesList.getClaimedRole(); if (!claimedRoles.isEmpty()) { AnyType claimedRole = claimedRoles.get(0); List<Object> claimedRoleContent = claimedRole.getContent(); for (Object claimedRoleContentItem : claimedRoleContent) { if (claimedRoleContentItem instanceof String) { role = (String) claimedRoleContentItem; LOG.debug("XAdES claimed role: " + role); break; } } } } } // XAdES-T // validate first SignatureTimeStamp Element signatureTimeStampElement = XAdESUtils .findUnsignedSignaturePropertyElement(qualifyingPropertiesElement, "SignatureTimeStamp"); if (null == signatureTimeStampElement) { throw new XAdESValidationException("no xades:SignatureTimeStamp present"); } XAdESTimeStampType signatureTimeStamp = XAdESUtils.unmarshall(signatureTimeStampElement, XAdESTimeStampType.class); List<TimeStampToken> signatureTimeStampTokens = XAdESSignatureTimeStampValidation .verify(signatureTimeStamp, signatureElement); // XAdES-X // validate first SigAndRefsTimeStamp Element sigAndRefsTimeStampElement = XAdESUtils .findUnsignedSignaturePropertyElement(qualifyingPropertiesElement, "SigAndRefsTimeStamp"); if (null == sigAndRefsTimeStampElement) { LOG.error("No SigAndRefsTimeStamp present"); throw new XAdESValidationException("no xades:SigAndRefsTimeStamp present"); } XAdESTimeStampType sigAndRefsTimeStamp = XAdESUtils.unmarshall(sigAndRefsTimeStampElement, XAdESTimeStampType.class); List<TimeStampToken> sigAndRefsTimeStampTokens = XAdESSigAndRefsTimeStampValidation .verify(sigAndRefsTimeStamp, signatureElement); // timestamp tokens trust validation LOG.debug("validate SignatureTimeStamp's trust..."); ValidationDataType signatureTimeStampValidationData = XAdESUtils.findNextSibling( signatureTimeStampElement, XAdESUtils.XADES_141_NS_URI, "TimeStampValidationData", ValidationDataType.class); if (null != signatureTimeStampValidationData) { LOG.debug("xadesv141:TimeStampValidationData present for xades:SignatureTimeStamp"); RevocationValuesType revocationValues = signatureTimeStampValidationData.getRevocationValues(); List<X509CRL> crls = XAdESUtils.getCrls(revocationValues); List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues); for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) { this.documentContext.validate(signatureTimeStampToken, ocspResponses, crls); } } else { for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) { this.documentContext.validate(signatureTimeStampToken); } } LOG.debug("validate SigAndRefsTimeStamp's trust..."); ValidationDataType sigAndRefsTimeStampValidationData = XAdESUtils.findNextSibling( sigAndRefsTimeStampElement, XAdESUtils.XADES_141_NS_URI, "TimeStampValidationData", ValidationDataType.class); if (null != sigAndRefsTimeStampValidationData) { LOG.debug("xadesv141:TimeStampValidationData present for xades:SigAndRefsTimeStamp"); RevocationValuesType revocationValues = sigAndRefsTimeStampValidationData.getRevocationValues(); List<X509CRL> crls = XAdESUtils.getCrls(revocationValues); List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues); for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) { this.documentContext.validate(sigAndRefsTimeStampToken, ocspResponses, crls); } } else { for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) { this.documentContext.validate(sigAndRefsTimeStampToken); } } // timestamp tokens time coherence verification long timestampMaxOffset = this.documentContext.getTimestampMaxOffset(); LOG.debug("validate timestamp tokens time coherence..."); for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) { DateTime stsTokenGenTime = new DateTime(signatureTimeStampToken.getTimeStampInfo().getGenTime()); try { XAdESUtils.checkCloseEnough(signingTime, stsTokenGenTime, timestampMaxOffset); } catch (XAdESValidationException e) { throw new XAdESValidationException("SignatureTimeStamp too far from SigningTime", e); } for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) { DateTime sigAndRefsTokenGenTime = new DateTime( sigAndRefsTimeStampToken.getTimeStampInfo().getGenTime()); if (sigAndRefsTokenGenTime.isBefore(stsTokenGenTime)) { throw new XAdESValidationException("SigAndRefsTimeStamp before SignatureTimeStamp"); } } } long maxGracePeriod = this.documentContext.getMaxGracePeriod(); for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) { DateTime sigAndRefsTokenGenTime = new DateTime( sigAndRefsTimeStampToken.getTimeStampInfo().getGenTime()); try { XAdESUtils.checkCloseEnough(signingTime, sigAndRefsTokenGenTime, maxGracePeriod * 1000 * 60 * 60); } catch (XAdESValidationException e) { throw new XAdESValidationException("SigAndRefsTimeStamp too far from SigningTime", e); } } // XAdES-X-L /* * Retrieve certificate chain and revocation data from XAdES-X-L * extension for trust validation. */ RevocationValuesType revocationValues = XAdESUtils.findUnsignedSignatureProperty(qualifyingProperties, RevocationValuesType.class, "RevocationValues"); List<X509CRL> crls = XAdESUtils.getCrls(revocationValues); List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues); CertificateValuesType certificateValues = XAdESUtils.findUnsignedSignatureProperty(qualifyingProperties, CertificateValuesType.class, "CertificateValues"); if (null == certificateValues) { throw new XAdESValidationException("no CertificateValues element found."); } List<X509Certificate> certificateChain = XAdESUtils.getCertificates(certificateValues); if (certificateChain.isEmpty()) { throw new XAdESValidationException("no cert chain in CertificateValues"); } /* * Check certificate chain is indeed contains the signing * certificate. */ if (!Arrays.equals(signingCertificate.getEncoded(), certificateChain.get(0).getEncoded())) { // throw new XAdESValidationException( // "XAdES certificate chain does not include actual signing certificate"); /* * Not all XAdES implementations add the entire certificate * chain via xades:CertificateValues. */ certificateChain.add(0, signingCertificate); } LOG.debug("XAdES certificate chain contains actual signing certificate"); // XAdES-C CompleteCertificateRefsType completeCertificateRefs = XAdESUtils.findUnsignedSignatureProperty( qualifyingProperties, CompleteCertificateRefsType.class, "CompleteCertificateRefs"); if (null == completeCertificateRefs) { throw new XAdESValidationException("missing CompleteCertificateRefs"); } CompleteRevocationRefsType completeRevocationRefs = XAdESUtils.findUnsignedSignatureProperty( qualifyingProperties, CompleteRevocationRefsType.class, "CompleteRevocationRefs"); if (null == completeRevocationRefs) { throw new XAdESValidationException("missing CompleteRevocationRefs"); } for (OCSPResp ocspResp : ocspResponses) { XAdESUtils.checkReference(ocspResp, completeRevocationRefs); } for (X509CRL crl : crls) { XAdESUtils.checkReference(crl, completeRevocationRefs); } Iterator<X509Certificate> certIterator = certificateChain.iterator(); certIterator.next(); // digestion of SigningCertificate already // checked while (certIterator.hasNext()) { X509Certificate certificate = certIterator.next(); XAdESUtils.checkReference(certificate, completeCertificateRefs); } /* * Perform trust validation via eID Trust Service */ this.documentContext.validate(certificateChain, signingTime.toDate(), ocspResponses, crls); /* * Retrieve the possible eID identity signature extension data. */ String firstName = null; String name = null; String middleName = null; SignatureInfo.Gender gender = null; byte[] photo = null; IdentityType identity = XAdESUtils.findIdentity(nsElement, xmlSignature, signatureElement); if (null != identity) { firstName = identity.getFirstName(); name = identity.getName(); middleName = identity.getMiddleName(); switch (identity.getGender()) { case MALE: gender = SignatureInfo.Gender.MALE; break; case FEMALE: gender = SignatureInfo.Gender.FEMALE; break; } photo = identity.getPhoto().getValue(); } /* * Return the result of the signature analysis. */ return new SignatureInfo(signingCertificate, signingTime.toDate(), role, firstName, name, middleName, gender, photo); } catch (CertificateEncodingException e) { throw new XAdESValidationException(e); } catch (Exception e) { throw new XAdESValidationException(e); } }
From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java
@SuppressWarnings("unchecked") public boolean isValidOOXMLSignature(XMLSignature xmlSignature, byte[] document) throws IOException, TransformerException, SAXException, ParserConfigurationException { // check c18n == http://www.w3.org/TR/2001/REC-xml-c14n-20010315 if (!xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm() .equals(CanonicalizationMethod.INCLUSIVE)) { LOG.error("Invalid c18n method on OOXML Signature"); return false; }/*from w ww . ja v a2s . co m*/ List<Reference> refs = xmlSignature.getSignedInfo().getReferences(); // check #idPackageObject reference Reference idPackageObjectRef = findReferenceFromURI(refs, "#idPackageObject"); if (null == idPackageObjectRef) { LOG.error("No \"idPackageObject\" reference found!"); return false; } // check idPackageObject element XMLObject idPackageObject = findObject(xmlSignature, "idPackageObject"); if (null == idPackageObject) { LOG.error("No \"idPackageObject\" object found!"); return false; } if (!isIdPackageObjectValid(xmlSignature.getId(), idPackageObject, document)) { LOG.error("Invalid \"idPackageObject\"."); return false; } // check #idOfficeObject reference Reference idOfficeObjectRef = findReferenceFromURI(refs, "#idOfficeObject"); if (null == idOfficeObjectRef) { LOG.error("No \"idOfficeObject\" reference found!"); return false; } // check idOfficeObject element XMLObject idOfficeObject = findObject(xmlSignature, "idOfficeObject"); if (null == idOfficeObject) { LOG.error("No \"idOfficeObject\" object found!"); return false; } if (!isIdOfficeObjectValid(xmlSignature.getId(), idOfficeObject)) { LOG.error("Invalid \"idOfficeObject\"."); return false; } return true; }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMXMLSignature.java
@Override public boolean equals(Object o) { if (this == o) { return true; }/*from w ww .j a va 2 s .com*/ if (!(o instanceof XMLSignature)) { return false; } XMLSignature osig = (XMLSignature) o; boolean idEqual = (id == null ? osig.getId() == null : id.equals(osig.getId())); boolean keyInfoEqual = (ki == null ? osig.getKeyInfo() == null : ki.equals(osig.getKeyInfo())); return (idEqual && keyInfoEqual && sv.equals(osig.getSignatureValue()) && si.equals(osig.getSignedInfo()) && objects.equals(osig.getObjects())); }
From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java
public void validate(RoleDescriptorType md, Document doc, Node root) throws SamlR2SignatureException { try {/*w w w . j a va2s .co m*/ // Check for duplicate IDs among XML elements NodeList nodes = evaluateXPath(doc, "//*/@ID"); boolean duplicateIdExists = false; List<String> ids = new ArrayList<String>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (ids.contains(node.getNodeValue())) { duplicateIdExists = true; logger.error("Duplicated Element ID in XML Document : " + node.getNodeValue()); } ids.add(node.getNodeValue()); } if (duplicateIdExists) { throw new SamlR2SignatureException("Duplicate IDs in document "); } // TODO : Check that the Signature references the root element (the one used by the application) // Keep in mind that signature reference might be an XPath expression ?! // We know that in SAML, the root element is the element used by the application, we just need to make sure that // the root element is the one referred by the signature Node rootIdAttr = root.getAttributes().getNamedItem("ID"); if (rootIdAttr == null) throw new SamlR2SignatureException("SAML document does not have an ID "); // Find Signature element NodeList signatureNodes = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (signatureNodes.getLength() == 0) { throw new SamlR2SignatureException("Cannot find Signature elements"); } // Create a DOM XMLSignatureFactory that will be used to unmarshal the // document containing the XMLSignature XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider); // Create a DOMValidateContext and specify a KeyValue KeySelector // and document context // Validate all Signature elements boolean rootIdMatched = false; for (int k = 0; k < signatureNodes.getLength(); k++) { DOMValidateContext valContext = new DOMValidateContext(new RawX509KeySelector(), signatureNodes.item(k)); // unmarshal the XMLSignature XMLSignature signature = fac.unmarshalXMLSignature(valContext); // Validate the XMLSignature (generated above) boolean coreValidity = signature.validate(valContext); // Check core validation status if (!coreValidity) { if (logger.isDebugEnabled()) logger.debug("Signature failed core validation"); boolean sv = signature.getSignatureValue().validate(valContext); if (logger.isDebugEnabled()) logger.debug("signature validation status: " + sv); // check the validation status of each Reference (should be only one!) Iterator i = signature.getSignedInfo().getReferences().iterator(); boolean refValid = true; for (int j = 0; i.hasNext(); j++) { Reference ref = (Reference) i.next(); boolean b = ref.validate(valContext); if (logger.isDebugEnabled()) logger.debug("ref[" + j + "] " + ref.getId() + " validity status: " + b); if (!b) { refValid = b; logger.error("Signature failed reference validation " + ref.getId()); } } throw new SamlR2SignatureValidationException( "Signature failed core validation" + (refValid ? " but passed all Reference validations" : " and some/all Reference validation")); } if (logger.isDebugEnabled()) logger.debug("Singnature passed Core validation"); // The Signature must contain only one reference, and it must be the signed top element's ID. List<Reference> refs = signature.getSignedInfo().getReferences(); if (refs.size() != 1) { throw new SamlR2SignatureValidationException( "Invalid number of 'Reference' elements in signature : " + refs.size() + " [" + signature.getId() + "]"); } Reference reference = refs.get(0); String referenceURI = reference.getURI(); if (referenceURI == null || !referenceURI.startsWith("#")) throw new SamlR2SignatureValidationException( "Signature reference URI format not supported " + referenceURI); if (referenceURI.substring(1).equals(rootIdAttr.getNodeValue())) rootIdMatched = true; Key key = signature.getKeySelectorResult().getKey(); boolean certValidity = validateCertificate(md, key); if (!certValidity) { throw new SamlR2SignatureValidationException("Signature failed Certificate validation"); } if (logger.isDebugEnabled()) logger.debug("Signature passed Certificate validation"); } // Check that any of the Signatures matched the root element ID if (!rootIdMatched) { logger.error("No Signature element refers to signed element (possible signature wrapping attack)"); throw new SamlR2SignatureValidationException("No Signature element refers to signed element"); } } catch (MarshalException e) { throw new RuntimeException(e.getMessage(), e); } catch (XMLSignatureException e) { throw new RuntimeException(e.getMessage(), e); } }