List of usage examples for javax.xml.crypto.dsig XMLSignatureException XMLSignatureException
public XMLSignatureException(Throwable cause)
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Validate the canonicalization method of the signature. * @param xmlSignature the XMLSignature to validate the canonicalization method of. * @throws XMLSignatureException when validation fails. *///from w w w . ja v a2 s . c o m private void validateCanonicalizationMethod(XMLSignature xmlSignature) throws XMLSignatureException { assert xmlSignature != null; // Exclusive canonicalization without comments (xml-exc-c14n) must be used prior to signature generation. if (!CanonicalizationMethod.EXCLUSIVE .equals(xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm())) { throw new XMLSignatureException(String.format("Canonicalization algorithm '%s' is not supported.", xmlSignature.getSignedInfo().getCanonicalizationMethod().getAlgorithm())); } }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Validate references present in the XmlSignature. * @param xmlSignature the xml signature whose references are to be validated. not null. * @param valContext validation context used to validate the signature itself. not null. * @param document document the signature belongs to. not null. * @param timestampNode the timestamp node of the soap security header within the document. * @throws XMLSignatureException when the validation fails. *//*from w w w. j av a 2 s.c om*/ private void validateSignatureReferences(XMLSignature xmlSignature, DOMValidateContext valContext, Document document, Node timestampNode) throws XMLSignatureException { assert xmlSignature != null; assert valContext != null; assert document != null; assert timestampNode != null; // If a signature is applied to a request then it must include: // Either the <S11:Body>, or the WS-Trust element as a direct child of the <S11:Body> // The <wsu:Timestamp>, if present in the <S11:Header>. // (in fact this must be present as per same spec, and SOAPHeaderExtractor validates it) Node soapBody = getSoapBody(document); Node wsTrustNode = getWsTrustNode(soapBody); boolean foundTimestampElement = false; boolean foundBodyOrWSTrustElement = false; List<Reference> references = xmlSignature.getSignedInfo().getReferences(); if ((references == null) || (references.size() == 0)) { throw new XMLSignatureException("Signature's SignInfo does not contain any references."); } for (Reference reference : references) { if (reference != null) { validateReferenceTransforms(reference); validateReferenceUri(reference); // note: order is important, we should not try to validate digests // before we checked expected transforms, and uri etc. if (!reference.validate(valContext)) { throw new XMLSignatureException( String.format("Signature reference '%s' is invalid.", reference.getURI())); } if (!foundTimestampElement || !foundBodyOrWSTrustElement) { String id = org.jcp.xml.dsig.internal.dom.Utils.parseIdFromSameDocumentURI(reference.getURI()); Node referencedNode = document.getElementById(id); foundTimestampElement = (foundTimestampElement) || (timestampNode.isSameNode(referencedNode)); foundBodyOrWSTrustElement = (foundBodyOrWSTrustElement) || (soapBody.isSameNode(referencedNode)) || (wsTrustNode.isSameNode(referencedNode)); } } } // for each reference if (!foundTimestampElement || !foundBodyOrWSTrustElement) { throw new XMLSignatureException( "Signature must include <wsu:Timestamp> and either SoapBody, or the WSTrust element within it."); } }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Validate the signature reference transforms are as expected. * (Only the exclusive canonicalization transform is supported). * * @param reference signature reference to validate the transforms of. * @throws XMLSignatureException when validation fails. *//*from w ww .j av a 2 s . c om*/ private void validateReferenceTransforms(Reference reference) throws XMLSignatureException { assert reference != null; List<Transform> transforms = reference.getTransforms(); if ((transforms != null) && (transforms.size() > 1)) { throw new XMLSignatureException( "Unexpected number of transforms. Only an exclusive canonicalization is supported."); } else if ((transforms != null) && (transforms.size() > 0) && (!CanonicalizationMethod.EXCLUSIVE.equals(transforms.get(0).getAlgorithm()))) { throw new XMLSignatureException( String.format("Unexpected Transform '%s'. Only an exclusive canonicalization is supported.", transforms.get(0).getAlgorithm())); } }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Validate the Signature Reference URI is the same document Uri. * It should not point to external resources. * @param reference Signature reference to validate the uri of. not null. * @throws XMLSignatureException when the validation fails. *//* www .ja v a2s . c o m*/ private void validateReferenceUri(Reference reference) throws XMLSignatureException { assert reference != null; if (!org.jcp.xml.dsig.internal.dom.Utils.sameDocumentURI(reference.getURI())) { throw new XMLSignatureException(String.format( "Invalid reference '%s'. Only a same-document references are aupported.", reference.getURI())); } }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * Retrieves the SoapBody element from the document. * @param document not null/*from w w w. ja v a2s.c o m*/ * @return Node of the Soap Body element. * @throws XMLSignatureException when unable to locate the Soap Body element. */ private Node getSoapBody(Document document) throws XMLSignatureException { assert document != null; NodeList nodes = null; Node soapBody = null; nodes = document.getElementsByTagNameNS(javax.xml.soap.SOAPConstants.URI_NS_SOAP_ENVELOPE, BODY_ELEMENT_NAME); if ((nodes == null) || (nodes.getLength() == 0)) { throw new XMLSignatureException("Unexpected soap format - unable to find soap body."); } else if (nodes.getLength() > 1) { throw new XMLSignatureException("Unexpected soap format - found more than 1 soap body elements."); } else { soapBody = nodes.item(0); } if (soapBody == null) { throw new XMLSignatureException("Unexpected soap format - unable to resolve soap body."); } return soapBody; }
From source file:com.vmware.identity.sts.ws.SignatureValidator.java
/** * retrieves the WSTrust element from the soap body. * @param soapBody not null/*from w ww . ja v a 2 s .c om*/ * @return Node of the WSTrust element. * @throws XMLSignatureException when unable to locate the WSTrust element. */ private Node getWsTrustNode(Node soapBody) throws XMLSignatureException { assert soapBody != null; Node wsTrustNode = null; // - All <wst:RequestSecurityToken>, <wst:RequestSecurityTokenResponse>, // and <wst:RequestSecurityTokenResponseCollection> elements must be carried // as the single direct child of the body of a SOAP 1.1 <S11:Envelope> element. wsTrustNode = soapBody.getFirstChild(); if (wsTrustNode == null) { throw new XMLSignatureException("Unexpected Soap structure. Body element is empty."); } else if (wsTrustNode.getNodeType() != Node.ELEMENT_NODE) { throw new XMLSignatureException(String.format( "Unexpected Soap structure. Body element has a child of type '%s'. Expect WSTrust element.", wsTrustNode.getNodeType())); } return wsTrustNode; }
From source file:com.trsst.server.TrsstAdapter.java
/** * Validate then persist incoming feed and entries. Any exception thrown * means no feed or entries are persisted. * //from w ww. j a va2 s . co m * @param feed * with zero or more entries to be validated and persisted. * @throws XMLSignatureException * if signature verification fails * @throws IllegalArgumentException * if data validation fails * @throws Exception * any other problem */ protected void ingestFeed(Storage storage, Feed feed) throws XMLSignatureException, IllegalArgumentException, Exception { // clone a copy so we can manipulate feed = (Feed) feed.clone(); // validate feed Date lastUpdated = feed.getUpdated(); if (lastUpdated == null) { throw new IllegalArgumentException("Feed update timestamp is required: " + feed.getId()); } if (lastUpdated.after(new Date(System.currentTimeMillis() + 1000 * 60 * 5))) { // allows five minutes of variance throw new IllegalArgumentException("Feed update timestamp cannot be in the future: " + feed.getId()); } // grab the signing key Element signingElement = feed.getFirstChild(new QName(Common.NS_URI, Common.SIGN)); if (signingElement == null) { throw new XMLSignatureException("Could not find signing key for feed: " + feed.getId()); } // verify that the key matches the id PublicKey publicKey = Common.toPublicKeyFromX509(signingElement.getText()); if (Common.fromFeedUrn(feed.getId()) == null || !Common.fromFeedUrn(feed.getId()).equals(Common.toFeedId(publicKey))) { throw new XMLSignatureException("Signing key does not match feed id: " + Common.fromFeedUrn(feed.getId()) + " : " + Common.toFeedId(publicKey)); } // prep the verifier AbderaSecurity security = new AbderaSecurity(Abdera.getInstance()); Signature signature = security.getSignature(); SignatureOptions options = signature.getDefaultSignatureOptions(); options.setSigningAlgorithm("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"); options.setSignLinks(false); options.setPublicKey(publicKey); // validate, persist, and remove each entry List<Entry> entries = new LinkedList<Entry>(); entries.addAll(feed.getEntries()); // make a copy String existingEntryXml; for (Entry entry : feed.getEntries()) { String feedId = Common.toFeedIdString(feed.getId()); long entryId = Common.toEntryId(entry.getId()); try { try { existingEntryXml = persistence.readEntry(feedId, entryId); } catch (FileNotFoundException fnfe) { existingEntryXml = null; } if (existingEntryXml != null) { Entry parsed = (Entry) Abdera.getInstance().getParser() .parse(new StringReader(existingEntryXml)).getRoot(); if (entry.getUpdated().after(parsed.getUpdated())) { // discard what we have in cache existingEntryXml = null; } } } catch (Exception e) { existingEntryXml = null; log.warn("Unexpected error parsing existing entry before validation: " + entry.getId(), e); } if (existingEntryXml != null) { log.trace("Skipping validation for existing entry: " + entry.getId()); } else { if (!signature.verify(entry, options)) { // failed validation Element activity = entry .getExtension(new QName("http://activitystrea.ms/spec/1.0/", "verb", "activity")); // if not a 'deleted' entry if (activity == null || !"deleted".equals(activity.getText())) { // TODO: should validate that the 'delete' entry that // this entry mentions is mentioning this entry log.warn("Could not verify signature for entry with id: " + feed.getId()); // fail ingest throw new XMLSignatureException("Could not verify signature for entry with id: " + entry.getId() + " : " + feed.getId()); } else { log.warn("Skipping signature verification for deleted entry: " + feed.getId()); } } try { // yield a bit while validating entries Thread.sleep(100); } catch (InterruptedException e) { log.error("Should never happen: ", e); } } // remove from feed parent entry.discard(); try { // see if this file already exists storage.readEntry(Common.toFeedIdString(feed.getId()), Common.toEntryId(entry.getId())); // this file exists; remove from processing entries.remove(entry); } catch (FileNotFoundException e) { // file does not already exist: resume } } // setEditDetail(request, entry, key); // String edit = entry.getEditLinkResolvedHref().toString(); // remove all navigation links before signing for (Link link : feed.getLinks()) { if (Link.REL_FIRST.equals(link.getRel()) || Link.REL_LAST.equals(link.getRel()) || Link.REL_CURRENT.equals(link.getRel()) || Link.REL_NEXT.equals(link.getRel()) || Link.REL_PREVIOUS.equals(link.getRel())) { link.discard(); } } // remove all opensearch elements before verifying for (Element e : feed.getExtensions("http://a9.com/-/spec/opensearch/1.1/")) { e.discard(); } // now validate feed signature sans entries if (!signature.verify(feed, options)) { log.warn("Could not verify signature for feed with id: " + feed.getId()); throw new XMLSignatureException("Could not verify signature for feed with id: " + feed.getId()); } // persist feed String existingFeedXml; try { String feedId = Common.toFeedIdString(feed.getId()); try { existingFeedXml = persistence.readFeed(feedId); } catch (FileNotFoundException fnfe) { existingFeedXml = null; } if (existingFeedXml != null) { Feed parsed = (Feed) Abdera.getInstance().getParser().parse(new StringReader(existingFeedXml)) .getRoot(); if (feed.getUpdated().after(parsed.getUpdated())) { // discard what we have in cache existingFeedXml = null; } } } catch (Exception e) { existingFeedXml = null; log.warn("Unexpected error parsing existing feed: " + feedId, e); } if (existingFeedXml == null) { persistence.updateFeed(feedId, feed.getUpdated(), feed.toString()); } // only now persist each entry for (Entry entry : entries) { Date date = entry.getPublished(); if (date == null) { // fall back to updated if publish not set date = entry.getUpdated(); } storage.updateEntry(Common.toFeedIdString(feed.getId()), Common.toEntryId(entry.getId()), date, entry.toString()); // check for delete operation String verb = entry .getSimpleExtension(new QName("http://activitystrea.ms/spec/1.0/", "verb", "activity")); if ("delete".equals(verb)) { // get mentions List<Category> mentions = entry.getCategories(); for (Category mention : mentions) { IRI scheme = mention.getScheme(); if (scheme != null && (Common.MENTION_URN.equals(scheme.toString()) || Common.MENTION_URN_LEGACY.equals(scheme.toString()))) { Entry deleted = null; try { deleted = deleteEntry(storage, Common.toFeedIdString(feed.getId()), Common.toEntryId(mention.getTerm()), Common.toEntryId(entry.getId())); } catch (IOException exc) { log.error("Could not delete entry: " + entry.getId(), exc); } if (deleted != null) { log.debug("Deleted entry: " + entry.getId()); } else { log.error("Failed to delete entry: " + entry.getId()); } } } } } }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMHMACSignatureMethod.java
boolean verify(Key key, SignedInfo si, byte[] sig, XMLValidateContext context) throws InvalidKeyException, SignatureException, XMLSignatureException { if (key == null || si == null || sig == null) { throw new NullPointerException(); }//from w ww . j ava2 s . com if (!(key instanceof SecretKey)) { throw new InvalidKeyException("key must be SecretKey"); } if (hmac == null) { try { hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } if (outputLengthSet && outputLength < getDigestLength()) { throw new XMLSignatureException("HMACOutputLength must not be less than " + getDigestLength()); } hmac.init((SecretKey) key); ((DOMSignedInfo) si).canonicalize(context, new MacOutputStream(hmac)); byte[] result = hmac.doFinal(); return MessageDigest.isEqual(sig, result); }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMHMACSignatureMethod.java
byte[] sign(Key key, SignedInfo si, XMLSignContext context) throws InvalidKeyException, XMLSignatureException { if (key == null || si == null) { throw new NullPointerException(); }/* ww w . j a v a 2 s .c om*/ if (!(key instanceof SecretKey)) { throw new InvalidKeyException("key must be SecretKey"); } if (hmac == null) { try { hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } if (outputLengthSet && outputLength < getDigestLength()) { throw new XMLSignatureException("HMACOutputLength must not be less than " + getDigestLength()); } hmac.init((SecretKey) key); ((DOMSignedInfo) si).canonicalize(context, new MacOutputStream(hmac)); return hmac.doFinal(); }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMReference.java
public void digest(XMLSignContext signContext) throws XMLSignatureException { Data data = null;/*from w ww . ja va 2s.c om*/ if (appliedTransformData == null) { data = dereference(signContext); } else { data = appliedTransformData; } digestValue = transform(data, signContext); // insert digestValue into DigestValue element String encodedDV = Base64.encode(digestValue); if (log.isDebugEnabled()) { log.debug("Reference object uri = " + uri); } Element digestElem = DOMUtils.getLastChildElement(refElem); if (digestElem == null) { throw new XMLSignatureException("DigestValue element expected"); } DOMUtils.removeAllChildren(digestElem); digestElem.appendChild(refElem.getOwnerDocument().createTextNode(encodedDV)); digested = true; if (log.isDebugEnabled()) { log.debug("Reference digesting completed"); } }