Package org.jboss.identity.federation.bindings.tomcat.idp

Source Code of org.jboss.identity.federation.bindings.tomcat.idp.IDPWebBrowserSSOValve

/*
* 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.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.Principal;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.Context;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Session;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.LifecycleSupport;
import org.apache.catalina.valves.ValveBase;
import org.apache.log4j.Logger;
import org.jboss.identity.federation.bindings.tomcat.TomcatRoleGenerator;
import org.jboss.identity.federation.core.config.IDPType;
import org.jboss.identity.federation.core.config.KeyProviderType;
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.exceptions.ParsingException;
import org.jboss.identity.federation.core.impl.DelegatedAttributeManager;
import org.jboss.identity.federation.core.interfaces.AttributeManager;
import org.jboss.identity.federation.core.interfaces.TrustKeyConfigurationException;
import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
import org.jboss.identity.federation.core.interfaces.TrustKeyProcessingException;
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.saml.v2.protocol.AuthnRequestType;
import org.jboss.identity.federation.saml.v2.protocol.RequestAbstractType;
import org.jboss.identity.federation.web.interfaces.RoleGenerator;
import org.jboss.identity.federation.web.util.ConfigurationUtil;
import org.jboss.identity.federation.web.util.IDPWebRequestUtil;
import org.jboss.identity.federation.web.util.RedirectBindingSignatureUtil;
import org.w3c.dom.Document;

/**
* Generic Web Browser SSO valve for the IDP
*
* Handles both the SAML Redirect as well as Post Bindings
*
* Note: Most of the work is done by {@code IDPWebRequestUtil}
* @author Anil.Saldhana@redhat.com
* @since May 18, 2009
*/
public class IDPWebBrowserSSOValve extends ValveBase implements Lifecycle
{
   private static Logger log =  Logger.getLogger(IDPWebBrowserSSOValve.class);
   private boolean trace = log.isTraceEnabled();
  
   protected IDPType idpConfiguration = null;
  
   private RoleGenerator rg = new TomcatRoleGenerator();

   private long assertionValidity = 5000; // 5 seconds in miliseconds
  
   private String identityURL = null;
  
   private TrustKeyManager keyManager;
  
   private Boolean ignoreIncomingSignatures = true;

   private Boolean signOutgoingMessages = true;

   private transient DelegatedAttributeManager attribManager = new DelegatedAttributeManager();
   private List<String> attributeKeys = new ArrayList<String>();
  
   //Set a list of attributes we are interested in separated by comma
   public void setAttributeList(String attribList)
   {
      if(attribList != null && !"".equals(attribList))
      {
         this.attributeKeys.clear();
         StringTokenizer st = new StringTokenizer(attribList,",");
         while(st != null && st.hasMoreTokens())
         {
            this.attributeKeys.add(st.nextToken());
         }
      }
   }
  
   public Boolean getIgnoreIncomingSignatures()
   {
      return ignoreIncomingSignatures;
   }

   public void setIgnoreIncomingSignatures(Boolean ignoreIncomingSignature)
   {
      this.ignoreIncomingSignatures = ignoreIncomingSignature;
   }

   public Boolean getSignOutgoingMessages()
   {
      return signOutgoingMessages;
   }

   public void setSignOutgoingMessages(Boolean signOutgoingMessages)
   {
      this.signOutgoingMessages = signOutgoingMessages;
   }
  
