use of org.apache.wss4j.dom.engine.WSSConfig 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.dom.engine.WSSConfig in project cxf by apache.
the class WSS4JInInterceptor method createSecurityEngine.
/**
* @return a freshly minted WSSecurityEngine instance, using the
* (non-null) processor map, to be used to initialize the
* WSSecurityEngine instance.
*/
protected static WSSecurityEngine createSecurityEngine(final Map<QName, Object> map) {
assert map != null;
final WSSConfig config = WSSConfig.getNewInstance();
for (Map.Entry<QName, Object> entry : map.entrySet()) {
final QName key = entry.getKey();
Object val = entry.getValue();
if (val instanceof Class<?>) {
config.setProcessor(key, (Class<?>) val);
} else if (val instanceof Processor) {
config.setProcessor(key, (Processor) val);
} else if (val instanceof Validator) {
config.setValidator(key, (Validator) val);
} else if (val == null) {
config.setProcessor(key, (Class<?>) null);
}
}
final WSSecurityEngine ret = new WSSecurityEngine();
ret.setWssConfig(config);
return ret;
}
use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.
the class SpnegoTokenInterceptorProvider method setupClient.
static String setupClient(STSClient client, SoapMessage message, AssertionInfoMap aim) {
client.setTrust(NegotiationUtils.getTrust10(aim));
client.setTrust(NegotiationUtils.getTrust13(aim));
Policy p = new Policy();
ExactlyOne ea = new ExactlyOne();
p.addPolicyComponent(ea);
All all = new All();
all.addPolicyComponent(NegotiationUtils.getAddressingPolicy(aim, false));
ea.addPolicyComponent(all);
client.setPolicy(p);
client.setSoap11(message.getVersion() == Soap11.getInstance());
client.setSpnego(true);
WSSConfig config = WSSConfig.getNewInstance();
String context = config.getIdAllocator().createSecureId("_", null);
client.setContext(context);
String s = message.getContextualProperty(Message.ENDPOINT_ADDRESS).toString();
client.setLocation(s);
AlgorithmSuite suite = NegotiationUtils.getAlgorithmSuite(aim);
if (suite != null) {
client.setAlgorithmSuite(suite);
int x = suite.getAlgorithmSuiteType().getMaximumSymmetricKeyLength();
if (x < 256) {
client.setKeySize(x);
}
}
Map<String, Object> ctx = client.getRequestContext();
mapSecurityProps(message, ctx);
return s;
}
use of org.apache.wss4j.dom.engine.WSSConfig in project ddf by codice.
the class LoginFilter method handleAuthenticationToken.
private Subject handleAuthenticationToken(HttpServletRequest httpRequest, SAMLAuthenticationToken token) throws ServletException {
Subject subject;
try {
LOGGER.debug("Validating received SAML assertion.");
boolean wasReference = false;
boolean firstLogin = true;
if (token.isReference()) {
wasReference = true;
LOGGER.trace("Converting SAML reference to assertion");
Object sessionToken = httpRequest.getSession(false).getAttribute(SecurityConstants.SAML_ASSERTION);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Http Session assertion - class: {} loader: {}", sessionToken.getClass().getName(), sessionToken.getClass().getClassLoader());
LOGGER.trace("SecurityToken class: {} loader: {}", SecurityToken.class.getName(), SecurityToken.class.getClassLoader());
}
SecurityToken savedToken = null;
try {
savedToken = ((SecurityTokenHolder) sessionToken).getSecurityToken(token.getRealm());
} catch (ClassCastException e) {
httpRequest.getSession(false).invalidate();
}
if (savedToken != null) {
firstLogin = false;
token.replaceReferenece(savedToken);
}
if (token.isReference()) {
String msg = "Missing or invalid SAML assertion for provided reference.";
LOGGER.debug(msg);
throw new InvalidSAMLReceivedException(msg);
}
}
SAMLAuthenticationToken newToken = renewSecurityToken(httpRequest.getSession(false), token);
SecurityToken securityToken;
if (newToken != null) {
firstLogin = false;
securityToken = (SecurityToken) newToken.getCredentials();
} else {
securityToken = (SecurityToken) token.getCredentials();
}
if (!wasReference) {
// wrap the token
SamlAssertionWrapper assertion = new SamlAssertionWrapper(securityToken.getToken());
// get the crypto junk
Crypto crypto = getSignatureCrypto();
Response samlResponse = createSamlResponse(httpRequest.getRequestURI(), assertion.getIssuerString(), createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null));
BUILDER.get().reset();
Document doc = BUILDER.get().newDocument();
Element policyElement = OpenSAMLUtil.toDom(samlResponse, doc);
doc.appendChild(policyElement);
Credential credential = new Credential();
credential.setSamlAssertion(assertion);
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(crypto);
WSSConfig wssConfig = WSSConfig.getNewInstance();
requestData.setWssConfig(wssConfig);
X509Certificate[] x509Certs = (X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate");
requestData.setTlsCerts(x509Certs);
validateHolderOfKeyConfirmation(assertion, x509Certs);
if (assertion.isSigned()) {
// Verify the signature
WSSSAMLKeyInfoProcessor wsssamlKeyInfoProcessor = new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument()));
assertion.verifySignature(wsssamlKeyInfoProcessor, crypto);
assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument())), requestData.getSigVerCrypto(), requestData.getCallbackHandler());
}
// Validate the Assertion & verify trust in the signature
assertionValidator.validate(credential, requestData);
}
// if it is all good, then we'll create our subject
subject = securityManager.getSubject(securityToken);
if (firstLogin) {
boolean hasSecurityAuditRole = Arrays.stream(System.getProperty("security.audit.roles").split(",")).filter(subject::hasRole).findFirst().isPresent();
if (hasSecurityAuditRole) {
SecurityLogger.audit("Subject has logged in with admin privileges", subject);
}
}
if (!wasReference && firstLogin) {
addSamlToSession(httpRequest, token.getRealm(), securityToken);
}
} catch (SecurityServiceException e) {
LOGGER.debug("Unable to get subject from SAML request.", e);
throw new ServletException(e);
} catch (WSSecurityException e) {
LOGGER.debug("Unable to read/validate security token from request.", e);
throw new ServletException(e);
}
return subject;
}
use of org.apache.wss4j.dom.engine.WSSConfig in project ddf by codice.
the class WebSSOTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
@Override
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.debug("Validating SSO Token");
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
Crypto sigCrypto = stsProperties.getSignatureCrypto();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(sigCrypto);
WSSConfig wssConfig = WSSConfig.getNewInstance();
requestData.setWssConfig(wssConfig);
requestData.setCallbackHandler(callbackHandler);
LOGGER.debug("Setting validate state to invalid before check.");
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
if (!validateTarget.isBinarySecurityToken()) {
LOGGER.debug("Validate target is not a binary security token, returning invalid response.");
return response;
}
LOGGER.debug("Getting binary security token from validate target");
BinarySecurityTokenType binarySecurityToken = (BinarySecurityTokenType) validateTarget.getToken();
//
// Decode the token
//
LOGGER.debug("Decoding binary security token.");
String base64Token = binarySecurityToken.getValue();
String ticket = null;
String service = null;
try {
byte[] token = Base64.getDecoder().decode(base64Token);
if (token == null || token.length == 0) {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null.");
}
String decodedToken = new String(token, Charset.forName("UTF-8"));
if (StringUtils.isNotBlank(decodedToken)) {
LOGGER.debug("Binary security token successfully decoded: {}", decodedToken);
// Token is in the format ticket|service
String[] parts = StringUtils.split(decodedToken, CAS_BST_SEP);
if (parts.length == 2) {
ticket = parts[0];
service = parts[1];
} else {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Was not able to parse out BST propertly. Should be in ticket|service format.");
}
} else {
throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null.");
}
} catch (WSSecurityException wsse) {
String msg = "Unable to decode BST into ticket and service for validation to CAS.";
LOGGER.info(msg, wsse);
return response;
}
//
try {
LOGGER.debug("Validating ticket [{}] for service [{}].", ticket, service);
// validate either returns an assertion or throws an exception
Assertion assertion = validate(ticket, service);
AttributePrincipal principal = assertion.getPrincipal();
LOGGER.debug("User name retrieved from CAS: {}", principal.getName());
response.setPrincipal(principal);
LOGGER.debug("CAS ticket successfully validated, setting state to valid.");
validateTarget.setState(STATE.VALID);
} catch (TicketValidationException e) {
LOGGER.debug("Unable to validate CAS token.", e);
}
return response;
}
Aggregations