/*
* 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.idp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.Principal;
import java.security.PrivateKey;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;
import org.apache.catalina.connector.Response;
import org.apache.log4j.Logger;
import org.jboss.identity.federation.api.saml.v2.common.IDGenerator;
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.IDPType;
import org.jboss.identity.federation.bindings.config.TrustType;
import org.jboss.identity.federation.bindings.util.HTTPRedirectUtil;
import org.jboss.identity.federation.bindings.util.PostBindingUtil;
import org.jboss.identity.federation.bindings.util.RedirectBindingUtil;
import org.jboss.identity.federation.bindings.util.ValveUtil;
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.exceptions.ParsingException;
import org.jboss.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssueInstantMissingException;
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.core.saml.v2.holders.IDPInfoHolder;
import org.jboss.identity.federation.core.saml.v2.holders.IssuerInfoHolder;
import org.jboss.identity.federation.core.saml.v2.holders.SPInfoHolder;
import org.jboss.identity.federation.core.saml.v2.holders.SignatureInfoHolder;
import org.jboss.identity.federation.core.saml.v2.util.SignatureUtil;
import org.jboss.identity.federation.saml.v2.assertion.AssertionType;
import org.jboss.identity.federation.saml.v2.assertion.AttributeStatementType;
import org.jboss.identity.federation.saml.v2.protocol.RequestAbstractType;
import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
import org.xml.sax.SAXException;
/**
* Request Util
* <b> Not thread safe</b>
* @author Anil.Saldhana@redhat.com
* @since May 18, 2009
*/
public class IDPWebRequestUtil
{
private static Logger log = Logger.getLogger(IDPWebRequestUtil.class);
private HttpServletRequest request;
private boolean redirectProfile = false;
private boolean postProfile = false;
private IDPType idpConfiguration;
public IDPWebRequestUtil(HttpServletRequest request, IDPType idp)
{
this.request = request;
this.idpConfiguration = idp;
hasSAMLRequestInRedirectProfile();
hasSAMLRequestInPostProfile();
}
public boolean hasSAMLRequestInRedirectProfile()
{
if("GET".equalsIgnoreCase(request.getMethod()))
{
redirectProfile = request.getParameter("SAMLRequest") != null;
}
return redirectProfile;
}
public boolean hasSAMLRequestInPostProfile()
{
if("POST".equalsIgnoreCase(request.getMethod()))
{
postProfile = request.getParameter("SAMLRequest") != null;
}
return postProfile;
}
public RequestAbstractType getSAMLRequest(String samlMessage)
throws ParsingException
{
InputStream is = null;
SAML2Request saml2Request = new SAML2Request();
if(redirectProfile)
{
is = RedirectBindingUtil.base64DeflateDecode(samlMessage);
}
else
{
byte[] samlBytes = PostBindingUtil.base64Decode(samlMessage);
log.trace("SAMLRequest=" + new String(samlBytes));
is = new ByteArrayInputStream(samlBytes);
}
try
{
return saml2Request.getRequestType(is);
}
catch (JAXBException e)
{
throw new ParsingException(e);
}
catch (SAXException e)
{
throw new ParsingException(e);
}
}
public ResponseType getResponse( String assertionConsumerURL,
Principal userPrincipal,
List<String> roles,
String identityURL,
long assertionValidity)
throws ConfigurationException, IssueInstantMissingException
{
log.trace("AssertionConsumerURL=" + assertionConsumerURL +
"::assertion validity=" + assertionValidity);
ResponseType responseType = null;
SAML2Response saml2Response = new SAML2Response();
//Create a response type
String id = IDGenerator.create("ID_");
IssuerInfoHolder issuerHolder = new IssuerInfoHolder(identityURL);
issuerHolder.setStatusCode(JBossSAMLURIConstants.STATUS_SUCCESS.get());
IDPInfoHolder idp = new IDPInfoHolder();
idp.setNameIDFormatValue(userPrincipal.getName());
idp.setNameIDFormat(JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get());
SPInfoHolder sp = new SPInfoHolder();
sp.setResponseDestinationURI(assertionConsumerURL);
responseType = saml2Response.createResponseType(id, sp, idp, issuerHolder);
//Add information on the roles
AssertionType assertion = (AssertionType) responseType.getAssertionOrEncryptedAssertion().get(0);
AttributeStatementType attrStatement = saml2Response.createAttributeStatement(roles);
assertion.getStatementOrAuthnStatementOrAuthzDecisionStatement().add(attrStatement);
//Add timed conditions
saml2Response.createTimedConditions(assertion, assertionValidity);
//Lets see how the response looks like
if(log.isTraceEnabled())
{
StringWriter sw = new StringWriter();
try
{
saml2Response.marshall(responseType, sw);
}
catch (JAXBException e)
{
log.trace(e);
}
catch (SAXException e)
{
log.trace(e);
}
log.trace("Response="+sw.toString());
}
return responseType;
}
/**
* Verify that the issuer is trusted
* @param issuer
* @throws IssuerNotTrustedException
*/
public void isTrusted(String issuer) throws IssuerNotTrustedException
{
try
{
String issuerDomain = ValveUtil.getDomain(issuer);
TrustType idpTrust = idpConfiguration.getTrust();
if(idpTrust != null)
{
String domainsTrusted = idpTrust.getDomains();
log.trace("Domains that IDP trusts="+domainsTrusted + " and issuer domain="+issuerDomain);
if(domainsTrusted.indexOf(issuerDomain) < 0)
{
//Let us do string parts checking
StringTokenizer st = new StringTokenizer(domainsTrusted, ",");
while(st != null && st.hasMoreTokens())
{
String uriBit = st.nextToken();
log.trace("Matching uri bit="+ uriBit);
if(issuerDomain.indexOf(uriBit) > 0)
{
log.trace("Matched " + uriBit + " trust for " + issuerDomain );
return;
}
}
throw new IssuerNotTrustedException(issuer);
}
}
}
catch (Exception e)
{
throw new IssuerNotTrustedException(e.getLocalizedMessage(),e);
}
}
/**
* Send a response
* @param responseType
* @param relayState
* @param response
* @throws IOException
* @throws GeneralSecurityException
*/
public void send(ResponseType responseType, String relayState,
Response response,
boolean supportSignature,
PrivateKey signingKey) throws IOException, GeneralSecurityException
{
if(responseType == null)
throw new IllegalArgumentException("reponseType is null");
SAML2Response saml2Response = new SAML2Response();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
saml2Response.marshall(responseType, baos);
}
catch (SAXException e1)
{
log.trace("Parsing Exception in sending response:",e1);
throw new ParsingException("Parsing Exception in sending response:" , e1);
}
catch (JAXBException e1)
{
log.trace("Parsing Exception in sending response:",e1);
throw new ParsingException("Parsing Exception in sending response:" ,e1);
}
if(redirectProfile)
{
String urlEncodedResponse = RedirectBindingUtil.deflateBase64URLEncode(baos.toByteArray());
String destination = responseType.getDestination();
log.trace("IDP:Destination=" + destination);
if(relayState != null && relayState.length() > 0)
relayState = RedirectBindingUtil.urlEncode(relayState);
String finalDest = destination + getDestination(urlEncodedResponse, relayState);
HTTPRedirectUtil.sendRedirectForResponder(finalDest, response);
}
else
{
/**
* Since the container finished authentication, it will try to locate
* index.jsp or index.html. We need to recycle whatever is in the
* response object such that we direct it to the html that is being
* created as part of the HTTP/POST binding
*/
response.recycle();
String samlResponse = PostBindingUtil.base64Encode(baos.toString());
SignatureInfoHolder signatureHolder = null;
if(supportSignature)
{
//SigAlg
String algo = signingKey.getAlgorithm();
String sigAlg = SignatureUtil.getXMLSignatureAlgorithmURI(algo);
sigAlg = URLEncoder.encode(sigAlg, "UTF-8");
byte[] signedValue = SignatureUtil.sign(samlResponse, signingKey);
signatureHolder = new SignatureInfoHolder(signedValue,sigAlg);
}
PostBindingUtil.sendPost(new DestinationInfoHolder(responseType.getDestination(),
samlResponse, relayState), signatureHolder, response, false);
}
}
/**
* Generate a Destination URL for the HTTPRedirect binding
* with the saml response and relay state
* @param urlEncodedResponse
* @param urlEncodedRelayState
* @return
*/
public String getDestination(String urlEncodedResponse, String urlEncodedRelayState)
{
if(redirectProfile)
{
StringBuilder sb = new StringBuilder();
sb.append("?SAMLResponse=").append(urlEncodedResponse);
if(urlEncodedRelayState != null && urlEncodedRelayState.length() > 0)
sb.append("&RelayState=").append(urlEncodedRelayState);
return sb.toString();
}
return null;
}
/**
* Create an Error Response
* @param responseURL
* @param status
* @param identityURL
* @return
* @throws ConfigurationException
*/
public ResponseType getErrorResponse(String responseURL, String status,
String identityURL)
{
ResponseType responseType = null;
SAML2Response saml2Response = new SAML2Response();
//Create a response type
String id = IDGenerator.create("ID_");
IssuerInfoHolder issuerHolder = new IssuerInfoHolder(identityURL);
issuerHolder.setStatusCode(status);
IDPInfoHolder idp = new IDPInfoHolder();
idp.setNameIDFormatValue(null);
idp.setNameIDFormat(JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get());
SPInfoHolder sp = new SPInfoHolder();
sp.setResponseDestinationURI(responseURL);
try
{
responseType = saml2Response.createResponseType(id, sp, idp, issuerHolder);
}
catch (ConfigurationException e1)
{
log.trace(e1);
responseType = saml2Response.createResponseType();
}
log.debug("ResponseType = ");
//Lets see how the response looks like
if(log.isTraceEnabled())
{
StringWriter sw = new StringWriter();
try
{
saml2Response.marshall(responseType, sw);
}
catch (JAXBException e)
{
log.trace(e);
}
catch (SAXException e)
{
log.trace(e);
}
log.trace("Response="+sw.toString());
}
return responseType;
}
}