   public void setRoleGenerator(String rgName)
   {
      try
      {
         Class<?> clazz = SecurityActions.getContextClassLoader().loadClass(rgName);
         rg = (RoleGenerator) clazz.newInstance();
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }
  
   @Override
   public void invoke(Request request, Response response) throws IOException, ServletException
   {
      String referer = request.getHeader("Referer");
      String relayState = request.getParameter("RelayState");
      String samlMessage = request.getParameter("SAMLRequest");
      String signature = request.getParameter("Signature");
      String sigAlg = request.getParameter("SigAlg");
     
      boolean containsSAMLRequestMessage =  samlMessage != null;
     
      Session session = request.getSessionInternal();
     
      if(containsSAMLRequestMessage)
      {
         if(trace) log.trace("Storing the SAMLRequest and RelayState in session");
         session.setNote("SAMLRequest", samlMessage);
         if(relayState != null && relayState.length() > 0)
            session.setNote("RelayState", relayState.trim());
         if(signature != null && signature.length() > 0)
            session.setNote("Signature", signature.trim());
         if(sigAlg != null && sigAlg.length() > 0)
            session.setNote("sigAlg", sigAlg.trim());
      }
     
      //Lets check if the user has been authenticated
      Principal userPrincipal = request.getPrincipal();
      if(userPrincipal == null)
      {
         try
         {
            //Next in the invocation chain
            getNext().invoke(request, response)
         }
         finally
         {
            userPrincipal = request.getPrincipal();
            referer = request.getHeader("Referer");
            if(trace)
               log.trace("Referer in finally block="+ referer + ":user principal=" + userPrincipal);
         }
      }
     
     
      IDPWebRequestUtil webRequestUtil = new IDPWebRequestUtil(request, idpConfiguration, keyManager);
      webRequestUtil.setAttributeManager(this.attribManager);
      webRequestUtil.setAttributeKeys(attributeKeys);
     
      Document samlErrorResponse = null;
      //Look for unauthorized status
      if(response.getStatus() == HttpServletResponse.SC_FORBIDDEN)
      {
         try
         {
            samlErrorResponse =
              webRequestUtil.getErrorResponse(referer,
                  JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                  this.identityURL, this.signOutgoingMessages);
        
            if(this.signOutgoingMessages)
               webRequestUtil.send(samlErrorResponse, referer, relayState, response, true,
                     this.keyManager.getSigningKey());
            else
               webRequestUtil.send(samlErrorResponse, referer,relayState, response, false,null);
           
         }
         catch (GeneralSecurityException e)
         {
            throw new ServletException(e);
        
         return;
     
     
      if(userPrincipal != null)
      {
         /**
          * Since the container has finished the authentication,
          * we can retrieve the original saml message as well as
          * any relay state from the SP
          */
         samlMessage = (String) session.getNote("SAMLRequest");
         relayState = (String) session.getNote("RelayState");
         signature = (String) session.getNote("Signature");
         sigAlg = (String) session.getNote("sigAlg");
        
         if(trace)
         {
            log.trace("Retrieved saml message and relay state from session");
            log.trace("saml message=" + samlMessage + "::relay state="+ relayState);
            log.trace("Signature=" + signature + "::sigAlg="+ sigAlg);
         }
        
         session.removeNote("SAMLRequest");
        
         if(relayState != null && relayState.length() > 0)
            session.removeNote("RelayState");
        
         if(signature != null && signature.length() > 0)
            session.removeNote("Signature");
         if(sigAlg != null && sigAlg.length() > 0)
            session.removeNote("sigAlg");
        
         //Send valid saml response after processing the request
         if(samlMessage != null)
         {
            //Get the SAML Request Message
            RequestAbstractType requestAbstractType =  null;
            Document samlResponse = null;
            String destination = null;
               try
               {
                  requestAbstractType = webRequestUtil.getSAMLRequest(samlMessage);
                  boolean isPost = webRequestUtil.hasSAMLRequestInPostProfile();
                  boolean isValid = validate(request.getRemoteAddr(),
                        request.getQueryString(),
                        new SessionHolder(samlMessage, signature, sigAlg), isPost);
                  if(!isValid)
                     throw new GeneralSecurityException("Validation check failed");
                 
                  webRequestUtil.isTrusted(requestAbstractType.getIssuer().getValue());

                  List<String> roles = rg.generateRoles(userPrincipal);
                 
                  log.trace("Roles have been determined:Creating response");

                  AuthnRequestType art = (AuthnRequestType) requestAbstractType;
                  destination = art.getAssertionConsumerServiceURL();
                 
                  samlResponse =
                     webRequestUtil.getResponse(destination,
                           userPrincipal, roles,
                           this.identityURL, this.assertionValidity, this.signOutgoingMessages);
               }
               catch (IssuerNotTrustedException e)
               {
                  if(trace) log.trace(e);
                  
                  samlResponse =
                        webRequestUtil.getErrorResponse(referer,
                            JBossSAMLURIConstants.STATUS_REQUEST_DENIED.get(),
                            this.identityURL, this.signOutgoingMessages)
               }
               catch (ParsingException e)
               {
                  if(trace) log.trace(e);
                  
                  samlResponse =
                     webRequestUtil.getErrorResponse(referer,
                         JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                         this.identityURL, this.signOutgoingMessages);
               }
               catch (ConfigurationException e)
               {
                  if(trace) log.trace(e);
                  
                  samlResponse =
                     webRequestUtil.getErrorResponse(referer,
                         JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                         this.identityURL, this.signOutgoingMessages);
               }
               catch (IssueInstantMissingException e)
               {
                  if(trace) log.trace(e);
                 
                  samlResponse =
                     webRequestUtil.getErrorResponse(referer,
                         JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                         this.identityURL, this.signOutgoingMessages);
               }
               catch(GeneralSecurityException e)
               {
                  if(trace) log.trace(e);
                 
                  samlResponse =
                     webRequestUtil.getErrorResponse(referer,
                         JBossSAMLURIConstants.STATUS_AUTHNFAILED.get(),
                         this.identityURL, this.signOutgoingMessages);
               }
               finally
               {
                  try
                  {
                     if(webRequestUtil.hasSAMLRequestInPostProfile())
                        recycle(response);
                    
                     if(this.signOutgoingMessages)
                        webRequestUtil.send(samlResponse, destination,relayState, response, true,
                              this.keyManager.getSigningKey());
                     else
                        webRequestUtil.send(samlResponse, destination, relayState, response, false,null);
                  }
                  catch (ParsingException e)
                  {
                     if(trace) log.trace(e);
                  }
                  catch (GeneralSecurityException e)
                  {
                     if(trace) log.trace(e);
                  }
               }
            return;
         }
         else
         {
            log.error("No SAML Request Message");
            if(trace) log.trace("Referer="+referer);
           
            try
            {
               sendErrorResponseToSP(referer, response, relayState, webRequestUtil);
            }
            catch (ConfigurationException e)
            {
               if(trace) log.trace(e);
            }
         }
      }
   }
  
   protected void sendErrorResponseToSP(String referrer, Response response, String relayState,
         IDPWebRequestUtil webRequestUtil) throws ServletException, IOException, ConfigurationException
   {
      if(trace) log.trace("About to send error response to SP:" + referrer);
     
      Document samlResponse =  
         webRequestUtil.getErrorResponse(referrer, JBossSAMLURIConstants.STATUS_RESPONDER.get(),
               this.identityURL, this.signOutgoingMessages);
      try
      {
         if(webRequestUtil.hasSAMLRequestInPostProfile())
            recycle(response);
        
         if(this.signOutgoingMessages)
            webRequestUtil.send(samlResponse, referrer, relayState, response, true,
                  this.keyManager.getSigningKey());
         else
            webRequestUtil.send(samlResponse, referrer, relayState, response, false,null);
      }
      catch (ParsingException e1)
      {
         throw new ServletException(e1);
      }
      catch (GeneralSecurityException e)
      {
         throw new ServletException(e);
      }
   }
  
   protected boolean validate(String remoteAddress,
         String queryString,
         SessionHolder holder, boolean isPost) throws IOException, GeneralSecurityException
   {  
      if (holder.samlRequest == null || holder.samlRequest.length() == 0)
      {
         return false;
      }

      if (!this.ignoreIncomingSignatures && !isPost)
      {
         String sig = holder.signature;
         if (sig == null || sig.length() == 0)
         {
            log.error("Signature received from SP is null:" + remoteAddress);
            return false;
         }
        
         //Check if there is a signature  
         byte[] sigValue = RedirectBindingSignatureUtil.getSignatureValueFromSignedURL(queryString);
         if(sigValue == null)
            return false;
        
         PublicKey validatingKey;
         try
         {
            validatingKey = keyManager.getValidatingKey(remoteAddress);
         }
         catch (TrustKeyConfigurationException e)
         {
            throw new GeneralSecurityException(e.getCause());
         }
         catch (TrustKeyProcessingException e)
         {
            throw new GeneralSecurityException(e.getCause());
         }
        
         return RedirectBindingSignatureUtil.validateSignature(queryString, validatingKey, sigValue);
      }
      else
      {
         //Post binding no signature verification. The SAML message signature is verified
         return true;
      }
   }
  
   //***************Lifecycle
   /**
    * The lifecycle event support for this component.
    */
   protected LifecycleSupport lifecycle = new LifecycleSupport(this);

   /**
    * Has this component been started yet?
    */
   private boolean started = false;

   /**
    * Add a lifecycle event listener to this component.
    *
    * @param listener The listener to add
    */
   public void addLifecycleListener(LifecycleListener listener)
   {
       lifecycle.addLifecycleListener(listener);
   }


   /**
    * Get the lifecycle listeners associated with this lifecycle. If this
    * Lifecycle has no listeners registered, a zero-length array is returned.
    */
   public LifecycleListener[] findLifecycleListeners()
   {
       return lifecycle.findLifecycleListeners();
   }


   /**
    * Remove a lifecycle event listener from this component.
    *
    * @param listener The listener to add
    */
   public void removeLifecycleListener(LifecycleListener listener)
   {
       lifecycle.removeLifecycleListener(listener);
   }


   /**
    * Prepare for the beginning of active use of the public methods of this
    * component.  This method should be called after <code>configure()</code>,
    * and before any of the public methods of the component are utilized.
    *
    * @exception LifecycleException if this component detects a fatal error
    *  that prevents this component from being used
    */
   public void start() throws LifecycleException
   {
       // Validate and update our current component state
       if (started)
           throw new LifecycleException
               ("IDPRedirectValve already Started");
       lifecycle.fireLifecycleEvent(START_EVENT, null);
       started = true;
      
       String configFile = "/WEB-INF/jboss-idfed.xml";
       Context context = (Context) getContainer();
       InputStream is = context.getServletContext().getResourceAsStream(configFile);
       if(is == null)
          throw new RuntimeException(configFile + " missing");
       try
       {
          idpConfiguration = ConfigurationUtil.getIDPConfiguration(is);
          this.identityURL = idpConfiguration.getIdentityURL();
          if(trace) log.trace("Identity Provider URL=" + this.identityURL);
          this.assertionValidity = idpConfiguration.getAssertionValidity();
          //Get the attribute manager
          String attributeManager = idpConfiguration.getAttributeManager();
          if(attributeManager != null && !"".equals(attributeManager))
          {
             ClassLoader tcl = SecurityActions.getContextClassLoader();
             AttributeManager delegate = (AttributeManager) tcl.loadClass(attributeManager).newInstance();
             this.attribManager.setDelegate(delegate);
          }
       }
       catch (Exception e)
       {
          throw new RuntimeException(e);
       }
      
       if(this.signOutgoingMessages)
       {
          KeyProviderType keyProvider = this.idpConfiguration.getKeyProvider();
          if(keyProvider == null)
             throw new LifecycleException("Key Provider is null for context=" + context.getName());
         
          try
          {
             ClassLoader tcl = SecurityActions.getContextClassLoader();
             String keyManagerClassName = keyProvider.getClassName();
             if(keyManagerClassName == null)
                throw new RuntimeException("KeyManager class name is null");
            
             Class<?> clazz = tcl.loadClass(keyManagerClassName);
             this.keyManager = (TrustKeyManager) clazz.newInstance();
             keyManager.setAuthProperties(keyProvider.getAuth());
             keyManager.setValidatingAlias(keyProvider.getValidatingAlias());
          }
          catch(Exception e)
          {
             log.error("Exception reading configuration:",e);
             throw new LifecycleException(e.getLocalizedMessage());
          }
          if(trace) log.trace("Key Provider=" + keyProvider.getClassName());
       }
      
       //Add some keys to the attibutes
       String[] ak = new String[] {"mail","cn","commonname","givenname",
             "surname","employeeType",
             "employeeNumber",
             "facsimileTelephoneNumber"};
      
       this.attributeKeys.addAll(Arrays.asList(ak));
   }


   /**
    * Gracefully terminate the active use of the public methods of this
    * component.  This method should be the last one called on a given
    * instance of this component.
    *
    * @exception LifecycleException if this component detects a fatal error
    *  that needs to be reported
    */
   public void stop() throws LifecycleException
   {
       // Validate and update our current component state
       if (!started)
           throw new LifecycleException
               ("IDPRedirectValve NotStarted");
       lifecycle.fireLifecycleEvent(STOP_EVENT, null);
       started = false;
   }
   //Private Methods
  
   protected static class SessionHolder
   {
      String samlRequest;
      String signature;
      String sigAlg;
     
      public SessionHolder(String req, String sig, String alg)
      {
         this.samlRequest = req;
         this.signature = sig;
         this.sigAlg = alg;
      }
   }
  
   private void recycle(Response response)
   {
      /**
       * 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();
   }
}
TOP

Related Classes of org.jboss.identity.federation.bindings.tomcat.idp.IDPWebBrowserSSOValve

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.