use of org.apache.xml.security.exceptions.XMLSecurityException in project OpenAM by OpenRock.
the class FMSigProvider method verify.
public boolean verify(String xmlString, String idValue, Set<X509Certificate> verificationCerts) throws SAML2Exception {
String classMethod = "FMSigProvider.verify: ";
if (xmlString == null || xmlString.length() == 0 || idValue == null || idValue.length() == 0) {
SAML2SDKUtils.debug.error(classMethod + "Either input xmlString or idValue is null.");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
}
Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
if (doc == null) {
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
}
Element nscontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "ds", Constants.SignatureSpecNS);
Element sigElement = null;
try {
sigElement = (Element) org.apache.xpath.XPathAPI.selectSingleNode(doc, "//ds:Signature[1]", nscontext);
} catch (TransformerException te) {
throw new SAML2Exception(te);
}
Element refElement;
try {
refElement = (Element) XPathAPI.selectSingleNode(doc, "//ds:Reference[1]", nscontext);
} catch (TransformerException te) {
throw new SAML2Exception(te);
}
String refUri = refElement.getAttribute("URI");
String signedId = ((Element) sigElement.getParentNode()).getAttribute(SAML2Constants.ID);
if (refUri == null || signedId == null || !refUri.substring(1).equals(signedId)) {
SAML2SDKUtils.debug.error(classMethod + "Signature reference ID does " + "not match with element ID");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("uriNoMatchWithId"));
}
doc.getDocumentElement().setIdAttribute(SAML2Constants.ID, true);
XMLSignature signature = null;
try {
signature = new XMLSignature((Element) sigElement, "");
} catch (XMLSignatureException sige) {
throw new SAML2Exception(sige);
} catch (XMLSecurityException xse) {
throw new SAML2Exception(xse);
}
signature.addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
KeyInfo ki = signature.getKeyInfo();
X509Certificate certToUse = null;
if (ki != null && ki.containsX509Data()) {
try {
certToUse = ki.getX509Certificate();
} catch (KeyResolverException kre) {
SAML2SDKUtils.debug.error(classMethod + "Could not obtain a certificate " + "from inside the document.");
certToUse = null;
}
if (certToUse != null && checkCert) {
if (!verificationCerts.contains(certToUse)) {
SAML2SDKUtils.debug.error(classMethod + "The cert contained in the document is NOT trusted");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidCertificate"));
}
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message(classMethod + "The cert contained in the document is trusted");
}
}
}
if (certToUse != null) {
verificationCerts = Collections.singleton(certToUse);
}
if (!isValidSignature(signature, verificationCerts)) {
SAML2SDKUtils.debug.error(classMethod + "Signature verification failed.");
return false;
}
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message(classMethod + "Signature verification successful.");
}
return true;
}
use of org.apache.xml.security.exceptions.XMLSecurityException in project OpenAM by OpenRock.
the class FMSigProvider method sign.
/**
* Sign the xml document node whose identifying attribute value
* is as supplied, using enveloped signatures and use exclusive xml
* canonicalization. The resulting signature is inserted after the
* first child node (normally Issuer element for SAML2) of the node
* to be signed.
* @param xmlString String representing an XML document to be signed
* @param idValue id attribute value of the root node to be signed
* @param privateKey Signing key
* @param cert Certificate which contain the public key correlated to
* the signing key; It if is not null, then the signature
* will include the certificate; Otherwise, the signature
* will not include any certificate
* @return Element representing the signature element
* @throws SAML2Exception if the document could not be signed
*/
public Element sign(String xmlString, String idValue, PrivateKey privateKey, X509Certificate cert) throws SAML2Exception {
String classMethod = "FMSigProvider.sign: ";
if (xmlString == null || xmlString.length() == 0 || idValue == null || idValue.length() == 0 || privateKey == null) {
SAML2SDKUtils.debug.error(classMethod + "Either input xml string or id value or " + "private key is null.");
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
}
Document doc = XMLUtils.toDOMDocument(xmlString, SAML2SDKUtils.debug);
if (doc == null) {
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorObtainingElement"));
}
Element root = doc.getDocumentElement();
XMLSignature sig = null;
try {
ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
} catch (XMLSecurityException xse1) {
throw new SAML2Exception(xse1);
}
root.setIdAttribute(SAML2Constants.ID, true);
try {
if ((sigAlg == null) || (sigAlg.trim().length() == 0)) {
if (privateKey.getAlgorithm().equalsIgnoreCase(SAML2Constants.DSA)) {
sigAlg = XMLSignature.ALGO_ID_SIGNATURE_DSA;
} else {
if (privateKey.getAlgorithm().equalsIgnoreCase(SAML2Constants.RSA)) {
sigAlg = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
}
}
}
sig = new XMLSignature(doc, "", sigAlg, c14nMethod);
} catch (XMLSecurityException xse2) {
throw new SAML2Exception(xse2);
}
Node firstChild = root.getFirstChild();
while (firstChild != null && (firstChild.getLocalName() == null || !firstChild.getLocalName().equals("Issuer"))) {
firstChild = firstChild.getNextSibling();
}
Node nextSibling = null;
if (firstChild != null) {
nextSibling = firstChild.getNextSibling();
}
if (nextSibling == null) {
root.appendChild(sig.getElement());
} else {
root.insertBefore(sig.getElement(), nextSibling);
}
sig.getSignedInfo().addResourceResolver(new com.sun.identity.saml.xmlsig.OfflineResolver());
Transforms transforms = new Transforms(doc);
try {
transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
} catch (TransformationException te1) {
throw new SAML2Exception(te1);
}
try {
transforms.addTransform(transformAlg);
} catch (TransformationException te2) {
throw new SAML2Exception(te2);
}
String ref = "#" + idValue;
try {
sig.addDocument(ref, transforms, Constants.ALGO_ID_DIGEST_SHA1);
} catch (XMLSignatureException sige1) {
throw new SAML2Exception(sige1);
}
if (cert != null) {
try {
sig.addKeyInfo(cert);
} catch (XMLSecurityException xse3) {
throw new SAML2Exception(xse3);
}
}
try {
sig.sign(privateKey);
} catch (XMLSignatureException sige2) {
throw new SAML2Exception(sige2);
}
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message(classMethod + "Signing is successful.");
}
return sig.getElement();
}
use of org.apache.xml.security.exceptions.XMLSecurityException in project OpenAM by OpenRock.
the class SecurityUtils method getPublicKey.
/**
* Returns the <code>PublicKey</code>.
*/
private static PublicKey getPublicKey(Element reference) throws XMLSignatureException {
PublicKey pubKey = null;
Document doc = reference.getOwnerDocument();
Element dsaKey = (Element) reference.getElementsByTagNameNS(Constants.SignatureSpecNS, SAMLConstants.TAG_DSAKEYVALUE).item(0);
if (dsaKey != null) {
// It's DSAKey
NodeList nodes = dsaKey.getChildNodes();
int nodeCount = nodes.getLength();
if (nodeCount > 0) {
BigInteger p = null, q = null, g = null, y = null;
for (int i = 0; i < nodeCount; i++) {
Node currentNode = nodes.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
String tagName = currentNode.getLocalName();
Node sub = currentNode.getChildNodes().item(0);
String value = sub.getNodeValue();
value = SAMLUtils.removeNewLineChars(value);
BigInteger v = new BigInteger(Base64.decode(value));
if (tagName.equals("P")) {
p = v;
} else if (tagName.equals("Q")) {
q = v;
} else if (tagName.equals("G")) {
g = v;
} else if (tagName.equals("Y")) {
y = v;
} else {
SAMLUtils.debug.error("Wrong tag name in DSA key.");
throw new XMLSignatureException(SAMLUtils.bundle.getString("errorObtainPK"));
}
}
}
DSAKeyValue dsaKeyValue = new DSAKeyValue(doc, p, q, g, y);
try {
pubKey = dsaKeyValue.getPublicKey();
} catch (XMLSecurityException xse) {
SAMLUtils.debug.error("Could not get Public Key from" + " DSA key value.");
throw new XMLSignatureException(SAMLUtils.bundle.getString("errorObtainPK"));
}
}
} else {
Element rsaKey = (Element) reference.getElementsByTagNameNS(Constants.SignatureSpecNS, SAMLConstants.TAG_RSAKEYVALUE).item(0);
if (rsaKey != null) {
// It's RSAKey
NodeList nodes = rsaKey.getChildNodes();
int nodeCount = nodes.getLength();
BigInteger m = null, e = null;
if (nodeCount > 0) {
for (int i = 0; i < nodeCount; i++) {
Node currentNode = nodes.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
String tagName = currentNode.getLocalName();
Node sub = currentNode.getChildNodes().item(0);
String value = sub.getNodeValue();
value = SAMLUtils.removeNewLineChars(value);
BigInteger v = new BigInteger(Base64.decode(value));
if (tagName.equals("Exponent")) {
e = v;
} else if (tagName.equals("Modulus")) {
m = v;
} else {
SAMLUtils.debug.error("Wrong tag name from " + "RSA key element.");
throw new XMLSignatureException(SAMLUtils.bundle.getString("errorObtainPK"));
}
}
}
}
RSAKeyValue rsaKeyValue = new RSAKeyValue(doc, m, e);
try {
pubKey = rsaKeyValue.getPublicKey();
} catch (XMLSecurityException ex) {
SAMLUtils.debug.error("Could not get Public Key from" + " RSA key value.");
throw new XMLSignatureException(SAMLUtils.bundle.getString("errorObtainPK"));
}
}
}
return pubKey;
}
use of org.apache.xml.security.exceptions.XMLSecurityException in project OpenAM by OpenRock.
the class DefaultSubjectProvider method getHoKSubjectConfirmationData.
private SubjectConfirmationData getHoKSubjectConfirmationData(X509Certificate certificate) throws TokenCreationException {
Element keyInfoElement;
try {
keyInfoElement = keyInfoFactory.generatePublicKeyInfo(certificate);
} catch (ParserConfigurationException e) {
throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught generating KeyInfo for HoK SubjectConfirmation DefaultSubjectProvider: " + e, e);
} catch (XMLSecurityException e) {
throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught generating KeyInfo for HoK SubjectConfirmation DefaultSubjectProvider: " + e, e);
}
try {
final List<Element> elementList = new ArrayList<Element>();
elementList.add(keyInfoElement);
final SubjectConfirmationData subjectConfirmationData = AssertionFactory.getInstance().createSubjectConfirmationData();
subjectConfirmationData.setContentType(KEY_INFO_CONFIRMATION_DATA_TYPE);
subjectConfirmationData.setContent(elementList);
return subjectConfirmationData;
} catch (SAML2Exception e) {
throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught generating SubjectConfirmationData with HoK KeyInfo element in DefaultSubjectProvider: " + e, e);
}
}
use of org.apache.xml.security.exceptions.XMLSecurityException in project ddf by codice.
the class X509PathTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*
* @param tokenParameters
* @return TokenValidatorResponse
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.trace("Validating X.509 Token");
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
Crypto sigCrypto = stsProperties.getSignatureCrypto();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(sigCrypto);
requestData.setWssConfig(WSSConfig.getNewInstance());
requestData.setCallbackHandler(callbackHandler);
requestData.setMsgContext(tokenParameters.getMessageContext());
requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
BinarySecurity binarySecurity = null;
BinarySecurityTokenType binarySecurityType = null;
if (validateTarget.isBinarySecurityToken()) {
binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
// Test the encoding type
String encodingType = binarySecurityType.getEncodingType();
if (!BASE64_ENCODING.equals(encodingType)) {
LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
return response;
}
//
// Turn the received JAXB object into a DOM element
//
Document doc = DOMUtils.createDocument();
binarySecurity = new X509Security(doc);
binarySecurity.setEncodingType(encodingType);
binarySecurity.setValueType(binarySecurityType.getValueType());
String data = binarySecurityType.getValue();
Node textNode = doc.createTextNode(data);
binarySecurity.getElement().appendChild(textNode);
} else if (validateTarget.isDOMElement()) {
try {
Document doc = DOMUtils.createDocument();
binarySecurity = new X509Security(doc);
binarySecurity.setEncodingType(BASE64_ENCODING);
X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
if (x509Data.containsCertificate()) {
XMLX509Certificate xmlx509Certificate = x509Data.itemCertificate(0);
if (xmlx509Certificate == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN);
}
X509Certificate cert = xmlx509Certificate.getX509Certificate();
((X509Security) binarySecurity).setX509Certificate(cert);
}
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to set certificate", ex);
return response;
} catch (XMLSecurityException ex) {
LOGGER.debug("Unable to get certificates", ex);
return response;
}
} else {
return response;
}
//
try {
Credential credential = new Credential();
credential.setBinarySecurityToken(binarySecurity);
if (merlin != null) {
byte[] token = binarySecurity.getToken();
if (token != null) {
if (binarySecurityType != null) {
if (binarySecurityType.getValueType().equals(X509_PKI_PATH)) {
X509Certificate[] certificates = merlin.getCertificatesFromBytes(token);
if (certificates != null) {
credential.setCertificates(certificates);
}
} else {
X509Certificate singleCert = merlin.loadCertificate(new ByteArrayInputStream(token));
credential.setCertificates(new X509Certificate[] { singleCert });
}
}
} else {
LOGGER.debug("Binary Security Token bytes were null.");
}
}
Credential returnedCredential = validator.validate(credential, requestData);
X500Principal subjectX500Principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
response.setPrincipal(subjectX500Principal);
if (response.getAdditionalProperties() == null) {
response.setAdditionalProperties(new HashMap<>());
}
try {
String emailAddress = SubjectUtils.getEmailAddress(subjectX500Principal);
if (emailAddress != null) {
response.getAdditionalProperties().put(SubjectUtils.EMAIL_ADDRESS_CLAIM_URI, emailAddress);
}
String country = SubjectUtils.getCountry(subjectX500Principal);
if (country != null) {
response.getAdditionalProperties().put(SubjectUtils.COUNTRY_CLAIM_URI, country);
}
} catch (Exception e) {
LOGGER.debug("Unable to set email address or country from certificate.", e);
}
validateTarget.setState(STATE.VALID);
validateTarget.setPrincipal(subjectX500Principal);
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate credentials.", ex);
}
return response;
}
Aggregations