use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.
the class SAMLTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOG.fine("Validating SAML Token");
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
Crypto sigCrypto = stsProperties.getSignatureCrypto();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
if (!validateTarget.isDOMElement()) {
return response;
}
try {
Element validateTargetElement = (Element) validateTarget.getToken();
SamlAssertionWrapper assertion = new SamlAssertionWrapper(validateTargetElement);
if (!assertion.isSigned()) {
LOG.log(Level.WARNING, "The received assertion is not signed, and therefore not trusted");
return response;
}
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(sigCrypto);
WSSConfig wssConfig = WSSConfig.getNewInstance();
requestData.setWssConfig(wssConfig);
requestData.setCallbackHandler(callbackHandler);
requestData.setMsgContext(tokenParameters.getMessageContext());
requestData.setSubjectCertConstraints(certConstraints.getCompiledSubjectContraints());
requestData.setWsDocInfo(new WSDocInfo(validateTargetElement.getOwnerDocument()));
// Verify the signature
Signature sig = assertion.getSignature();
KeyInfo keyInfo = sig.getKeyInfo();
SAMLKeyInfo samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto);
assertion.verifySignature(samlKeyInfo);
SecurityToken secToken = null;
byte[] signatureValue = assertion.getSignatureValue();
if (tokenParameters.getTokenStore() != null && signatureValue != null && signatureValue.length > 0) {
int hash = Arrays.hashCode(signatureValue);
secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
if (secToken != null && secToken.getTokenHash() != hash) {
secToken = null;
}
}
if (secToken != null && secToken.isExpired()) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Token: " + secToken.getId() + " is in the cache but expired - revalidating");
}
secToken = null;
}
Principal principal = null;
if (secToken == null) {
// Validate the assertion against schemas/profiles
validateAssertion(assertion);
// Now verify trust on the signature
Credential trustCredential = new Credential();
trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
trustCredential.setCertificates(samlKeyInfo.getCerts());
trustCredential = validator.validate(trustCredential, requestData);
principal = trustCredential.getPrincipal();
// Finally check that subject DN of the signing certificate matches a known constraint
X509Certificate cert = null;
if (trustCredential.getCertificates() != null) {
cert = trustCredential.getCertificates()[0];
}
if (!certConstraints.matches(cert)) {
return response;
}
}
if (principal == null) {
principal = new SAMLTokenPrincipalImpl(assertion);
}
// Parse roles from the validated token
if (samlRoleParser != null) {
Set<Principal> roles = samlRoleParser.parseRolesFromAssertion(principal, null, assertion);
response.setRoles(roles);
}
// Get the realm of the SAML token
String tokenRealm = null;
SAMLRealmCodec codec = samlRealmCodec;
if (codec == null) {
codec = stsProperties.getSamlRealmCodec();
}
if (codec != null) {
tokenRealm = codec.getRealmFromToken(assertion);
// verify the realm against the cached token
if (secToken != null) {
Map<String, Object> props = secToken.getProperties();
if (props != null) {
String cachedRealm = (String) props.get(STSConstants.TOKEN_REALM);
if (cachedRealm != null && !tokenRealm.equals(cachedRealm)) {
return response;
}
}
}
}
response.setTokenRealm(tokenRealm);
if (!validateConditions(assertion, validateTarget)) {
return response;
}
// Store the successfully validated token in the cache
if (secToken == null) {
storeTokenInCache(tokenParameters.getTokenStore(), assertion, tokenParameters.getPrincipal(), tokenRealm);
}
// Add the SamlAssertionWrapper to the properties, as the claims are required to be transformed
Map<String, Object> addProps = new HashMap<>(1);
addProps.put(SamlAssertionWrapper.class.getName(), assertion);
response.setAdditionalProperties(addProps);
response.setPrincipal(principal);
validateTarget.setState(STATE.VALID);
LOG.fine("SAML Token successfully validated");
} catch (WSSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
}
return response;
}
use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.
the class SCTCanceller method cancelToken.
/**
* Cancel a Token using the given TokenCancellerParameters.
*/
public TokenCancellerResponse cancelToken(TokenCancellerParameters tokenParameters) {
LOG.fine("Trying to cancel a SecurityContextToken");
TokenCancellerResponse response = new TokenCancellerResponse();
ReceivedToken cancelTarget = tokenParameters.getToken();
if (tokenParameters.getTokenStore() == null) {
LOG.log(Level.FINE, "A cache must be configured to use the SCTCanceller");
return response;
}
if (cancelTarget == null) {
LOG.log(Level.FINE, "Cancel Target is null");
return response;
}
cancelTarget.setState(STATE.NONE);
response.setToken(cancelTarget);
if (cancelTarget.isDOMElement()) {
try {
Element cancelTargetElement = (Element) cancelTarget.getToken();
SecurityContextToken sct = new SecurityContextToken(cancelTargetElement);
String identifier = sct.getIdentifier();
SecurityToken token = tokenParameters.getTokenStore().getToken(identifier);
if (token == null) {
LOG.fine("Identifier: " + identifier + " is not found in the cache");
return response;
}
if (verifyProofOfPossession && !matchKey(tokenParameters, token.getSecret())) {
throw new STSException("Failed to verify the proof of possession of the key associated with the " + "security context. No matching key found in the request.", STSException.INVALID_REQUEST);
}
tokenParameters.getTokenStore().remove(token.getId());
cancelTarget.setState(STATE.CANCELLED);
LOG.fine("SecurityContextToken successfully cancelled");
} catch (WSSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
}
}
return response;
}
use of org.apache.wss4j.common.ext.WSSecurityException 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.ext.WSSecurityException in project cxf by apache.
the class Saml2CallbackHandler method handle.
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof SAMLCallback) {
SAMLCallback callback = (SAMLCallback) callbacks[i];
callback.setSamlVersion(Version.SAML_20);
callback.setIssuer("intermediary");
String subjectName = "uid=" + principal.getName();
String confirmationMethod = SAML2Constants.CONF_SENDER_VOUCHES;
SubjectBean subjectBean = new SubjectBean(subjectName, null, confirmationMethod);
callback.setSubject(subjectBean);
AttributeStatementBean attrBean = new AttributeStatementBean();
if (subjectBean != null) {
attrBean.setSubject(subjectBean);
}
AttributeBean attributeBean = new AttributeBean();
attributeBean.setQualifiedName("role");
attributeBean.addAttributeValue("user");
attrBean.setSamlAttributes(Collections.singletonList(attributeBean));
callback.setAttributeStatementData(Collections.singletonList(attrBean));
try {
String file = "serviceKeystore.properties";
Crypto crypto = CryptoFactory.getInstance(file);
callback.setIssuerCrypto(crypto);
callback.setIssuerKeyName("myservicekey");
callback.setIssuerKeyPassword("skpass");
callback.setSignAssertion(true);
} catch (WSSecurityException e) {
throw new IOException(e);
}
}
}
}
use of org.apache.wss4j.common.ext.WSSecurityException in project cxf by apache.
the class SymmetricBindingHandler method doEncryption.
private WSSecEncrypt doEncryption(AbstractTokenWrapper recToken, SecurityToken encrTok, boolean attached, List<WSEncryptionPart> encrParts, boolean atEnd, SecretKey symmetricKey) {
AbstractToken encrToken = recToken.getToken();
assertPolicy(recToken);
assertPolicy(encrToken);
try {
WSSecEncrypt encr = new WSSecEncrypt(secHeader);
encr.setEncryptionSerializer(new StaxSerializer());
encr.setIdAllocator(wssConfig.getIdAllocator());
encr.setCallbackLookup(callbackLookup);
encr.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message));
encr.setStoreBytesInAttachment(storeBytesInAttachment);
encr.setExpandXopInclude(isExpandXopInclude());
encr.setWsDocInfo(wsDocInfo);
String encrTokId = encrTok.getId();
if (attached) {
encrTokId = encrTok.getWsuId();
if (encrTokId == null && (encrToken instanceof SecureConversationToken || encrToken instanceof SecurityContextToken)) {
encr.setEncKeyIdDirectId(true);
encrTokId = encrTok.getId();
} else if (encrTokId == null) {
encrTokId = encrTok.getId();
}
if (encrTokId.startsWith("#")) {
encrTokId = encrTokId.substring(1);
}
} else {
encr.setEncKeyIdDirectId(true);
}
if (encrTok.getTokenType() != null) {
encr.setCustomReferenceValue(encrTok.getTokenType());
}
encr.setEncKeyId(encrTokId);
AlgorithmSuite algorithmSuite = sbinding.getAlgorithmSuite();
encr.setSymmetricEncAlgorithm(algorithmSuite.getAlgorithmSuiteType().getEncryption());
Crypto crypto = getEncryptionCrypto();
if (crypto != null) {
setEncryptionUser(encr, encrToken, false, crypto);
}
encr.setEncryptSymmKey(false);
encr.setMGFAlgorithm(algorithmSuite.getAlgorithmSuiteType().getMGFAlgo());
encr.setDigestAlgorithm(algorithmSuite.getAlgorithmSuiteType().getEncryptionDigest());
if (encrToken instanceof IssuedToken || encrToken instanceof SpnegoContextToken || encrToken instanceof SecureConversationToken) {
// Setting the AttachedReference or the UnattachedReference according to the flag
Element ref;
if (attached) {
ref = encrTok.getAttachedReference();
} else {
ref = encrTok.getUnattachedReference();
}
String tokenType = encrTok.getTokenType();
if (ref != null) {
SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer());
encr.setSecurityTokenReference(secRef);
} else if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
encr.setCustomReferenceValue(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
} else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
encr.setCustomReferenceValue(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
} else {
encr.setCustomReferenceValue(tokenType);
encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
}
} else if (encrToken instanceof UsernameToken) {
encr.setCustomReferenceValue(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
} else if (encrToken instanceof KerberosToken && !isRequestor()) {
encr.setCustomReferenceValue(WSS4JConstants.WSS_KRB_KI_VALUE_TYPE);
encr.setEncKeyId(encrTok.getSHA1());
} else if (!isRequestor() && encrTok.getSHA1() != null) {
encr.setCustomReferenceValue(encrTok.getSHA1());
encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
}
encr.prepare(crypto, symmetricKey);
if (encr.getBSTTokenId() != null) {
encr.prependBSTElementToHeader();
}
Element refList = encr.encryptForRef(null, encrParts, symmetricKey);
List<Element> attachments = encr.getAttachmentEncryptedDataElements();
addAttachmentsForEncryption(atEnd, refList, attachments);
return encr;
} catch (InvalidCanonicalizerException | WSSecurityException e) {
LOG.log(Level.FINE, e.getMessage(), e);
unassertPolicy(recToken, e);
}
return null;
}
Aggregations