use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class LoginFilterTest method testExpiredSamlCookie.
@Test(expected = ServletException.class)
public void testExpiredSamlCookie() throws IOException, XMLStreamException, ServletException, ParserConfigurationException, SAXException, SecurityServiceException {
FilterConfig filterConfig = mock(FilterConfig.class);
LoginFilter loginFilter = new LoginFilter();
loginFilter.setSessionFactory(sessionFactory);
ddf.security.service.SecurityManager securityManager = mock(ddf.security.service.SecurityManager.class);
loginFilter.setSecurityManager(securityManager);
loginFilter.setSignaturePropertiesFile("signature.properties");
try {
loginFilter.init(filterConfig);
} catch (ServletException e) {
fail(e.getMessage());
}
HttpServletRequest servletRequest = new TestHttpServletRequest();
HttpServletResponse servletResponse = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
SecurityToken securityToken = new SecurityToken();
Element thisToken = readDocument("/good_saml.xml").getDocumentElement();
securityToken.setToken(thisToken);
SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, securityToken, "karaf");
HandlerResult result = new HandlerResult(HandlerResult.Status.COMPLETED, samlToken);
servletRequest.setAttribute("ddf.security.token", result);
loginFilter.doFilter(servletRequest, servletResponse, filterChain);
}
use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class LoginFilter method addSamlToSession.
/**
* Adds SAML assertion to HTTP session.
*
* @param httpRequest the http request object for this request
* @param securityToken the SecurityToken object representing the SAML assertion
*/
private void addSamlToSession(HttpServletRequest httpRequest, String realm, SecurityToken securityToken) {
if (securityToken == null) {
LOGGER.debug("Cannot add null security token to session.");
return;
}
HttpSession session = sessionFactory.getOrCreateSession(httpRequest);
SecurityToken sessionToken = getSecurityToken(session, realm);
if (sessionToken == null) {
addSecurityToken(session, realm, securityToken);
}
SecurityAssertion securityAssertion = new SecurityAssertionImpl(securityToken);
SecurityLogger.audit("Added SAML for user [{}] to session [{}]", securityAssertion.getPrincipal().getName(), session.getId());
int minutes = getExpirationTime();
//we just want to set this to some non-zero value if the configuration is messed up
int seconds = 60;
if (minutes > 0) {
seconds = minutes * 60;
}
session.setMaxInactiveInterval(seconds);
}
use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class IdpEndpoint method determineAuthMethod.
private AuthObj determineAuthMethod(String bodyStr, AuthnRequest authnRequest) {
XMLStreamReader xmlStreamReader = null;
try {
xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(bodyStr));
} catch (XMLStreamException e) {
LOGGER.debug("Unable to parse SOAP message from client.", e);
}
SoapMessage soapMessage = new SoapMessage(Soap11.getInstance());
SAAJInInterceptor.SAAJPreInInterceptor preInInterceptor = new SAAJInInterceptor.SAAJPreInInterceptor();
soapMessage.setContent(XMLStreamReader.class, xmlStreamReader);
preInInterceptor.handleMessage(soapMessage);
SAAJInInterceptor inInterceptor = new SAAJInInterceptor();
inInterceptor.handleMessage(soapMessage);
SOAPPart soapMessageContent = (SOAPPart) soapMessage.getContent(Node.class);
AuthObj authObj = new AuthObj();
try {
Iterator soapHeaderElements = soapMessageContent.getEnvelope().getHeader().examineAllHeaderElements();
while (soapHeaderElements.hasNext()) {
SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) soapHeaderElements.next();
if (soapHeaderElement.getLocalName().equals("Security")) {
Iterator childElements = soapHeaderElement.getChildElements();
while (childElements.hasNext()) {
Object nextElement = childElements.next();
if (nextElement instanceof SOAPElement) {
SOAPElement element = (SOAPElement) nextElement;
if (element.getLocalName().equals("UsernameToken")) {
Iterator usernameTokenElements = element.getChildElements();
Object next;
while (usernameTokenElements.hasNext()) {
if ((next = usernameTokenElements.next()) instanceof Element) {
Element nextEl = (Element) next;
if (nextEl.getLocalName().equals("Username")) {
authObj.username = nextEl.getTextContent();
} else if (nextEl.getLocalName().equals("Password")) {
authObj.password = nextEl.getTextContent();
}
}
}
if (authObj.username != null && authObj.password != null) {
authObj.method = USER_PASS;
break;
}
} else if (element.getLocalName().equals("Assertion") && element.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
authObj.assertion = new SecurityToken(element.getAttribute("ID"), element, null, null);
authObj.method = SAML;
break;
}
}
}
}
}
} catch (SOAPException e) {
LOGGER.debug("Unable to parse SOAP message.", e);
}
RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
boolean requestingPki = false;
boolean requestingUp = false;
if (requestedAuthnContext != null) {
List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
for (AuthnContextClassRef authnContextClassRef : authnContextClassRefs) {
String authnContextClassRefStr = authnContextClassRef.getAuthnContextClassRef();
if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SMARTCARD_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SOFTWARE_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SPKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_TLS_CLIENT.equals(authnContextClassRefStr)) {
requestingPki = true;
} else if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD_PROTECTED_TRANSPORT.equals(authnContextClassRefStr)) {
requestingUp = true;
}
}
} else {
//The requested auth context isn't required so we don't know what they want... just set both to true
requestingPki = true;
requestingUp = true;
}
if (requestingUp && authObj.method != null && authObj.method.equals(USER_PASS)) {
LOGGER.trace("Found UsernameToken and correct AuthnContextClassRef");
return authObj;
} else if (requestingPki && authObj.method == null) {
LOGGER.trace("Found no token, but client requested PKI AuthnContextClassRef");
authObj.method = PKI;
return authObj;
} else if (authObj.method == null) {
LOGGER.debug("No authentication tokens found for the current request and the client did not request PKI authentication");
}
return authObj;
}
use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class IdpEndpoint method handleLogin.
protected org.opensaml.saml.saml2.core.Response handleLogin(AuthnRequest authnRequest, String authMethod, HttpServletRequest request, AuthObj authObj, boolean passive, boolean hasCookie) throws SecurityServiceException, WSSecurityException, SimpleSign.SignatureException, ConstraintViolationException {
LOGGER.debug("Performing login for user. passive: {}, cookie: {}", passive, hasCookie);
BaseAuthenticationToken token = null;
request.setAttribute(ContextPolicy.ACTIVE_REALM, BaseAuthenticationToken.ALL_REALM);
if (PKI.equals(authMethod)) {
LOGGER.debug("Logging user in via PKI.");
PKIHandler pkiHandler = new PKIHandler();
pkiHandler.setTokenFactory(tokenFactory);
try {
HandlerResult handlerResult = pkiHandler.getNormalizedToken(request, null, null, false);
if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
token = handlerResult.getToken();
}
} catch (ServletException e) {
LOGGER.info("Encountered an exception while checking for PKI auth info.", e);
}
} else if (USER_PASS.equals(authMethod)) {
LOGGER.debug("Logging user in via BASIC auth.");
if (authObj != null && authObj.username != null && authObj.password != null) {
token = new UPAuthenticationToken(authObj.username, authObj.password, BaseAuthenticationToken.ALL_REALM);
} else {
BasicAuthenticationHandler basicAuthenticationHandler = new BasicAuthenticationHandler();
HandlerResult handlerResult = basicAuthenticationHandler.getNormalizedToken(request, null, null, false);
if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
token = handlerResult.getToken();
}
}
} else if (SAML.equals(authMethod)) {
LOGGER.debug("Logging user in via SAML assertion.");
token = new SAMLAuthenticationToken(null, authObj.assertion, BaseAuthenticationToken.ALL_REALM);
} else if (GUEST.equals(authMethod) && guestAccess) {
LOGGER.debug("Logging user in as Guest.");
token = new GuestAuthenticationToken(BaseAuthenticationToken.ALL_REALM, request.getRemoteAddr());
} else {
throw new IllegalArgumentException("Auth method is not supported.");
}
org.w3c.dom.Element samlToken = null;
String statusCode;
if (hasCookie) {
samlToken = getSamlAssertion(request);
statusCode = StatusCode.SUCCESS;
} else {
try {
statusCode = StatusCode.AUTHN_FAILED;
Subject subject = securityManager.getSubject(token);
for (Object principal : subject.getPrincipals().asList()) {
if (principal instanceof SecurityAssertion) {
SecurityToken securityToken = ((SecurityAssertion) principal).getSecurityToken();
samlToken = securityToken.getToken();
}
}
if (samlToken != null) {
statusCode = StatusCode.SUCCESS;
}
} catch (SecurityServiceException e) {
if (!passive) {
throw e;
} else {
statusCode = StatusCode.AUTHN_FAILED;
}
}
}
LOGGER.debug("User log in successful.");
return SamlProtocol.createResponse(SamlProtocol.createIssuer(SystemBaseUrl.constructUrl("/idp/login", true)), SamlProtocol.createStatus(statusCode), authnRequest.getID(), samlToken);
}
use of org.apache.cxf.ws.security.tokenstore.SecurityToken in project ddf by codice.
the class IdpEndpointTest method setup.
@Before
public void setup() throws IOException, SecurityServiceException, ParserConfigurationException, SAXException {
System.setProperty("org.codice.ddf.system.hostname", "localhost");
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
File jksFile = temporaryFolder.newFile("serverKeystore.jks");
FileOutputStream jksOutStream = new FileOutputStream(jksFile);
InputStream jksStream = IdpEndpointTest.class.getResourceAsStream("/serverKeystore.jks");
IOUtils.copy(jksStream, jksOutStream);
IOUtils.closeQuietly(jksStream);
IOUtils.closeQuietly(jksOutStream);
File signatureFile = temporaryFolder.newFile("signature.properties");
FileOutputStream signatureOutStream = new FileOutputStream(signatureFile);
InputStream signatureStream = IdpEndpointTest.class.getResourceAsStream("/signature.properties");
IOUtils.copy(signatureStream, signatureOutStream);
IOUtils.closeQuietly(signatureStream);
IOUtils.closeQuietly(signatureOutStream);
File encryptionFile = temporaryFolder.newFile("encryption.properties");
FileOutputStream encryptionOutStream = new FileOutputStream(encryptionFile);
InputStream encryptionStream = IdpEndpointTest.class.getResourceAsStream("/encryption.properties");
IOUtils.copy(encryptionStream, encryptionOutStream);
IOUtils.closeQuietly(encryptionStream);
IOUtils.closeQuietly(encryptionOutStream);
EncryptionService encryptionService = mock(EncryptionService.class);
when(encryptionService.decrypt(anyString())).thenReturn("changeit");
when(encryptionService.encrypt(anyString())).thenReturn("changeit");
SecurityManager securityManager = mock(SecurityManager.class);
Subject subject = mock(Subject.class);
PrincipalCollection principalCollection = mock(PrincipalCollection.class);
SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
SecurityToken securityToken = mock(SecurityToken.class);
when(subject.getPrincipals()).thenReturn(principalCollection);
when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
when(securityAssertion.getSecurityToken()).thenReturn(securityToken);
when(securityToken.getToken()).thenReturn(readDocument("/saml.xml").getDocumentElement());
when(securityManager.getSubject(anyObject())).thenReturn(subject);
System.setProperty("javax.net.ssl.keyStore", jksFile.getAbsolutePath());
idpEndpoint = new IdpEndpoint(signatureFile.getAbsolutePath(), encryptionFile.getAbsolutePath(), encryptionService);
idpEndpoint.setStrictSignature(true);
idpEndpoint.init();
idpEndpoint.setSpMetadata(Collections.singletonList(spMetadata));
idpEndpoint.setSecurityManager(securityManager);
PKIAuthenticationTokenFactory pkiAuthenticationTokenFactory = new PKIAuthenticationTokenFactory();
pkiAuthenticationTokenFactory.setSignaturePropertiesPath(signatureFile.getAbsolutePath());
pkiAuthenticationTokenFactory.init();
idpEndpoint.setTokenFactory(pkiAuthenticationTokenFactory);
idpEndpoint.cookieCache.cacheSamlAssertion("1", readDocument("/saml.xml").getDocumentElement());
idpEndpoint.setExpirationTime(30);
relayState = "ef95c04b-6c05-4d12-b65f-dd32fed8811e";
requestCertificateAttributeName = "javax.servlet.request.X509Certificate";
requestURL = new StringBuffer("https://www.example.com");
samlConditionDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
signature = authNRequestGetSignature;
signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
ssoSAMLResponse = "https://localhost:8993/services/saml/sso?SAMLResponse=";
}
Aggregations