List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory unmarshalXMLSignature
public abstract XMLSignature unmarshalXMLSignature(XMLStructure xmlStructure) throws MarshalException;
XMLSignature
instance from a mechanism-specific XMLStructure
instance. From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java
@Override public boolean checkIntegrity(Document detachedDocument) { DOMValidateContext valContext = new DOMValidateContext( KeySelector.singletonKeySelector(getSigningCertificate().getPublicKey()), this.signatureElement); if (detachedDocument != null) { valContext.setURIDereferencer(new OneExternalFileURIDereferencer("detached-file", detachedDocument)); }/*from www . j ava 2 s . c o m*/ XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); try { XMLSignature signature = factory.unmarshalXMLSignature(valContext); recursiveIdBrowse(valContext, signatureElement); boolean r = signature.validate(valContext); return r; } catch (MarshalException e) { throw new RuntimeException(e); } catch (XMLSignatureException e) { throw new RuntimeException(e); } }
From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java
@Override public List<AdvancedSignature> getCounterSignatures() { // see ETSI TS 101 903 V1.4.2 (2010-12) pp. 38/39/40 try {/*from www .j a v a 2 s. co m*/ NodeList counterSigs = XMLUtils.getNodeList(signatureElement, "./ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties" + "/xades:CounterSignature"); if (counterSigs == null) { return null; } List<AdvancedSignature> xadesList = new ArrayList<AdvancedSignature>(); for (int i = 0; i < counterSigs.getLength(); i++) { Element counterSigEl = (Element) counterSigs.item(i); Element signatureEl = XMLUtils.getElement(counterSigEl, "./ds:Signature"); // Verify that the element is a proper signature by trying to build a XAdESSignature out of it XAdESSignature xCounterSig = new XAdESSignature(signatureEl); // Verify that there is a ds:Reference element with a Type set to: http://uri.etsi.org/01903#CountersignedSignature // (as per the XAdES spec) XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature = factory.unmarshalXMLSignature(new DOMStructure(signatureEl)); LOG.info("Verifying countersignature References"); for (Object refobj : signature.getSignedInfo().getReferences()) { Reference ref = (Reference) refobj; if (ref.getType() != null && ref.getType().equals("http://uri.etsi.org/01903#CountersignedSignature")) { // Ok, this seems to be a countersignature // Verify that the digest is that of the signature value if (ref.validate(new DOMValidateContext(xCounterSig.getSigningCertificate().getPublicKey(), XMLUtils.getElement(signatureElement, "./ds:SignatureValue")))) { LOG.info("Reference verification succeeded, adding countersignature"); xadesList.add(xCounterSig); } else { LOG.warning( "Skipping countersignature because the Reference doesn't contain a hash of the embedding SignatureValue"); } break; } } } return xadesList; } catch (XPathExpressionException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING); } catch (MarshalException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING); } catch (XMLSignatureException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING); } }
From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureVerifier.java
public List<X509Certificate> getSigners(URL url) throws IOException, ParserConfigurationException, SAXException, TransformerException, MarshalException, XMLSignatureException, JAXBException { List<X509Certificate> signers = new LinkedList<X509Certificate>(); List<String> signatureResourceNames = getSignatureResourceNames(url); if (signatureResourceNames.isEmpty()) { LOG.debug("no signature resources"); }// ww w . java2 s . co m for (String signatureResourceName : signatureResourceNames) { Document signatureDocument = getSignatureDocument(url, signatureResourceName); if (null == signatureDocument) { continue; } NodeList signatureNodeList = signatureDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (0 == signatureNodeList.getLength()) { return null; } Node signatureNode = signatureNodeList.item(0); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode); domValidateContext.setProperty("org.jcp.xml.dsig.validateManifests", Boolean.TRUE); OOXMLURIDereferencer dereferencer = new OOXMLURIDereferencer(url); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean valid = xmlSignature.validate(domValidateContext); if (!valid) { LOG.debug("not a valid signature"); continue; } /* * Check the content of idPackageObject. */ List<XMLObject> objects = xmlSignature.getObjects(); XMLObject idPackageObject = null; for (XMLObject object : objects) { if ("idPackageObject".equals(object.getId())) { idPackageObject = object; break; } } if (null == idPackageObject) { LOG.debug("idPackageObject ds:Object not present"); continue; } List<XMLStructure> idPackageObjectContent = idPackageObject.getContent(); Manifest idPackageObjectManifest = null; for (XMLStructure content : idPackageObjectContent) { if (content instanceof Manifest) { idPackageObjectManifest = (Manifest) content; break; } } if (null == idPackageObjectManifest) { LOG.debug("no ds:Manifest present within idPackageObject ds:Object"); continue; } LOG.debug("ds:Manifest present within idPackageObject ds:Object"); List<Reference> idPackageObjectReferences = idPackageObjectManifest.getReferences(); Set<String> idPackageObjectReferenceUris = new HashSet<String>(); Set<String> remainingIdPackageObjectReferenceUris = new HashSet<String>(); for (Reference idPackageObjectReference : idPackageObjectReferences) { idPackageObjectReferenceUris.add(idPackageObjectReference.getURI()); remainingIdPackageObjectReferenceUris.add(idPackageObjectReference.getURI()); } LOG.debug("idPackageObject ds:Reference URIs: " + idPackageObjectReferenceUris); CTTypes contentTypes = getContentTypes(url); List<String> relsEntryNames = getRelsEntryNames(url); for (String relsEntryName : relsEntryNames) { LOG.debug("---- relationship entry name: " + relsEntryName); CTRelationships relationships = getRelationships(url, relsEntryName); List<CTRelationship> relationshipList = relationships.getRelationship(); boolean includeRelationshipInSignature = false; for (CTRelationship relationship : relationshipList) { String relationshipType = relationship.getType(); STTargetMode targetMode = relationship.getTargetMode(); if (null != targetMode) { LOG.debug("TargetMode: " + targetMode.name()); if (targetMode == STTargetMode.EXTERNAL) { /* * ECMA-376 Part 2 - 3rd edition * * 13.2.4.16 Manifest Element * * "The producer shall not create a Manifest element that references any data outside of the package." */ continue; } } if (false == OOXMLSignatureFacet.isSignedRelationship(relationshipType)) { continue; } String relationshipTarget = relationship.getTarget(); String baseUri = "/" + relsEntryName.substring(0, relsEntryName.indexOf("_rels/")); String streamEntry = baseUri + relationshipTarget; LOG.debug("stream entry: " + streamEntry); streamEntry = FilenameUtils.separatorsToUnix(FilenameUtils.normalize(streamEntry)); LOG.debug("normalized stream entry: " + streamEntry); String contentType = getContentType(contentTypes, streamEntry); if (relationshipType.endsWith("customXml")) { if (false == contentType.equals("inkml+xml") && false == contentType.equals("text/xml")) { LOG.debug("skipping customXml with content type: " + contentType); continue; } } includeRelationshipInSignature = true; LOG.debug("content type: " + contentType); String referenceUri = streamEntry + "?ContentType=" + contentType; LOG.debug("reference URI: " + referenceUri); if (false == idPackageObjectReferenceUris.contains(referenceUri)) { throw new RuntimeException( "no reference in idPackageObject ds:Object for relationship target: " + streamEntry); } remainingIdPackageObjectReferenceUris.remove(referenceUri); } String relsReferenceUri = "/" + relsEntryName + "?ContentType=application/vnd.openxmlformats-package.relationships+xml"; if (includeRelationshipInSignature && false == idPackageObjectReferenceUris.contains(relsReferenceUri)) { LOG.debug("missing ds:Reference for: " + relsEntryName); throw new RuntimeException("missing ds:Reference for: " + relsEntryName); } remainingIdPackageObjectReferenceUris.remove(relsReferenceUri); } if (false == remainingIdPackageObjectReferenceUris.isEmpty()) { LOG.debug("remaining idPackageObject reference URIs" + idPackageObjectReferenceUris); throw new RuntimeException("idPackageObject manifest contains unknown ds:References: " + remainingIdPackageObjectReferenceUris); } X509Certificate signer = keySelector.getCertificate(); signers.add(signer); } return signers; }
From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java
@Override public byte[] getArchiveTimestampData(int index, Document originalData) throws IOException { try {//from ww w .j av a 2s . com ByteArrayOutputStream buffer = new ByteArrayOutputStream(); XMLStructure s = new DOMStructure(signatureElement); XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); DOMXMLSignature signature = (DOMXMLSignature) factory.unmarshalXMLSignature(s); DOMSignContext signContext = new DOMSignContext(new SpecialPrivateKey(), signatureElement); signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); signContext.setProperty("javax.xml.crypto.dsig.cacheReference", true); signContext.setURIDereferencer(new OneExternalFileURIDereferencer("detached-file", originalData)); // TODO naramsda: check ! Don't let met publish that without further test !! // DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // dbf.setNamespaceAware(true); // org.w3c.dom.Document xmlDoc = dbf.newDocumentBuilder().newDocument(); // signature.marshal(xmlDoc.createElement("test"), "ds", signContext); for (Object o : signature.getSignedInfo().getReferences()) { DOMReference r = (DOMReference) o; InputStream data = r.getDigestInputStream(); if (data != null) { IOUtils.copy(data, buffer); } } List<Node> timeStampNodesXadesA = new LinkedList<Node>(); Element signedInfo = XMLUtils.getElement(signatureElement, "./ds:SignedInfo"); timeStampNodesXadesA.add(signedInfo); Element signatureValue = XMLUtils.getElement(signatureElement, "./ds:SignatureValue"); timeStampNodesXadesA.add(signatureValue); Element keyInfo = XMLUtils.getElement(signatureElement, "./ds:KeyInfo"); timeStampNodesXadesA.add(keyInfo); Element unsignedSignaturePropertiesNode = getUnsignedSignatureProperties(signatureElement); NodeList unsignedProperties = unsignedSignaturePropertiesNode.getChildNodes(); int count = 0; for (int i = 0; i < unsignedProperties.getLength(); i++) { if (unsignedProperties.item(i).getNodeType() == Node.ELEMENT_NODE) { Element unsignedProperty = (Element) unsignedProperties.item(i); if ("ArchiveTimeStamp".equals(unsignedProperty.getLocalName())) { if (count == index) { LOG.info("We only need data up to ArchiveTimeStamp index " + index); break; } count++; } timeStampNodesXadesA.add(unsignedProperty); } } buffer.write(getC14nValue(timeStampNodesXadesA)); return buffer.toByteArray(); // } catch (ParserConfigurationException e) { // throw new IOException("Error when computing the archive data", e); } catch (MarshalException e) { throw new IOException("Error when computing the archive data", e); } catch (XPathExpressionException e) { throw new EncodingException(MSG.ARCHIVE_TIMESTAMP_DATA_ENCODING); } }
From source file:be.fedict.eid.tsl.TrustServiceList.java
public X509Certificate verifySignature() { if (null == this.tslDocument) { LOG.debug("first save the document"); return null; }// w w w .j a v a2s .c om Node signatureNode = getSignatureNode(); if (null == signatureNode) { LOG.debug("no ds:Signature element present"); return null; } KeyInfoKeySelector keyInfoKeySelector = new KeyInfoKeySelector(); DOMValidateContext valContext = new DOMValidateContext(keyInfoKeySelector, signatureNode); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature; try { signature = xmlSignatureFactory.unmarshalXMLSignature(valContext); } catch (MarshalException e) { throw new RuntimeException("XML signature parse error: " + e.getMessage(), e); } boolean coreValidity; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { throw new RuntimeException("XML signature error: " + e.getMessage(), e); } // TODO: check what has been signed if (coreValidity) { LOG.debug("signature valid"); return keyInfoKeySelector.getCertificate(); } LOG.debug("signature invalid"); return null; }
From source file:eu.europa.ec.markt.dss.validation102853.xades.XAdESSignature.java
@Override public List<AdvancedSignature> getCounterSignatures() { // see ETSI TS 101 903 V1.4.2 (2010-12) pp. 38/39/40 try {//from w w w . jav a 2s . c o m NodeList counterSigs = DSSXMLUtils.getNodeList(signatureElement, XPATH_COUNTER_SIGNATURE); if (counterSigs == null) { return null; } List<AdvancedSignature> xadesList = new ArrayList<AdvancedSignature>(); for (int i = 0; i < counterSigs.getLength(); i++) { Element counterSigEl = (Element) counterSigs.item(i); Element signatureEl = DSSXMLUtils.getElement(counterSigEl, XPATH_SIGNATURE); // Verify that the element is a proper signature by trying to build a XAdESSignature out of it XAdESSignature xCounterSig = new XAdESSignature(signatureEl, certPool); /* * Verify that there is a ds:Reference element with a Type set to: * http://uri.etsi.org/01903#CountersignedSignature (as per the XAdES spec) */ XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); javax.xml.crypto.dsig.XMLSignature signature = factory .unmarshalXMLSignature(new DOMStructure(signatureEl)); LOG.info("Verifying countersignature References"); for (Object refobj : signature.getSignedInfo().getReferences()) { Reference ref = (Reference) refobj; if (ref.getType() != null && ref.getType().equals(XADES_COUNTERSIGNED_SIGNATURE)) { // Ok, this seems to be a CounterSignature // Verify that the digest is that of the signature value CertificateToken certToken = xCounterSig.getSigningCertificate().getCertToken(); PublicKey publicKey = certToken.getCertificate().getPublicKey(); if (ref.validate(new DOMValidateContext(publicKey, DSSXMLUtils.getElement(signatureElement, XPATH_SIGNATURE_VALUE)))) { LOG.info("Reference verification succeeded, adding countersignature"); xadesList.add(xCounterSig); } else { LOG.warning( "Skipping countersignature because the Reference doesn't contain a hash of the embedding SignatureValue"); } break; } } } return xadesList; } catch (MarshalException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING, e); } catch (XMLSignatureException e) { throw new EncodingException(MSG.COUNTERSIGNATURE_ENCODING, e); } }
From source file:eu.europa.ec.markt.dss.validation102853.xades.XAdESSignature.java
@Override public SignatureCryptographicVerification checkIntegrity(DSSDocument detachedDocument) { final SignatureCryptographicVerification scv = new SignatureCryptographicVerification(); final CertificateToken certToken = getSigningCertificate().getCertToken(); if (certToken != null) { final PublicKey publicKey = certToken.getCertificate().getPublicKey(); final KeySelector keySelector = KeySelector.singletonKeySelector(publicKey); /**//from ww w . jav a2 s .c o m * Creating a Validation Context<br> * We create an XMLValidateContext instance containing input parameters for validating the signature. Since we * are using DOM, we instantiate a DOMValidateContext instance (a subclass of XMLValidateContext), and pass it * two parameters, a KeyValueKeySelector object and a reference to the Signature element to be validated (which * is the first entry of the NodeList we generated earlier): */ final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureElement); try { URIDereferencer dereferencer = new ExternalFileURIDereferencer(detachedDocument); valContext.setURIDereferencer(dereferencer); /** * This property controls whether or not the digested Reference objects will cache the dereferenced content * and pre-digested input for subsequent retrieval via the Reference.getDereferencedData and * Reference.getDigestInputStream methods. The default value if not specified is Boolean.FALSE. */ valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); /** * Unmarshalling the XML Signature<br> * We extract the contents of the Signature element into an XMLSignature object. This process is called * unmarshalling. The Signature element is unmarshalled using an XMLSignatureFactory object. An application * can obtain a DOM implementation of XMLSignatureFactory by calling the following line of code: */ // These providers do not support ECDSA algorithm // factory = XMLSignatureFactory.getInstance("DOM"); // factory = XMLSignatureFactory.getInstance("DOM", "XMLDSig"); // factory = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); // This provider support ECDSA signature /** * ApacheXMLDSig / Apache Santuario XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory; C14N 1.0, C14N * 1.1, Exclusive C14N, Base64, Enveloped, XPath, XPath2, XSLT TransformServices)<br> * If this library is used than the same library must be used for the URIDereferencer. */ final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", xmlProvider); /** * We then invoke the unmarshalXMLSignature method of the factory to unmarshal an XMLSignature object, and * pass it the validation context we created earlier: */ final XMLSignature signature = factory.unmarshalXMLSignature(valContext); //System.out.println("XMLSignature class: " + signature.getClass()); // Austrian specific signature //org.apache.xml.security.signature.XMLSignature signature_ = null; // try { // signature_ = new org.apache.xml.security.signature.XMLSignature(signatureElement, ""); // } catch (Exception e) { // // throw new DSSException(e); // } // signature.addResourceResolver(new XPointerResourceResolver(signatureElement)); //signature_.getSignedInfo().verifyReferences();//getVerificationResult(1); /** * In case of org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI() provider, the ID attributes need to be set * manually.<br> * The DSSXMLUtils.recursiveIdBrowse(...) method do not take into account the XML outside of the Signature * tag. It prevents some signatures to be validated.<br> * * Solution: the following lines where added: */ final Document document = signatureElement.getOwnerDocument(); final Element rootElement = document.getDocumentElement(); if (rootElement.hasAttribute(DSSXMLUtils.ID_ATTRIBUTE_NAME)) { valContext.setIdAttributeNS(rootElement, null, DSSXMLUtils.ID_ATTRIBUTE_NAME); } DSSXMLUtils.recursiveIdBrowse(valContext, rootElement); /** * Validating the XML Signature<br> * Now we are ready to validate the signature. We do this by invoking the validate method on the * XMLSignature object, and pass it the validation context as follows: */ boolean coreValidity = false; try { coreValidity = signature.validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage("Signature validation: " + e.getMessage()); } boolean signatureValidity = coreValidity; boolean dataFound = true; boolean dataHashValid = true; /** * If the XMLSignature.validate method returns false, we can try to narrow down the cause of the failure. * There are two phases in core XML Signature validation: <br> * - Signature validation (the cryptographic verification of the signature)<br> * - Reference validation (the verification of the digest of each reference in the signature)<br> * Each phase must be successful for the signature to be valid. To check if the signature failed to * cryptographically validate, we can check the status, as follows: */ try { signatureValidity = signature.getSignatureValue().validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage(e.getMessage()); } @SuppressWarnings("unchecked") final List<Reference> references = signature.getSignedInfo().getReferences(); for (Reference reference : references) { boolean refHashValidity = false; try { refHashValidity = reference.validate(valContext); } catch (XMLSignatureException e) { scv.setErrorMessage(reference.getURI() + ": " + e.getMessage()); } dataHashValid = dataHashValid && refHashValidity; if (LOG.isLoggable(Level.INFO)) { LOG.info("Reference hash validity checked: " + reference.getURI() + "=" + refHashValidity); } final Data data = reference.getDereferencedData(); dataFound = dataFound && (data != null); final InputStream digestInputStream = reference.getDigestInputStream(); if (data != null && digestInputStream != null) { // The references are saved for later treatment in -A level. try { IOUtils.copy(digestInputStream, referencesDigestOutputStream); } catch (IOException e) { } } } scv.setReferenceDataFound(dataFound); scv.setReferenceDataIntact(dataHashValid); scv.setSignatureIntegrity(signatureValidity); } catch (MarshalException e) { scv.setErrorMessage(e.getMessage()); } } else { scv.setErrorMessage( "Unable to proceed with the signature cryptographic verification. There is no signing certificate!"); } return scv; }
From source file:nl.clockwork.mule.ebms.cxf.XMLDSignatureInInterceptor.java
private boolean verify(Document document, List<EbMSDataSource> dataSources) throws MarshalException, XMLSignatureException { NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nodeList.getLength() > 0) { XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(); DOMValidateContext validateContext = new DOMValidateContext(new XMLDSigKeySelector(), nodeList.item(0)); URIDereferencer dereferencer = new EbMSDataSourceURIDereferencer(dataSources); validateContext.setURIDereferencer(dereferencer); XMLSignature signature = signFactory.unmarshalXMLSignature(validateContext); return signature.validate(validateContext); }// w w w .j av a 2 s . co m return true; }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
private boolean verifySignature(Element element, PublicKey validatingKey, AtomicReference<String> OutReadableErrorMessage) { if (OutReadableErrorMessage == null) { OutReadableErrorMessage = new AtomicReference<String>(); }/*www .j av a 2 s .c o m*/ XMLSignatureFactory fac = initXMLSigFactory(); NodeList nl = element.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new RuntimeException("Cannot find Signature element"); } DOMValidateContext valContext = new DOMValidateContext(validatingKey, nl.item(0)); try { valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); XMLSignature signature = fac.unmarshalXMLSignature(valContext); boolean coreValidity = signature.validate(valContext); // Check core validation status. if (coreValidity == false) { logger.warn("Signature failed core validation"); boolean sv = signature.getSignatureValue().validate(valContext); logger.debug("signature validation status: " + sv); OutReadableErrorMessage .set("signature validation failed: " + sv + "." + OutReadableErrorMessage.get()); // Check the validation status of each Reference. @SuppressWarnings("unchecked") Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator(); //System.out.println("---------------------------------------------"); for (int j = 0; i.hasNext(); j++) { Reference ref = (Reference) i.next(); boolean refValid = ref.validate(valContext); logger.debug(j); logger.debug("ref[" + j + "] validity status: " + refValid); if (!refValid) { OutReadableErrorMessage .set("signature reference " + j + " invalid. " + OutReadableErrorMessage.get()); } logger.debug("Ref type: " + ref.getType() + ", URI: " + ref.getURI()); for (Object xform : ref.getTransforms()) { logger.debug("Transform: " + xform); } String calcDigValStr = digestToString(ref.getCalculatedDigestValue()); String expectedDigValStr = digestToString(ref.getDigestValue()); logger.warn(" Calc Digest: " + calcDigValStr); logger.warn("Expected Digest: " + expectedDigValStr); if (!calcDigValStr.equalsIgnoreCase(expectedDigValStr)) { OutReadableErrorMessage.set( "digest mismatch for signature ref " + j + "." + OutReadableErrorMessage.get()); } } } else { logger.info("Signature passed core validation"); } return coreValidity; } catch (Exception e) { OutReadableErrorMessage .set("signature validation failed: " + e.getMessage() + OutReadableErrorMessage.get()); logger.fatal(e); return false; } }
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 {/*from w ww . j ava 2 s . 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); } }