opensaml-2.4.1

16:39:22.014 INFO  jd.cli.Main - Decompiling opensaml-2.4.1.jar
package org.opensaml;

import org.apache.velocity.app.Velocity;
import org.apache.xml.security.Init;
import org.opensaml.saml1.binding.artifact.SAML1ArtifactBuilderFactory;
import org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilderFactory;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.XMLConfigurator;
import org.opensaml.xml.parse.StaticBasicParserPool;
import org.opensaml.xml.parse.XMLParserException;
import org.opensaml.xml.security.DefaultSecurityConfigurationBootstrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultBootstrap
{
  private static String[] xmlToolingConfigs = { "/default-config.xml", "/schema-config.xml", "/signature-config.xml", "/signature-validation-config.xml", "/encryption-config.xml", "/encryption-validation-config.xml", "/soap11-config.xml", "/wsfed11-protocol-config.xml", "/saml1-assertion-config.xml", "/saml1-protocol-config.xml", "/saml1-core-validation-config.xml", "/saml2-assertion-config.xml", "/saml2-protocol-config.xml", "/saml2-core-validation-config.xml", "/saml1-metadata-config.xml", "/saml2-metadata-config.xml", "/saml2-metadata-validation-config.xml", "/saml2-metadata-idp-discovery-config.xml", "/saml2-protocol-thirdparty-config.xml", "/saml2-metadata-query-config.xml", "/saml2-assertion-delegation-restriction-config.xml", "/saml2-ecp-config.xml", "/xacml10-saml2-profile-config.xml", "/xacml11-saml2-profile-config.xml", "/xacml20-context-config.xml", "/xacml20-policy-config.xml", "/xacml2-saml2-profile-config.xml", "/xacml3-saml2-profile-config.xml", "/wsaddressing-config.xml", "/wssecurity-config.xml" };
  
  public static synchronized void bootstrap()
    throws ConfigurationException
  {
    initializeXMLSecurity();
    
    initializeVelocity();
    
    initializeXMLTooling(xmlToolingConfigs);
    
    initializeArtifactBuilderFactories();
    
    initializeGlobalSecurityConfiguration();
    
    initializeParserPool();
  }
  
  protected static void initializeParserPool()
    throws ConfigurationException
  {
    StaticBasicParserPool pp = new StaticBasicParserPool();
    pp.setMaxPoolSize(50);
    try
    {
      pp.initialize();
    }
    catch (XMLParserException e)
    {
      throw new ConfigurationException("Error initializing parser pool", e);
    }
    Configuration.setParserPool(pp);
  }
  
  protected static void initializeGlobalSecurityConfiguration()
  {
    Configuration.setGlobalSecurityConfiguration(DefaultSecurityConfigurationBootstrap.buildDefaultConfig());
  }
  
  protected static void initializeXMLSecurity()
    throws ConfigurationException
  {
    Logger log = getLogger();
    String lineBreakPropName = "org.apache.xml.security.ignoreLineBreaks";
    if (System.getProperty(lineBreakPropName) == null) {
      System.setProperty(lineBreakPropName, "true");
    }
    if (!Init.isInitialized())
    {
      log.debug("Initializing Apache XMLSecurity library");
      Init.init();
    }
  }
  
  protected static void initializeVelocity()
    throws ConfigurationException
  {
    Logger log = getLogger();
    try
    {
      log.debug("Initializing Velocity template engine");
      Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogChute");
      
      Velocity.setProperty("ISO-8859-1", "UTF-8");
      Velocity.setProperty("output.encoding", "UTF-8");
      Velocity.setProperty("resource.loader", "classpath");
      Velocity.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
      
      Velocity.init();
    }
    catch (Exception e)
    {
      throw new ConfigurationException("Unable to initialize Velocity template engine", e);
    }
  }
  
  protected static void initializeXMLTooling(String[] providerConfigs)
    throws ConfigurationException
  {
    Logger log = getLogger();
    Class clazz = Configuration.class;
    XMLConfigurator configurator = new XMLConfigurator();
    for (String config : providerConfigs)
    {
      log.debug("Loading XMLTooling configuration {}", config);
      configurator.load(clazz.getResourceAsStream(config));
    }
  }
  
  protected static void initializeArtifactBuilderFactories()
    throws ConfigurationException
  {
    Logger log = getLogger();
    log.debug("Initializing SAML Artifact builder factories");
    Configuration.setSAML1ArtifactBuilderFactory(new SAML1ArtifactBuilderFactory());
    Configuration.setSAML2ArtifactBuilderFactory(new SAML2ArtifactBuilderFactory());
  }
  
  protected static Logger getLogger()
  {
    return LoggerFactory.getLogger(DefaultBootstrap.class);
  }
}

