use of org.apache.wss4j.common.token.BinarySecurity in project cxf by apache.
the class X509TokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOG.fine("Validating X.509 Token");
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
// See CXF-4028
Crypto crypto = stsProperties.getEncryptionCrypto();
if (crypto == null) {
crypto = stsProperties.getSignatureCrypto();
}
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(crypto);
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);
final BinarySecurity binarySecurity;
if (validateTarget.isBinarySecurityToken()) {
BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
// Test the encoding type
String encodingType = binarySecurityType.getEncodingType();
if (!BASE64_ENCODING.equals(encodingType)) {
LOG.fine("Bad encoding type attribute specified: " + encodingType);
return response;
}
//
// Turn the received JAXB object into a DOM element
//
Document doc = DOMUtils.getEmptyDocument();
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.getEmptyDocument();
binarySecurity = new X509Security(doc);
binarySecurity.setEncodingType(BASE64_ENCODING);
X509Data x509Data = new X509Data((Element) validateTarget.getToken(), "");
if (x509Data.containsCertificate()) {
X509Certificate cert = x509Data.itemCertificate(0).getX509Certificate();
((X509Security) binarySecurity).setX509Certificate(cert);
}
} catch (XMLSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
return response;
}
} else {
return response;
}
//
try {
Credential credential = new Credential();
credential.setBinarySecurityToken(binarySecurity);
if (crypto != null) {
X509Certificate cert = ((X509Security) binarySecurity).getX509Certificate(crypto);
credential.setCertificates(new X509Certificate[] { cert });
}
Credential returnedCredential = validator.validate(credential, requestData);
Principal principal = returnedCredential.getPrincipal();
if (principal == null) {
principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
}
response.setPrincipal(principal);
validateTarget.setState(STATE.VALID);
LOG.fine("X.509 Token successfully validated");
} catch (WSSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
}
return response;
}
use of org.apache.wss4j.common.token.BinarySecurity 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;
}
use of org.apache.wss4j.common.token.BinarySecurity in project cxf by apache.
the class BinarySecurityTokenTest method testBinarySecurityToken.
@org.junit.Test
public void testBinarySecurityToken() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = BinarySecurityTokenTest.class.getResource("client.xml");
Bus bus = bf.createBus(busFile.toString());
BusFactory.setDefaultBus(bus);
BusFactory.setThreadDefaultBus(bus);
URL wsdl = BinarySecurityTokenTest.class.getResource("DoubleItTokens.wsdl");
Service service = Service.create(wsdl, SERVICE_QNAME);
// Successful invocation
QName portQName = new QName(NAMESPACE, "DoubleItBinarySecurityTokenPort");
DoubleItPortType port = service.getPort(portQName, DoubleItPortType.class);
updateAddressPort(port, PORT);
// Mock up a BinarySecurityToken to add
SecurityToken securityToken = new SecurityToken();
securityToken.setId("_" + UUID.randomUUID().toString());
Document doc = DOMUtils.newDocument();
BinarySecurity binarySecurity = new BinarySecurity(doc);
binarySecurity.setValueType("http://custom-value-type");
binarySecurity.setToken("This is a token".getBytes());
securityToken.setToken(binarySecurity.getElement());
((BindingProvider) port).getRequestContext().put(SecurityConstants.TOKEN, securityToken);
assertEquals(50, port.doubleIt(25));
((java.io.Closeable) port).close();
bus.shutdown(true);
}
use of org.apache.wss4j.common.token.BinarySecurity in project cxf by apache.
the class IssuedTokenPolicyValidator method validatePolicies.
/**
* Validate policies.
*/
public void validatePolicies(PolicyValidatorParameters parameters, Collection<AssertionInfo> ais) {
List<WSSecurityEngineResult> samlResults = parameters.getSamlResults();
if (samlResults != null) {
for (WSSecurityEngineResult samlResult : samlResults) {
SamlAssertionWrapper samlAssertion = (SamlAssertionWrapper) samlResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
if (validateSAMLToken(parameters, samlAssertion, ais)) {
// Store token on the security context
SecurityToken token = createSecurityToken(samlAssertion);
parameters.getMessage().getExchange().put(SecurityConstants.TOKEN, token);
return;
}
}
}
List<WSSecurityEngineResult> bstResults = parameters.getResults().getActionResults().get(WSConstants.BST);
if (bstResults != null) {
for (WSSecurityEngineResult bstResult : bstResults) {
BinarySecurity binarySecurity = (BinarySecurity) bstResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
if (Boolean.TRUE.equals(bstResult.get(WSSecurityEngineResult.TAG_VALIDATED_TOKEN)) && validateBinarySecurityToken(parameters, binarySecurity, ais)) {
// Store token on the security context
SecurityToken token = createSecurityToken(binarySecurity);
parameters.getMessage().getExchange().put(SecurityConstants.TOKEN, token);
return;
}
}
}
}
use of org.apache.wss4j.common.token.BinarySecurity in project cxf by apache.
the class LayoutPolicyValidator method findCorrespondingTokenIndex.
/**
* Find the index of the token corresponding to either the X509Certificate or PublicKey used
* to sign the "signatureResult" argument.
*/
private int findCorrespondingTokenIndex(WSSecurityEngineResult signatureResult, List<WSSecurityEngineResult> results) {
// See what was used to sign this result
X509Certificate cert = (X509Certificate) signatureResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
PublicKey publicKey = (PublicKey) signatureResult.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
for (int i = 0; i < results.size(); i++) {
WSSecurityEngineResult token = results.get(i);
Integer actInt = (Integer) token.get(WSSecurityEngineResult.TAG_ACTION);
if (actInt == WSConstants.SIGN) {
continue;
}
BinarySecurity binarySecurity = (BinarySecurity) token.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
PublicKey foundPublicKey = (PublicKey) token.get(WSSecurityEngineResult.TAG_PUBLIC_KEY);
if (binarySecurity instanceof X509Security || binarySecurity instanceof PKIPathSecurity) {
X509Certificate foundCert = (X509Certificate) token.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
if (foundCert.equals(cert)) {
return i;
}
} else if (actInt.intValue() == WSConstants.ST_SIGNED || actInt.intValue() == WSConstants.ST_UNSIGNED) {
SamlAssertionWrapper assertionWrapper = (SamlAssertionWrapper) token.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
if (samlKeyInfo != null) {
X509Certificate[] subjectCerts = samlKeyInfo.getCerts();
PublicKey subjectPublicKey = samlKeyInfo.getPublicKey();
if ((cert != null && subjectCerts != null && cert.equals(subjectCerts[0])) || (subjectPublicKey != null && subjectPublicKey.equals(publicKey))) {
return i;
}
}
} else if (publicKey != null && publicKey.equals(foundPublicKey)) {
return i;
}
}
return -1;
}
Aggregations