use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class UPBSTValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*
* @param tokenParameters
* @return TokenValidatorResponse
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.trace("Validating UPBST Token");
if (parser == null) {
throw new IllegalStateException("XMLParser must be configured.");
}
if (failedLoginDelayer == null) {
throw new IllegalStateException("Failed Login Delayer must be configured");
}
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);
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
if (!validateTarget.isBinarySecurityToken()) {
return response;
}
BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
// Test the encoding type
String encodingType = binarySecurityType.getEncodingType();
if (!UPAuthenticationToken.BASE64_ENCODING.equals(encodingType)) {
LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
return response;
}
UPAuthenticationToken usernameToken = getUsernameTokenFromTarget(validateTarget);
if (usernameToken == null) {
return response;
}
UsernameTokenType usernameTokenType = getUsernameTokenType(usernameToken);
// Marshall the received JAXB object into a DOM Element
Element usernameTokenElement = null;
JAXBElement<UsernameTokenType> tokenType = new JAXBElement<>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
Document doc = DOMUtils.createDocument();
Element rootElement = doc.createElement("root-element");
List<String> ctxPath = new ArrayList<>(1);
ctxPath.add(UsernameTokenType.class.getPackage().getName());
ParserConfigurator configurator = parser.configureParser(ctxPath, UPBSTValidator.class.getClassLoader());
try {
parser.marshal(configurator, tokenType, rootElement);
} catch (ParserException ex) {
LOGGER.info("Unable to parse username token", ex);
return response;
}
usernameTokenElement = (Element) rootElement.getFirstChild();
//
// Validate the token
//
WSSConfig wssConfig = WSSConfig.getNewInstance();
try {
boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
// The parsed principal is set independent whether validation is successful or not
response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
if (ut.getPassword() == null) {
return response;
}
String tokenId = String.format("%s:%s:%s", usernameToken.getUsername(), usernameToken.getPassword(), usernameToken.getRealm());
// See if the UsernameToken is stored in the cache
int hash = tokenId.hashCode();
SecurityToken secToken = null;
if (tokenParameters.getTokenStore() != null) {
secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
if (secToken != null && secToken.getTokenHash() != hash) {
secToken = null;
} else if (secToken != null) {
validateTarget.setState(STATE.VALID);
}
}
if (secToken == null) {
Credential credential = new Credential();
credential.setUsernametoken(ut);
if (usernameToken.getRealm() != null && !"*".equals(usernameToken.getRealm())) {
Validator validator = validators.get(usernameToken.getRealm());
if (validator != null) {
try {
validator.validate(credential, requestData);
validateTarget.setState(STATE.VALID);
LOGGER.debug("Validated user against realm {}", usernameToken.getRealm());
} catch (WSSecurityException ex) {
LOGGER.debug("Not able to validate user against realm {}", usernameToken.getRealm());
}
}
} else {
Set<Map.Entry<String, Validator>> entries = validators.entrySet();
for (Map.Entry<String, Validator> entry : entries) {
try {
entry.getValue().validate(credential, requestData);
validateTarget.setState(STATE.VALID);
LOGGER.debug("Validated user against realm {}", entry.getKey());
break;
} catch (WSSecurityException ex) {
LOGGER.debug("Not able to validate user against realm {}", entry.getKey());
}
}
}
}
Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
// Store the successfully validated token in the cache
if (tokenParameters.getTokenStore() != null && secToken == null && STATE.VALID.equals(validateTarget.getState())) {
secToken = new SecurityToken(ut.getID());
secToken.setToken(ut.getElement());
int hashCode = tokenId.hashCode();
String identifier = Integer.toString(hashCode);
secToken.setTokenHash(hashCode);
tokenParameters.getTokenStore().add(identifier, secToken);
}
response.setPrincipal(principal);
response.setTokenRealm(null);
validateTarget.setPrincipal(principal);
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate token.", ex);
}
if (response.getToken().getState() != STATE.VALID) {
failedLoginDelayer.delay(response.getToken().getPrincipal().getName());
}
return response;
}
use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class UPBSTValidatorTest method testValidateBadTokenCache.
@Test
public void testValidateBadTokenCache() {
UPBSTValidator upbstValidator = getUpbstValidator(new XmlParser(), meanValidator);
upbstValidator.addRealm(null);
TokenValidatorParameters tokenParameters = new TokenValidatorParameters();
tokenParameters.setTokenStore(new TokenStore() {
@Override
public void add(SecurityToken token) {
}
@Override
public void add(String identifier, SecurityToken token) {
}
@Override
public void remove(String identifier) {
}
@Override
public Collection<String> getTokenIdentifiers() {
return null;
}
@Override
public SecurityToken getToken(String identifier) {
SecurityToken securityToken = new SecurityToken();
securityToken.setTokenHash(-1432225336);
return securityToken;
}
});
ReceivedToken validateTarget = new ReceivedToken(upbstToken);
tokenParameters.setToken(validateTarget);
tokenParameters.setStsProperties(stsPropertiesMBean);
TokenValidatorResponse response = upbstValidator.validateToken(tokenParameters);
Assert.assertEquals(ReceivedToken.STATE.INVALID, response.getToken().getState());
verify(failedLoginDelayer, times(1)).delay(anyString());
}
use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class GuestInterceptor method internalHandleMessage.
private void internalHandleMessage(SoapMessage message, SOAPMessage soapMessage) throws Fault {
//Check if security header exists; if not, execute GuestInterceptor logic
String actor = (String) getOption(WSHandlerConstants.ACTOR);
if (actor == null) {
actor = (String) message.getContextualProperty(SecurityConstants.ACTOR);
}
Element existingSecurityHeader = null;
try {
LOGGER.debug("Checking for security header.");
existingSecurityHeader = WSSecurityUtil.getSecurityHeader(soapMessage.getSOAPPart(), actor);
} catch (WSSecurityException e1) {
LOGGER.debug("Issue with getting security header", e1);
}
if (existingSecurityHeader != null) {
LOGGER.debug("SOAP message contains security header, no action taken by the GuestInterceptor.");
return;
}
LOGGER.debug("Current request has no security header, continuing with GuestInterceptor");
AssertionInfoMap assertionInfoMap = message.get(AssertionInfoMap.class);
boolean hasAddressingAssertion = assertionInfoMap.entrySet().stream().flatMap(p -> p.getValue().stream()).filter(info -> MetadataConstants.ADDRESSING_ASSERTION_QNAME.equals(info.getAssertion().getName())).findFirst().isPresent();
if (hasAddressingAssertion) {
createAddressing(message, soapMessage);
}
LOGGER.debug("Creating guest security token.");
HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
SecurityToken securityToken = createSecurityToken(request.getRemoteAddr());
message.put(SecurityConstants.TOKEN, securityToken);
if (!MessageUtils.isRequestor(message)) {
try {
message.put(Message.REQUESTOR_ROLE, true);
policyBasedWss4jOutInterceptor.handleMessage(message);
} finally {
message.remove(Message.REQUESTOR_ROLE);
}
} else {
policyBasedWss4jOutInterceptor.handleMessage(message);
}
}
use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class GuestInterceptor method createSecurityToken.
private SecurityToken createSecurityToken(String ipAddress) {
SecurityToken securityToken = null;
Subject subject = getSubject(ipAddress);
LOGGER.trace("Attempting to create Security token.");
if (subject != null) {
PrincipalCollection principals = subject.getPrincipals();
if (principals != null) {
SecurityAssertion securityAssertion = principals.oneByType(SecurityAssertion.class);
if (securityAssertion != null) {
securityToken = securityAssertion.getSecurityToken();
} else {
LOGGER.info("Subject did not contain a security assertion, could not add assertion to the security header.");
}
} else {
LOGGER.info("Subject did not contain any principals, could not create security token.");
}
}
return securityToken;
}
use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class TestPepInterceptorActions method testMessageWithMessageAction.
@Test
public void testMessageWithMessageAction() throws SecurityServiceException {
PEPAuthorizingInterceptor interceptor = new PEPAuthorizingInterceptor();
SecurityManager mockSecurityManager = mock(SecurityManager.class);
interceptor.setSecurityManager(mockSecurityManager);
Message messageWithAction = mock(Message.class);
SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);
SecurityToken mockSecurityToken = mock(SecurityToken.class);
Subject mockSubject = mock(Subject.class);
assertNotNull(mockSecurityAssertion);
PowerMockito.mockStatic(SecurityAssertionStore.class);
PowerMockito.mockStatic(SecurityLogger.class);
when(SecurityAssertionStore.getSecurityAssertion(messageWithAction)).thenReturn(mockSecurityAssertion);
// SecurityLogger is already stubbed out
when(mockSecurityAssertion.getSecurityToken()).thenReturn(mockSecurityToken);
when(mockSecurityToken.getToken()).thenReturn(null);
when(mockSecurityManager.getSubject(mockSecurityToken)).thenReturn(mockSubject);
MessageInfo mockMessageInfo = mock(MessageInfo.class);
when(messageWithAction.get(MessageInfo.class.getName())).thenReturn(mockMessageInfo);
when(mockMessageInfo.getExtensionAttribute(new QName(Names.WSA_NAMESPACE_WSDL_METADATA, Names.WSAW_ACTION_NAME))).thenReturn("urn:catalog:query:query-port:search");
doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
CollectionPermission perm = (CollectionPermission) invocation.getArguments()[0];
assertEquals("urn:catalog:query:query-port:search", perm.getAction());
return true;
}
}).when(mockSubject).isPermitted(isA(CollectionPermission.class));
// This should work.
interceptor.handleMessage(messageWithAction);
PowerMockito.verifyStatic();
}
Aggregations