/* Location:
 * Qualified Name:     org.opensaml.DefaultBootstrap
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml;

import org.joda.time.chrono.ISOChronology;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.opensaml.saml1.binding.artifact.SAML1ArtifactBuilderFactory;
import org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilderFactory;

public class Configuration
  extends org.opensaml.xml.Configuration
{
  private static String defaultDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
  private static DateTimeFormatter dateFormatter;
  private static SAML1ArtifactBuilderFactory saml1ArtifactBuilderFactory;
  private static SAML2ArtifactBuilderFactory saml2ArtifactBuilderFactory;
  
  public static DateTimeFormatter getSAMLDateFormatter()
  {
    if (dateFormatter == null)
    {
      DateTimeFormatter formatter = DateTimeFormat.forPattern(defaultDateFormat);
      dateFormatter = formatter.withChronology(ISOChronology.getInstanceUTC());
    }
    return dateFormatter;
  }
  
  public static void setSAMLDateFormat(String format)
  {
    DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
    dateFormatter = formatter.withChronology(ISOChronology.getInstanceUTC());
  }
  
  public static SAML1ArtifactBuilderFactory getSAML1ArtifactBuilderFactory()
  {
    return saml1ArtifactBuilderFactory;
  }
  
  public static void setSAML1ArtifactBuilderFactory(SAML1ArtifactBuilderFactory factory)
  {
    saml1ArtifactBuilderFactory = factory;
  }
  
  public static SAML2ArtifactBuilderFactory getSAML2ArtifactBuilderFactory()
  {
    return saml2ArtifactBuilderFactory;
  }
  
  public static void setSAML2ArtifactBuilderFactory(SAML2ArtifactBuilderFactory factory)
  {
    saml2ArtifactBuilderFactory = factory;
  }
}

/* Location:
 * Qualified Name:     org.opensaml.Configuration
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.opensaml.common.binding.BasicEndpointSelector;
import org.opensaml.saml2.core.AuthnRequest;
import org.opensaml.saml2.metadata.Endpoint;
import org.opensaml.saml2.metadata.EntityDescriptor;
import org.opensaml.saml2.metadata.IndexedEndpoint;
import org.opensaml.saml2.metadata.RoleDescriptor;
import org.opensaml.xml.util.DatatypeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AuthnResponseEndpointSelector
  extends BasicEndpointSelector
{
  private final Logger log = LoggerFactory.getLogger(AuthnResponseEndpointSelector.class);
  
  public Endpoint selectEndpoint()
  {
    if (getEntityRoleMetadata() == null)
    {
      log.debug("Unable to select endpoint, no entity role metadata available.");
      return null;
    }
    List<? extends Endpoint> endpoints = getEntityRoleMetadata().getEndpoints(getEndpointType());
    if ((endpoints == null) || (endpoints.size() == 0)) {
      return null;
    }
    Endpoint endpoint = null;
    AuthnRequest request = (AuthnRequest)getSamlRequest();
    if (request != null)
    {
      endpoints = filterEndpointsByProtocolBinding(endpoints);
      if ((endpoints == null) || (endpoints.isEmpty())) {
        return null;
      }
      if (request.getAssertionConsumerServiceIndex() != null)
      {
        log.debug("Selecting endpoint by ACS index '{}' for request '{}' from entity '{}'", new Object[] { request.getAssertionConsumerServiceIndex(), request.getID(), getEntityMetadata().getEntityID() });
        
        endpoint = selectEndpointByACSIndex(request, endpoints);
      }
      else if (request.getAssertionConsumerServiceURL() != null)
      {
        log.debug("Selecting endpoint by ACS URL '{}' and protocol binding '{}' for request '{}' from entity '{}'", new Object[] { request.getAssertionConsumerServiceURL(), request.getProtocolBinding(), request.getID(), getEntityMetadata().getEntityID() });
        
        endpoint = selectEndpointByACSURL(request, endpoints);
      }
    }
    if ((endpoint == null) && (request.getAssertionConsumerServiceIndex() == null) && (request.getAssertionConsumerServiceURL() == null))
    {
      log.debug("No ACS index or URL given, selecting endpoint without additional constraints.");
      if ((endpoints.get(0) instanceof IndexedEndpoint)) {
        endpoint = selectIndexedEndpoint(endpoints);
      } else {
        endpoint = selectNonIndexedEndpoint(endpoints);
      }
    }
    return endpoint;
  }
  
  protected List<? extends Endpoint> filterEndpointsByProtocolBinding(List<? extends Endpoint> endpoints)
  {
    log.debug("Filtering peer endpoints.  Supported peer endpoint bindings: {}", getSupportedIssuerBindings());
    AuthnRequest request = (AuthnRequest)getSamlRequest();
    
    boolean filterByRequestBinding = false;
    String acsBinding = DatatypeHelper.safeTrimOrNullString(request.getProtocolBinding());
    if ((acsBinding != null) && (request.getAssertionConsumerServiceIndex() != null)) {
      filterByRequestBinding = true;
    }
    List<Endpoint> filteredEndpoints = new ArrayList(endpoints);
    Iterator<Endpoint> endpointItr = filteredEndpoints.iterator();
    while (endpointItr.hasNext())
    {
      Endpoint endpoint = (Endpoint)endpointItr.next();
      if (!getSupportedIssuerBindings().contains(endpoint.getBinding()))
      {
        log.debug("Removing endpoint {} because its binding {} is not supported", endpoint.getLocation(), endpoint.getBinding());
        
        endpointItr.remove();
      }
      else if ((filterByRequestBinding) && (!endpoint.getBinding().equals(acsBinding)))
      {
        log.debug("Removing endpoint {} because its binding {} does not match request's requested binding", endpoint.getLocation(), endpoint.getBinding());
        
        endpointItr.remove();
      }
    }
    return filteredEndpoints;
  }
  
  protected Endpoint selectEndpointByACSIndex(AuthnRequest request, List<IndexedEndpoint> endpoints)
  {
    Integer acsIndex = request.getAssertionConsumerServiceIndex();
    for (IndexedEndpoint endpoint : endpoints) {
      if ((endpoint == null) || (!getSupportedIssuerBindings().contains(endpoint.getBinding())))
      {
        log.debug("Endpoint '{}' with binding '{}' discarded because it requires an unsupported outbound binding.", endpoint.getLocation(), endpoint.getBinding());
      }
      else
      {
        if (DatatypeHelper.safeEquals(acsIndex, endpoint.getIndex())) {
          return endpoint;
        }
        log.debug("Endpoint '{}' with index '{}' discard because it does have the required index '{}'", new Object[] { endpoint.getLocation(), endpoint.getIndex(), acsIndex });
      }
    }
    log.warn("Relying party '{}' requested the response to be returned to endpoint with ACS index '{}' however no endpoint, with that index and using a supported binding, can be found  in the relying party's metadata ", getEntityMetadata().getEntityID(), acsIndex);
    
    return null;
  }
  
  protected Endpoint selectEndpointByACSURL(AuthnRequest request, List<IndexedEndpoint> endpoints)
  {
    String acsBinding = DatatypeHelper.safeTrimOrNullString(request.getProtocolBinding());
    for (IndexedEndpoint endpoint : endpoints) {
      if (!getSupportedIssuerBindings().contains(endpoint.getBinding()))
      {
        log.debug("Endpoint '{}' with binding '{}' discarded because that is not a supported outbound binding.", endpoint.getLocation(), endpoint.getBinding());
      }
      else if ((acsBinding != null) && 
        (!DatatypeHelper.safeEquals(acsBinding, endpoint.getBinding())))
      {
        log.debug("Endpoint '{}' with binding '{}' discarded because it does not meet protocol binding selection criteria", endpoint.getLocation(), endpoint.getBinding());
      }
      else
      {
        if ((DatatypeHelper.safeEquals(endpoint.getLocation(), request.getAssertionConsumerServiceURL())) || (DatatypeHelper.safeEquals(endpoint.getResponseLocation(), request.getAssertionConsumerServiceURL()))) {
          return endpoint;
        }
        log.debug("Endpoint '{}' discarded because neither its Location nor ResponseLocation match ACS URL '{}'", endpoint.getLocation(), request.getAssertionConsumerServiceURL());
      }
    }
    log.warn("Relying party '{}' requested the response to be returned to endpoint with ACS URL '{}'  and binding '{}' however no endpoint, with that URL and using a supported binding,  can be found in the relying party's metadata ", new Object[] { getEntityMetadata().getEntityID(), request.getAssertionConsumerServiceURL(), acsBinding == null ? "any" : acsBinding });
    
    return null;
  }
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.AuthnResponseEndpointSelector
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding.artifact;

import org.opensaml.common.SAMLObject;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.saml2.core.NameID;

public abstract interface SAML2ArtifactBuilder<ArtifactType extends AbstractSAML2Artifact>
{
  public abstract ArtifactType buildArtifact(SAMLMessageContext<SAMLObject, SAMLObject, NameID> paramSAMLMessageContext);
  
  public abstract ArtifactType buildArtifact(byte[] paramArrayOfByte);
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilder
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding.artifact;

import java.util.Map;
import org.opensaml.xml.util.Base64;
import org.opensaml.xml.util.LazyMap;

public class SAML2ArtifactBuilderFactory
{
  private Map<String, SAML2ArtifactBuilder> artifactBuilders;
  
  public SAML2ArtifactBuilderFactory()
  {
    artifactBuilders = new LazyMap();
    artifactBuilders.put(new String(SAML2ArtifactType0004.TYPE_CODE), new SAML2ArtifactType0004Builder());
  }
  
  public Map<String, SAML2ArtifactBuilder> getArtifactBuilders()
  {
    return artifactBuilders;
  }
  
  public SAML2ArtifactBuilder getArtifactBuilder(byte[] type)
  {
    return (SAML2ArtifactBuilder)artifactBuilders.get(new String(type));
  }
  
  public AbstractSAML2Artifact buildArtifact(String base64Artifact)
  {
    return buildArtifact(Base64.decode(base64Artifact));
  }
  
  public AbstractSAML2Artifact buildArtifact(byte[] artifact)
  {
    if (artifact == null) {
      return null;
    }
    byte[] type = new byte[2];
    type[0] = artifact[0];
    type[1] = artifact[1];
    
    SAML2ArtifactBuilder<?> artifactBuilder = getArtifactBuilder(type);
    return artifactBuilder.buildArtifact(artifact);
  }
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilderFactory
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding.artifact;

import org.opensaml.common.binding.artifact.AbstractSAMLArtifact;

public abstract class AbstractSAML2Artifact
  extends AbstractSAMLArtifact
{
  private byte[] endpointIndex;
  
  protected AbstractSAML2Artifact(byte[] artifactType)
  {
    super(artifactType);
  }
  
  public AbstractSAML2Artifact(byte[] artifactType, byte[] index)
  {
    super(artifactType);
    setEndpointIndex(index);
  }
  
  public byte[] getArtifactBytes()
  {
    byte[] remainingArtifact = getRemainingArtifact();
    byte[] artifact = new byte[4 + remainingArtifact.length];
    
    System.arraycopy(getTypeCode(), 0, artifact, 0, 2);
    System.arraycopy(getEndpointIndex(), 0, artifact, 2, 2);
    System.arraycopy(remainingArtifact, 0, artifact, 4, remainingArtifact.length);
    
    return artifact;
  }
  
  public byte[] getEndpointIndex()
  {
    return endpointIndex;
  }
  
  public void setEndpointIndex(byte[] newIndex)
  {
    if (newIndex.length != 2) {
      throw new IllegalArgumentException("Artifact endpoint index must be two bytes long");
    }
    endpointIndex = newIndex;
  }
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.artifact.AbstractSAML2Artifact
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding.artifact;

import java.util.Arrays;

public class SAML2ArtifactType0004
  extends AbstractSAML2Artifact
{
  public static final byte[] TYPE_CODE = { 0, 4 };
  private byte[] sourceID;
  private byte[] messageHandle;
  
  public SAML2ArtifactType0004()
  {
    super(TYPE_CODE);
  }
  
  public SAML2ArtifactType0004(byte[] endpointIndex, byte[] source, byte[] handle)
  {
    super(TYPE_CODE, endpointIndex);
    setSourceID(source);
    setMessageHandle(handle);
  }
  
  public static SAML2ArtifactType0004 parseArtifact(byte[] artifact)
  {
    if (artifact.length != 44) {
      throw new IllegalArgumentException("Artifact length must be 44 bytes it was " + artifact.length + "bytes");
    }
    byte[] typeCode = { artifact[0], artifact[1] };
    if (!Arrays.equals(typeCode, TYPE_CODE)) {
      throw new IllegalArgumentException("Illegal artifact type code");
    }
    byte[] endpointIndex = { artifact[2], artifact[3] };
    
    byte[] sourceID = new byte[20];
    System.arraycopy(artifact, 4, sourceID, 0, 20);
    
    byte[] messageHandle = new byte[20];
    System.arraycopy(artifact, 24, messageHandle, 0, 20);
    
    return new SAML2ArtifactType0004(endpointIndex, sourceID, messageHandle);
  }
  
  public byte[] getSourceID()
  {
    return sourceID;
  }
  
  public void setSourceID(byte[] newSourceID)
  {
    if (newSourceID.length != 20) {
      throw new IllegalArgumentException("Artifact source ID must be 20 bytes long");
    }
    sourceID = newSourceID;
  }
  
  public byte[] getMessageHandle()
  {
    return messageHandle;
  }
  
  public void setMessageHandle(byte[] handle)
  {
    if (handle.length != 20) {
      throw new IllegalArgumentException("Artifact message handle must be 20 bytes long");
    }
    messageHandle = handle;
  }
  
  public byte[] getRemainingArtifact()
  {
    byte[] remainingArtifact = new byte[40];
    
    System.arraycopy(getSourceID(), 0, remainingArtifact, 0, 20);
    System.arraycopy(getMessageHandle(), 0, remainingArtifact, 20, 20);
    
    return remainingArtifact;
  }
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.artifact.SAML2ArtifactType0004
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding.artifact;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.binding.BasicEndpointSelector;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.saml2.core.NameID;
import org.opensaml.saml2.metadata.ArtifactResolutionService;
import org.opensaml.saml2.metadata.Endpoint;
import org.opensaml.saml2.metadata.IndexedEndpoint;
import org.opensaml.xml.util.DatatypeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SAML2ArtifactType0004Builder
  implements SAML2ArtifactBuilder<SAML2ArtifactType0004>
{
  private final Logger log = LoggerFactory.getLogger(SAML2ArtifactType0004Builder.class);
  
  public SAML2ArtifactType0004 buildArtifact(byte[] artifact)
  {
    return SAML2ArtifactType0004.parseArtifact(artifact);
  }
  
  public SAML2ArtifactType0004 buildArtifact(SAMLMessageContext<SAMLObject, SAMLObject, NameID> requestContext)
  {
    try
    {
      IndexedEndpoint acsEndpoint = (IndexedEndpoint)getAcsEndpoint(requestContext);
      if (acsEndpoint == null) {
        return null;
      }
      byte[] endpointIndex = DatatypeHelper.intToByteArray(acsEndpoint.getIndex().intValue());
      byte[] trimmedIndex = new byte[2];
      trimmedIndex[0] = endpointIndex[2];
      trimmedIndex[1] = endpointIndex[3];
      
      MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1");
      byte[] source = sha1Digester.digest(requestContext.getLocalEntityId().getBytes());
      
      SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
      
      byte[] assertionHandle = new byte[20];
      handleGenerator.nextBytes(assertionHandle);
      
      return new SAML2ArtifactType0004(trimmedIndex, source, assertionHandle);
    }
    catch (NoSuchAlgorithmException e)
    {
      log.error("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG.", e);
      throw new InternalError("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG.");
    }
  }
  
  protected Endpoint getAcsEndpoint(SAMLMessageContext<SAMLObject, SAMLObject, NameID> requestContext)
  {
    BasicEndpointSelector selector = new BasicEndpointSelector();
    selector.setEndpointType(ArtifactResolutionService.DEFAULT_ELEMENT_NAME);
    selector.getSupportedIssuerBindings().add("urn:oasis:names:tc:SAML:2.0:bindings:SOAP");
    selector.setMetadataProvider(requestContext.getMetadataProvider());
    selector.setEntityMetadata(requestContext.getLocalEntityMetadata());
    selector.setEntityRoleMetadata(requestContext.getLocalEntityRoleMetadata());
    
    Endpoint acsEndpoint = selector.selectEndpoint();
    if (acsEndpoint == null)
    {
      log.error("No artifact resolution service endpoint defined for the entity " + requestContext.getOutboundMessageIssuer());
      
      return null;
    }
    return acsEndpoint;
  }
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.artifact.SAML2ArtifactType0004Builder
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding;

import org.opensaml.common.SAMLObject;
import org.opensaml.common.binding.SAMLMessageContext;

public abstract interface SAML2ArtifactMessageContext<InboundMessageType extends SAMLObject, OutboundMessageType extends SAMLObject, NameIdentifierType extends SAMLObject>
  extends SAMLMessageContext<InboundMessageType, OutboundMessageType, NameIdentifierType>
{
  public abstract String getArtifact();
  
  public abstract void setArtifact(String paramString);
  
  public abstract SAMLObject getReferencedMessage();
  
  public abstract void setReferencedMessage(SAMLObject paramSAMLObject);
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.SAML2ArtifactMessageContext
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding.encoding;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.opensaml.Configuration;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.SignableSAMLObject;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.common.binding.encoding.SAMLMessageEncoder;
import org.opensaml.saml2.core.StatusResponseType;
import org.opensaml.saml2.metadata.Endpoint;
import org.opensaml.util.URLBuilder;
import org.opensaml.ws.message.encoder.BaseMessageEncoder;
import org.opensaml.ws.message.encoder.MessageEncodingException;
import org.opensaml.xml.XMLObjectBuilder;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.opensaml.xml.io.Marshaller;
import org.opensaml.xml.io.MarshallerFactory;
import org.opensaml.xml.io.MarshallingException;
import org.opensaml.xml.security.SecurityException;
import org.opensaml.xml.security.SecurityHelper;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureException;
import org.opensaml.xml.signature.Signer;
import org.opensaml.xml.util.DatatypeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class BaseSAML2MessageEncoder
  extends BaseMessageEncoder
  implements SAMLMessageEncoder
{
  private final Logger log = LoggerFactory.getLogger(BaseSAML2MessageEncoder.class);
  private List<String> allowedURLSchemes;
  
  public BaseSAML2MessageEncoder()
  {
    setAllowedURLSchemes(new String[] { "http", "https" });
  }
  
  public List<String> getAllowedURLSchemes()
  {
    return allowedURLSchemes;
  }
  
  public void setAllowedURLSchemes(String[] schemes)
  {
    if ((schemes == null) || (schemes.length == 0))
    {
      allowedURLSchemes = Collections.emptyList();
    }
    else
    {
      List<String> temp = new ArrayList();
      for (String scheme : schemes) {
        temp.add(scheme);
      }
      allowedURLSchemes = Collections.unmodifiableList(temp);
    }
  }
  
  protected URLBuilder getEndpointURL(SAMLMessageContext messageContext)
    throws MessageEncodingException
  {
    Endpoint endpoint = messageContext.getPeerEntityEndpoint();
    if (endpoint == null) {
      throw new MessageEncodingException("Endpoint for relying party was null.");
    }
    URLBuilder urlBuilder;
    URLBuilder urlBuilder;
    if (((messageContext.getOutboundMessage() instanceof StatusResponseType)) && (!DatatypeHelper.isEmpty(endpoint.getResponseLocation())))
    {
      urlBuilder = new URLBuilder(endpoint.getResponseLocation());
    }
    else
    {
      if (DatatypeHelper.isEmpty(endpoint.getLocation())) {
        throw new MessageEncodingException("Relying party endpoint location was null or empty.");
      }
      urlBuilder = new URLBuilder(endpoint.getLocation());
    }
    if (!getAllowedURLSchemes().contains(urlBuilder.getScheme())) {
      throw new MessageEncodingException("Relying party endpoint used the untrusted URL scheme " + urlBuilder.getScheme());
    }
    return urlBuilder;
  }
  
  protected boolean checkRelayState(String relayState)
  {
    if (!DatatypeHelper.isEmpty(relayState))
    {
      if (relayState.getBytes().length > 80) {
        log.warn("Relay state exceeds 80 bytes, some application may not support this.");
      }
      return true;
    }
    return false;
  }
  
  protected void setResponseDestination(SAMLObject outboundMessage, String endpointURL)
  {
    if ((outboundMessage instanceof StatusResponseType)) {
      ((StatusResponseType)outboundMessage).setDestination(endpointURL);
    }
  }
  
  protected void signMessage(SAMLMessageContext messageContext)
    throws MessageEncodingException
  {
    SAMLObject outboundSAML = messageContext.getOutboundSAMLMessage();
    Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential();
    if (((outboundSAML instanceof SignableSAMLObject)) && (signingCredential != null))
    {
      SignableSAMLObject signableMessage = (SignableSAMLObject)outboundSAML;
      
      XMLObjectBuilder<Signature> signatureBuilder = Configuration.getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
      
      Signature signature = (Signature)signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
      
      signature.setSigningCredential(signingCredential);
      try
      {
        SecurityHelper.prepareSignatureParams(signature, signingCredential, null, null);
      }
      catch (SecurityException e)
      {
        throw new MessageEncodingException("Error preparing signature for signing", e);
      }
      signableMessage.setSignature(signature);
      try
      {
        Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(signableMessage);
        if (marshaller == null) {
          throw new MessageEncodingException("No marshaller registered for " + signableMessage.getElementQName() + ", unable to marshall in preperation for signing");
        }
        marshaller.marshall(signableMessage);
        
        Signer.signObject(signature);
      }
      catch (MarshallingException e)
      {
        log.error("Unable to marshall protocol message in preparation for signing", e);
        throw new MessageEncodingException("Unable to marshall protocol message in preparation for signing", e);
      }
      catch (SignatureException e)
      {
        log.error("Unable to sign protocol message", e);
        throw new MessageEncodingException("Unable to sign protocol message", e);
      }
    }
  }
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.encoding.BaseSAML2MessageEncoder
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding.encoding;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.SignableSAMLObject;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.saml2.core.RequestAbstractType;
import org.opensaml.saml2.core.StatusResponseType;
import org.opensaml.util.URLBuilder;
import org.opensaml.ws.message.MessageContext;
import org.opensaml.ws.message.encoder.MessageEncodingException;
import org.opensaml.ws.transport.http.HTTPOutTransport;
import org.opensaml.ws.transport.http.HTTPTransportUtils;
import org.opensaml.xml.Configuration;
import org.opensaml.xml.security.SecurityConfiguration;
import org.opensaml.xml.security.SecurityException;
import org.opensaml.xml.security.SecurityHelper;
import org.opensaml.xml.security.SigningUtil;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.util.Base64;
import org.opensaml.xml.util.Pair;
import org.opensaml.xml.util.XMLHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HTTPRedirectDeflateEncoder
  extends BaseSAML2MessageEncoder
{
  private final Logger log = LoggerFactory.getLogger(HTTPRedirectDeflateEncoder.class);
  
  public String getBindingURI()
  {
    return "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
  }
  
  public boolean providesMessageConfidentiality(MessageContext messageContext)
    throws MessageEncodingException
  {
    return false;
  }
  
  public boolean providesMessageIntegrity(MessageContext messageContext)
    throws MessageEncodingException
  {
    return false;
  }
  
  protected void doEncode(MessageContext messageContext)
    throws MessageEncodingException
  {
    if (!(messageContext instanceof SAMLMessageContext))
    {
      log.error("Invalid message context type, this encoder only support SAMLMessageContext");
      throw new MessageEncodingException("Invalid message context type, this encoder only support SAMLMessageContext");
    }
    if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport))
    {
      log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport");
      throw new MessageEncodingException("Invalid outbound message transport type, this encoder only support HTTPOutTransport");
    }
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext)messageContext;
    
    String endpointURL = getEndpointURL(samlMsgCtx).buildURL();
    
    setResponseDestination(samlMsgCtx.getOutboundSAMLMessage(), endpointURL);
    
    removeSignature(samlMsgCtx);
    
    String encodedMessage = deflateAndBase64Encode(samlMsgCtx.getOutboundSAMLMessage());
    
    String redirectURL = buildRedirectURL(samlMsgCtx, endpointURL, encodedMessage);
    
    HTTPOutTransport out = (HTTPOutTransport)messageContext.getOutboundMessageTransport();
    HTTPTransportUtils.addNoCacheHeaders(out);
    HTTPTransportUtils.setUTF8Encoding(out);
    
    out.sendRedirect(redirectURL);
  }
  
  protected void removeSignature(SAMLMessageContext messageContext)
  {
    SignableSAMLObject message = (SignableSAMLObject)messageContext.getOutboundSAMLMessage();
    if (message.isSigned())
    {
      log.debug("Removing SAML protocol message signature");
      message.setSignature(null);
    }
  }
  
  protected String deflateAndBase64Encode(SAMLObject message)
    throws MessageEncodingException
  {
    log.debug("Deflating and Base64 encoding SAML message");
    try
    {
      String messageStr = XMLHelper.nodeToString(marshallMessage(message));
      
      ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
      Deflater deflater = new Deflater(8, true);
      DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
      deflaterStream.write(messageStr.getBytes("UTF-8"));
      deflaterStream.finish();
      
      return Base64.encodeBytes(bytesOut.toByteArray(), 8);
    }
    catch (IOException e)
    {
      throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e);
    }
  }
  
  protected String buildRedirectURL(SAMLMessageContext messagesContext, String endpointURL, String message)
    throws MessageEncodingException
  {
    log.debug("Building URL to redirect client to");
    URLBuilder urlBuilder = new URLBuilder(endpointURL);
    
    List<Pair<String, String>> queryParams = urlBuilder.getQueryParams();
    queryParams.clear();
    if ((messagesContext.getOutboundSAMLMessage() instanceof RequestAbstractType)) {
      queryParams.add(new Pair("SAMLRequest", message));
    } else if ((messagesContext.getOutboundSAMLMessage() instanceof StatusResponseType)) {
      queryParams.add(new Pair("SAMLResponse", message));
    } else {
      throw new MessageEncodingException("SAML message is neither a SAML RequestAbstractType or StatusResponseType");
    }
    String relayState = messagesContext.getRelayState();
    if (checkRelayState(relayState)) {
      queryParams.add(new Pair("RelayState", relayState));
    }
    Credential signingCredential = messagesContext.getOuboundSAMLMessageSigningCredential();
    if (signingCredential != null)
    {
      String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null);
      Pair<String, String> sigAlg = new Pair("SigAlg", sigAlgURI);
      queryParams.add(sigAlg);
      String sigMaterial = urlBuilder.buildQueryString();
      
      queryParams.add(new Pair("Signature", generateSignature(signingCredential, sigAlgURI, sigMaterial)));
    }
    return urlBuilder.buildURL();
  }
  
  protected String getSignatureAlgorithmURI(Credential credential, SecurityConfiguration config)
    throws MessageEncodingException
  {
    SecurityConfiguration secConfig;
    SecurityConfiguration secConfig;
    if (config != null) {
      secConfig = config;
    } else {
      secConfig = Configuration.getGlobalSecurityConfiguration();
    }
    String signAlgo = secConfig.getSignatureAlgorithmURI(credential);
    if (signAlgo == null) {
      throw new MessageEncodingException("The signing credential's algorithm URI could not be derived");
    }
    return signAlgo;
  }
  
  protected String generateSignature(Credential signingCredential, String algorithmURI, String queryString)
    throws MessageEncodingException
  {
    log.debug(String.format("Generating signature with key type '%s', algorithm URI '%s' over query string '%s'", new Object[] { SecurityHelper.extractSigningKey(signingCredential).getAlgorithm(), algorithmURI, queryString }));
    
    String b64Signature = null;
    try
    {
      byte[] rawSignature = SigningUtil.signWithURI(signingCredential, algorithmURI, queryString.getBytes("UTF-8"));
      
      b64Signature = Base64.encodeBytes(rawSignature, 8);
      log.debug("Generated digital signature value (base64-encoded) {}", b64Signature);
    }
    catch (SecurityException e)
    {
      log.error("Error during URL signing process", e);
      throw new MessageEncodingException("Unable to sign URL query string", e);
    }
    catch (UnsupportedEncodingException e) {}
    return b64Signature;
  }
}

/* Location:
 * Qualified Name:     org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package org.opensaml.saml2.binding.encoding;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.List;
import org.opensaml.Configuration;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.ws.message.MessageContext;
import org.opensaml.ws.message.encoder.MessageEncodingException;
import org.opensaml.ws.soap.common.SOAPObjectBuilder;
import org.opensaml.ws.soap.soap11.Body;
import org.opensaml.ws.soap.soap11.Envelope;
import org.opensaml.ws.transport.OutTransport;
import org.opensaml.ws.transport.http.HTTPOutTransport;
import org.opensaml.ws.transport.http.HTTPTransportUtils;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.opensaml.xml.util.XMLHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;

public class HTTPSOAP11Encoder
  extends BaseSAML2MessageEncoder
{
  private final Logger log = LoggerFactory.getLogger(HTTPSOAP11Encoder.class);
  
  public String getBindingURI()
  {
    return "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";
  }
  
  public boolean providesMessageConfidentiality(MessageContext messageContext)
    throws MessageEncodingException
  {
    if (messageContext.getOutboundMessageTransport().isConfidential()) {
      return true;
    }
    return false;
  }
  
  public boolean providesMessageIntegrity(MessageContext messageContext)
    throws MessageEncodingException
  {
    if (messageContext.getOutboundMessageTransport().isIntegrityProtected()) {
      return true;
    }
    return false;
  }
  
  protected void doEncode(MessageContext messageContext)
    throws MessageEncodingException
  {
    if (!(messageContext instanceof SAMLMessageContext))
    {
      log.error("Invalid message context type, this encoder only support SAMLMessageContext");
      throw new MessageEncodingException("Invalid message context type, this encoder only support SAMLMessageContext");
    }
    if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport))
    {
      log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport");
      throw new MessageEncodingException("Invalid outbound message transport type, this encoder only support HTTPOutTransport");
    }
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext)messageContext;
    
    SAMLObject samlMessage = samlMsgCtx.getOutboundSAMLMessage();
    if (samlMessage == null) {
      throw new MessageEncodingException("No outbound SAML message contained in message context");
    }
    signMessage(samlMsgCtx);
    Envelope envelope = buildSOAPMessage(samlMessage);
    samlMsgCtx.setOutboundMessage(envelope);
    
    Element envelopeElem = marshallMessage(envelope);
    try
    {
      HTTPOutTransport outTransport = (HTTPOutTransport)messageContext.getOutboundMessageTransport();
      HTTPTransportUtils.addNoCacheHeaders(outTransport);
      HTTPTransportUtils.setUTF8Encoding(outTransport);
      HTTPTransportUtils.setContentType(outTransport, "text/xml");
      outTransport.setHeader("SOAPAction", "http://www.oasis-open.org/committees/security");
      Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8");
      XMLHelper.writeNode(envelopeElem, out);
      out.flush();
    }
    catch (UnsupportedEncodingException e)
    {
      log.error("JVM does not support required UTF-8 encoding");
      throw new MessageEncodingException("JVM does not support required UTF-8 encoding");
    }
    catch (IOException e)
    {
      log.error("Unable to write message content to outbound stream", e);
      throw new MessageEncodingException("Unable to write message cont
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd