/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.identity.federation.bindings.tomcat.sp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import org.apache.catalina.Session;
import org.apache.catalina.authenticator.Constants;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.deploy.LoginConfig;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.log4j.Logger;
import org.jboss.identity.federation.api.saml.v2.request.SAML2Request;
import org.jboss.identity.federation.api.saml.v2.response.SAML2Response;
import org.jboss.identity.federation.bindings.config.TrustType;
import org.jboss.identity.federation.bindings.tomcat.sp.holder.ServiceProviderSAMLContext;
import org.jboss.identity.federation.bindings.util.PostBindingUtil;
import org.jboss.identity.federation.bindings.util.ValveUtil;
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.saml.v2.exceptions.AssertionExpiredException;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
import org.jboss.identity.federation.core.saml.v2.holders.DestinationInfoHolder;
import org.jboss.identity.federation.saml.v2.assertion.EncryptedElementType;
import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
import org.xml.sax.SAXException;
/**
* Authenticator at the Service Provider
* that handles HTTP/Post binding of SAML 2
* but falls back on Form Authentication
*
* @author Anil.Saldhana@redhat.com
* @since Dec 12, 2008
*/
public class SPPostFormAuthenticator extends BaseFormAuthenticator
{
private static Logger log = Logger.getLogger(SPPostFormAuthenticator.class);
public SPPostFormAuthenticator()
{
super();
}
@Override
public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
{
SPUtil spUtil = new SPUtil();
Principal principal = request.getUserPrincipal();
if (principal != null)
{
log.debug("Already authenticated '" + principal.getName() + "'");
return true;
}
Session session = request.getSessionInternal(true);
String relayState = request.getParameter("RelayState");
//Try to get the username
try
{
principal = (GenericPrincipal) process(request,response);
if(principal == null)
{
AuthnRequestType authnRequest = spUtil.createSAMLRequest(serviceURL, identityURL);
sendRequestToIDP(authnRequest, relayState, response);
return false;
}
String username = principal.getName();
String password = ServiceProviderSAMLContext.EMPTY_PASSWORD;
//Map to JBoss specific principal
if(spConfiguration.getServerEnvironment().equalsIgnoreCase("JBOSS"))
{
GenericPrincipal gp = (GenericPrincipal) principal;
//Push a context
ServiceProviderSAMLContext.push(username, Arrays.asList(gp.getRoles()));
principal = context.getRealm().authenticate(username, password);
ServiceProviderSAMLContext.clear();
}
session.setNote(Constants.SESS_USERNAME_NOTE, username);
session.setNote(Constants.SESS_PASSWORD_NOTE, password);
request.setUserPrincipal(principal);
register(request, response, principal, Constants.FORM_METHOD, username, password);
return true;
}
catch(AssertionExpiredException aie)
{
log.debug("Assertion has expired. Issuing a new saml2 request to the IDP");
try
{
AuthnRequestType authnRequest = spUtil.createSAMLRequest(serviceURL, identityURL);
sendRequestToIDP(authnRequest, relayState, response);
}
catch (Exception e)
{
log.trace("Exception:",e);
}
return false;
}
catch(Exception e)
{
log.debug("Exception :",e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
//fallback
return super.authenticate(request, response, loginConfig);
}
protected void sendRequestToIDP(AuthnRequestType authnRequest, String relayState, Response response)
throws IOException, SAXException, JAXBException,GeneralSecurityException
{
SAML2Request saml2Request = new SAML2Request();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
saml2Request.marshall(authnRequest, baos);
String samlMessage = PostBindingUtil.base64Encode(baos.toString());
String destination = authnRequest.getDestination();
PostBindingUtil.sendPost(new DestinationInfoHolder(destination, samlMessage, relayState),
null,response, true);
}
protected AuthnRequestType createSAMLRequestMessage(String relayState, Response response)
throws ServletException, ConfigurationException
{
//create a saml request
if(this.serviceURL == null)
throw new ServletException("serviceURL is not configured");
SPUtil spUtil = new SPUtil();
return spUtil.createSAMLRequest(serviceURL, identityURL);
}
protected String getDestination(String urlEncodedRequest, String urlEncodedRelayState)
{
StringBuilder sb = new StringBuilder();
sb.append("?SAMLRequest=").append(urlEncodedRequest);
if(urlEncodedRelayState != null && urlEncodedRelayState.length() > 0)
sb.append("&RelayState=").append(urlEncodedRelayState);
return sb.toString();
}
protected void isTrusted(String issuer) throws IssuerNotTrustedException
{
try
{
String issuerDomain = ValveUtil.getDomain(issuer);
TrustType idpTrust = spConfiguration.getTrust();
if(idpTrust != null)
{
String domainsTrusted = idpTrust.getDomains();
if(domainsTrusted.indexOf(issuerDomain) < 0)
throw new IssuerNotTrustedException(issuer);
}
}
catch (Exception e)
{
throw new IssuerNotTrustedException(e.getLocalizedMessage(),e);
}
}
/**
* Subclasses should provide the implementation
* @param responseType ResponseType that contains the encrypted assertion
* @return response type with the decrypted assertion
*/
protected ResponseType decryptAssertion(ResponseType responseType)
{
throw new RuntimeException("This authenticator does not handle encryption");
}
private Principal process(Request request, Response response)
throws JAXBException, SAXException, IssuerNotTrustedException,
AssertionExpiredException, ConfigurationException, GeneralSecurityException
{
Principal userPrincipal = null;
String samlResponse = request.getParameter("SAMLResponse");
if(samlResponse != null && samlResponse.length() > 0 )
{
boolean isValid = false;
try
{
isValid = this.validate(request);
}
catch (IOException e)
{
throw new GeneralSecurityException(e);
}
if(!isValid)
throw new GeneralSecurityException("Validity check failed");
//deal with SAML response from IDP
byte[] base64DecodedResponse = PostBindingUtil.base64Decode(samlResponse);
InputStream is = new ByteArrayInputStream(base64DecodedResponse);
SAML2Response saml2Response = new SAML2Response();
ResponseType responseType = saml2Response.getResponseType(is);
this.isTrusted(responseType.getIssuer().getValue());
List<Object> assertions = responseType.getAssertionOrEncryptedAssertion();
if(assertions.size() == 0)
throw new IllegalStateException("No assertions in reply from IDP");
Object assertion = assertions.get(0);
if(assertion instanceof EncryptedElementType)
{
responseType = this.decryptAssertion(responseType);
}
SPUtil spUtil = new SPUtil();
return spUtil.handleSAMLResponse(request, responseType);
}
return userPrincipal;
}
}