예제 #1
0
 private static FilterInfo getFilterInfo(FilterDef fd) {
   FilterInfo fi = new FilterInfo();
   fi.setFilterName(fd.getFilterName());
   fi.setFilterClass(fd.getFilterClass());
   fi.setFilterDesc(fd.getDescription());
   return fi;
 }
  /** Return a String representation of this object. */
  public String toString() {

    StringBuffer sb = new StringBuffer("ApplicationFilterConfig[");
    sb.append("name=");
    sb.append(filterDef.getFilterName());
    sb.append(", filterClass=");
    sb.append(filterDef.getFilterClass());
    sb.append("]");
    return (sb.toString());
  }
예제 #3
0
  private void addSessionFilter(Context ctx) {
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterName(HibernateSessionFilter.class.getSimpleName());
    filterDef.setFilter(new HibernateSessionFilter());
    filterDef.setAsyncSupported("true");
    ctx.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(HibernateSessionFilter.class.getSimpleName());
    filterMap.addURLPattern("/api/*");
    ctx.addFilterMap(filterMap);
  }
예제 #4
0
  private void addCharacterEncodingFilter(Context ctx) {
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterName(CharsetFilter.class.getSimpleName());
    filterDef.setFilter(new CharsetFilter());
    filterDef.setAsyncSupported("true");
    ctx.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(CharsetFilter.class.getSimpleName());
    filterMap.addURLPattern("/*");
    ctx.addFilterMap(filterMap);
  }
  /**
   * Construct a new ApplicationFilterConfig for the specified filter definition.
   *
   * @param context The context with which we are associated
   * @param filterDef Filter definition for which a FilterConfig is to be constructed
   * @exception ClassCastException if the specified class does not implement the <code>
   *     javax.servlet.Filter</code> interface
   * @exception ClassNotFoundException if the filter class cannot be found
   * @exception IllegalAccessException if the filter class cannot be publicly instantiated
   * @exception InstantiationException if an exception occurs while instantiating the filter object
   * @exception ServletException if thrown by the filter's init() method
   * @throws NamingException
   * @throws InvocationTargetException
   */
  ApplicationFilterConfig(Context context, FilterDef filterDef)
      throws ClassCastException, ClassNotFoundException, IllegalAccessException,
          InstantiationException, ServletException, InvocationTargetException, NamingException {

    super();

    this.context = context;
    setFilterDef(filterDef);
    if (filterDef.getFilter() != null) {
      this.filter = filterDef.getFilter();
      getInstanceManager().newInstance(filter);
      initFilter();
    }
  }
  /**
   * Return the application Filter we are configured for.
   *
   * @exception ClassCastException if the specified class does not implement the <code>
   *     javax.servlet.Filter</code> interface
   * @exception ClassNotFoundException if the filter class cannot be found
   * @exception IllegalAccessException if the filter class cannot be publicly instantiated
   * @exception InstantiationException if an exception occurs while instantiating the filter object
   * @exception ServletException if thrown by the filter's init() method
   */
  Filter getFilter()
      throws ClassCastException, ClassNotFoundException, IllegalAccessException,
          InstantiationException, ServletException {

    // Return the existing filter instance, if any
    if (this.filter != null) return (this.filter);

    // Identify the class loader we will be using
    String filterClass = filterDef.getFilterClass();
    ClassLoader classLoader = null;
    if (filterClass.startsWith("org.apache.catalina."))
      classLoader = this.getClass().getClassLoader();
    else classLoader = context.getLoader().getClassLoader();

    ClassLoader oldCtxClassLoader = Thread.currentThread().getContextClassLoader();

    // Instantiate a new instance of this filter and return it
    Class clazz = classLoader.loadClass(filterClass);
    this.filter = (Filter) clazz.newInstance();
    if (context instanceof StandardContext && ((StandardContext) context).getSwallowOutput()) {
      try {
        SystemLogHandler.startCapture();
        filter.init(this);
      } finally {
        String log = SystemLogHandler.stopCapture();
        if (log != null && log.length() > 0) {
          getServletContext().log(log);
        }
      }
    } else {
      filter.init(this);
    }
    return (this.filter);
  }
예제 #7
0
  private static void configureTest46243Context(Context context, boolean fail) {
    // Add a test filter that fails
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterClass(Bug46243Filter.class.getName());
    filterDef.setFilterName("Bug46243");
    filterDef.addInitParameter("fail", Boolean.toString(fail));
    context.addFilterDef(filterDef);
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName("Bug46243");
    filterMap.addURLPattern("*");
    context.addFilterMap(filterMap);

    // Add a test servlet so there is something to generate a response if
    // it works (although it shouldn't)
    Tomcat.addServlet(context, "Bug46243", new HelloWorldServlet());
    context.addServletMapping("/", "Bug46243");
  }
  /**
   * Return a <code>String</code> containing the value of the named initialization parameter, or
   * <code>null</code> if the parameter does not exist.
   *
   * @param name Name of the requested initialization parameter
   */
  @Override
  public String getInitParameter(String name) {

    Map<String, String> map = filterDef.getParameterMap();
    if (map == null) {
      return (null);
    }

    return map.get(name);
  }
  /**
   * Return an <code>Enumeration</code> of the names of the initialization parameters for this
   * Filter.
   */
  @Override
  public Enumeration<String> getInitParameterNames() {
    Map<String, String> map = filterDef.getParameterMap();

    if (map == null) {
      return Collections.enumeration(emptyString);
    }

    return Collections.enumeration(map.keySet());
  }
  private void registerJMX() {
    String parentName = context.getName();
    if (!parentName.startsWith("/")) {
      parentName = "/" + parentName;
    }

    String hostName = context.getParent().getName();
    hostName = (hostName == null) ? "DEFAULT" : hostName;

    // domain == engine name
    String domain = context.getParent().getParent().getName();

    String webMod = "//" + hostName + parentName;
    String onameStr = null;
    if (context instanceof StandardContext) {
      StandardContext standardContext = (StandardContext) context;
      onameStr =
          domain
              + ":j2eeType=Filter,name="
              + filterDef.getFilterName()
              + ",WebModule="
              + webMod
              + ",J2EEApplication="
              + standardContext.getJ2EEApplication()
              + ",J2EEServer="
              + standardContext.getJ2EEServer();
    } else {
      onameStr =
          domain + ":j2eeType=Filter,name=" + filterDef.getFilterName() + ",WebModule=" + webMod;
    }
    try {
      oname = new ObjectName(onameStr);
      Registry.getRegistry(null, null).registerComponent(this, oname, null);
    } catch (Exception ex) {
      log.info(
          sm.getString(
              "applicationFilterConfig.jmxRegisterFail", getFilterClass(), getFilterName()),
          ex);
    }
  }
예제 #11
0
  @Test
  public void testBug46243() throws Exception {

    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    File docBase = new File(tomcat.getHost().getAppBase(), "ROOT");
    if (!docBase.mkdirs() && !docBase.isDirectory()) {
      fail("Unable to create docBase");
    }

    Context root = tomcat.addContext("", "ROOT");

    // Add test a filter that fails
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterClass(Bug46243Filter.class.getName());
    filterDef.setFilterName("Bug46243");
    root.addFilterDef(filterDef);
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName("Bug46243");
    filterMap.addURLPattern("*");
    root.addFilterMap(filterMap);

    // Add a test servlet so there is something to generate a response if
    // it works (although it shouldn't)
    Tomcat.addServlet(root, "Bug46243", new HelloWorldServlet());
    root.addServletMapping("/", "Bug46243");

    tomcat.start();

    // Configure the client
    Bug46243Client client = new Bug46243Client(tomcat.getConnector().getLocalPort());
    client.setRequest(new String[] {REQUEST});

    client.connect();
    client.processRequest();
    assertTrue(client.isResponse404());
  }
  /**
   * Return the application Filter we are configured for.
   *
   * @exception ClassCastException if the specified class does not implement the <code>
   *     javax.servlet.Filter</code> interface
   * @exception ClassNotFoundException if the filter class cannot be found
   * @exception IllegalAccessException if the filter class cannot be publicly instantiated
   * @exception InstantiationException if an exception occurs while instantiating the filter object
   * @exception ServletException if thrown by the filter's init() method
   * @throws NamingException
   * @throws InvocationTargetException
   */
  Filter getFilter()
      throws ClassCastException, ClassNotFoundException, IllegalAccessException,
          InstantiationException, ServletException, InvocationTargetException, NamingException {

    // Return the existing filter instance, if any
    if (this.filter != null) return (this.filter);

    // Identify the class loader we will be using
    String filterClass = filterDef.getFilterClass();
    this.filter = (Filter) getInstanceManager().newInstance(filterClass);

    initFilter();

    return (this.filter);
  }
  /**
   * Set the filter definition we are configured for. This has the side effect of instantiating an
   * instance of the corresponding filter class.
   *
   * @param filterDef The new filter definition
   * @exception ClassCastException if the specified class does not implement the <code>
   *     javax.servlet.Filter</code> interface
   * @exception ClassNotFoundException if the filter class cannot be found
   * @exception IllegalAccessException if the filter class cannot be publicly instantiated
   * @exception InstantiationException if an exception occurs while instantiating the filter object
   * @exception ServletException if thrown by the filter's init() method
   * @throws NamingException
   * @throws InvocationTargetException
   */
  void setFilterDef(FilterDef filterDef)
      throws ClassCastException, ClassNotFoundException, IllegalAccessException,
          InstantiationException, ServletException, InvocationTargetException, NamingException {

    this.filterDef = filterDef;
    if (filterDef == null) {

      // Release any previously allocated filter instance
      if (this.filter != null) {
        if (Globals.IS_SECURITY_ENABLED) {
          try {
            SecurityUtil.doAsPrivilege("destroy", filter);
          } catch (java.lang.Exception ex) {
            context.getLogger().error("ApplicationFilterConfig.doAsPrivilege", ex);
          }
          SecurityUtil.remove(filter);
        } else {
          filter.destroy();
        }
        if (!context.getIgnoreAnnotations()) {
          try {
            ((StandardContext) context).getInstanceManager().destroyInstance(this.filter);
          } catch (Exception e) {
            Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(t);
            context.getLogger().error("ApplicationFilterConfig.preDestroy", t);
          }
        }
      }
      this.filter = null;

    } else {
      // Allocate a new filter instance if necessary
      if (filterDef.getFilter() == null) {
        getFilter();
      }
    }
  }
  @Override
  protected void doStart() throws ElasticsearchException {
    try {

      final String currentDir = new File(".").getCanonicalPath();
      final String tomcatDir = currentDir + File.separatorChar + "tomcat";

      logger.debug("cur dir " + currentDir);

      if (tomcat != null) {
        try {
          tomcat.stop();
          tomcat.destroy();
        } catch (final Exception e) {

        }
      }

      tomcat = new ExtendedTomcat();
      tomcat.enableNaming();
      tomcat.getServer().setPort(-1); // shutdown disabled
      tomcat.getServer().setAddress("localhost");

      final String httpProtocolImpl =
          blockingServer
              ? "org.apache.coyote.http11.Http11Protocol"
              : "org.apache.coyote.http11.Http11NioProtocol";

      final Connector httpConnector = new Connector(httpProtocolImpl);
      tomcat.setConnector(httpConnector);
      tomcat.getService().addConnector(httpConnector);

      // TODO report tomcat bug with setProtocol

      if (maxContentLength != null) {
        httpConnector.setMaxPostSize(maxContentLength.bytesAsInt());
      }

      if (maxHeaderSize != null) {
        httpConnector.setAttribute("maxHttpHeaderSize", maxHeaderSize.bytesAsInt());
      }

      if (tcpNoDelay != null) {
        httpConnector.setAttribute("tcpNoDelay", tcpNoDelay.booleanValue());
      }

      if (reuseAddress != null) {
        httpConnector.setAttribute("socket.soReuseAddress", reuseAddress.booleanValue());
      }

      if (tcpKeepAlive != null) {
        httpConnector.setAttribute("socket.soKeepAlive", tcpKeepAlive.booleanValue());
        httpConnector.setAttribute(
            "maxKeepAliveRequests", tcpKeepAlive.booleanValue() ? "100" : "1");
      }

      if (tcpReceiveBufferSize != null) {
        httpConnector.setAttribute("socket.rxBufSize", tcpReceiveBufferSize.bytesAsInt());
      }

      if (tcpSendBufferSize != null) {
        httpConnector.setAttribute("socket.txBufSize", tcpSendBufferSize.bytesAsInt());
      }

      httpConnector.setAttribute(
          "compression", compression ? String.valueOf(compressionLevel) : "off");

      if (maxChunkSize != null) {
        httpConnector.setAttribute("maxExtensionSize", maxChunkSize.bytesAsInt());
      }

      httpConnector.setPort(Integer.parseInt(port));

      tomcat.setBaseDir(tomcatDir);

      final TomcatHttpTransportHandlerServlet servlet = new TomcatHttpTransportHandlerServlet();
      servlet.setTransport(this);

      final Context ctx = tomcat.addContext("", currentDir);

      logger.debug("currentDir " + currentDir);

      Tomcat.addServlet(ctx, "ES Servlet", servlet);

      ctx.addServletMapping("/*", "ES Servlet");

      if (useSSL) {
        logger.info("Using SSL");

        // System.setProperty("javax.net.debug", "ssl");
        httpConnector.setAttribute("SSLEnabled", "true");
        httpConnector.setSecure(true);
        httpConnector.setScheme("https");

        httpConnector.setAttribute("sslProtocol", "TLS");

        httpConnector.setAttribute(
            "keystoreFile", settings.get("security.ssl.keystorefile", "keystore"));
        httpConnector.setAttribute(
            "keystorePass", settings.get("security.ssl.keystorepass", "changeit"));
        httpConnector.setAttribute(
            "keystoreType", settings.get("security.ssl.keystoretype", "JKS"));

        final String keyalias = settings.get("security.ssl.keyalias", null);

        if (keyalias != null) {
          httpConnector.setAttribute("keyAlias", keyalias);
        }

        if (useClientAuth) {

          logger.info(
              "Using SSL Client Auth (PKI), so user/roles will be retrieved from client certificate.");

          httpConnector.setAttribute("clientAuth", "true");

          httpConnector.setAttribute(
              "truststoreFile",
              settings.get("security.ssl.clientauth.truststorefile", "truststore"));
          httpConnector.setAttribute(
              "truststorePass", settings.get("security.ssl.clientauth.truststorepass", "changeit"));
          httpConnector.setAttribute(
              "truststoreType", settings.get("security.ssl.clientauth.truststoretype", "JKS"));

          /*final String loginconf = this.settings
          		.get("security.kerberos.login.conf.path");
          final String krbconf = this.settings
          		.get("security.kerberos.krb5.conf.path");

          SecurityUtil.setSystemPropertyToAbsoluteFile(
          		"java.security.auth.login.config", loginconf);
          SecurityUtil.setSystemPropertyToAbsoluteFile(
          		"java.security.krb5.conf", krbconf);*/

          // httpConnector.setAttribute("allowUnsafeLegacyRenegotiation", "true");

          final SecurityConstraint constraint = new SecurityConstraint();
          constraint.addAuthRole("*");
          constraint.setAuthConstraint(true);
          constraint.setUserConstraint("CONFIDENTIAL");

          final SecurityCollection col = new SecurityCollection();
          col.addPattern("/*");

          constraint.addCollection(col);
          ctx.addConstraint(constraint);

          final LoginConfig lc = new LoginConfig();
          lc.setAuthMethod("CLIENT-CERT");
          lc.setRealmName("clientcretificate");
          ctx.setLoginConfig(lc);

          configureJndiRealm(ctx);

          ctx.getPipeline().addValve(new SSLAuthenticator());
          logger.info("Auth Method is CLIENT-CERT");

          // http://pki-tutorial.readthedocs.org/en/latest/simple/

        }

      } else {
        if (useClientAuth) {
          logger.error("Client Auth only available with SSL");
          throw new RuntimeException("Client Auth only available with SSL");
        }

        // useClientAuth = false;
      }

      if (!useClientAuth) {
        if ("waffle".equalsIgnoreCase(kerberosMode)) {

          final Boolean testMode = settings.getAsBoolean("security.waffle.testmode", false);

          final FilterDef fd = new FilterDef();
          fd.setFilterClass("waffle.servlet.NegotiateSecurityFilter");
          fd.setFilterName("Waffle");

          if (testMode != null && testMode.booleanValue()) {

            fd.addInitParameter("principalFormat", "fqn");
            fd.addInitParameter("roleFormat", "both");
            fd.addInitParameter("allowGuestLogin", "true");
            fd.addInitParameter(
                "securityFilterProviders",
                "org.elasticsearch.plugins.security.waffle.TestProvider");

            logger.info(
                "Kerberos implementaton is WAFFLE in testmode (only work on Windows Operations system)");
          } else {
            final Map<String, String> waffleSettings =
                settings.getByPrefix("security.waffle").getAsMap();

            for (final String waffleKey : waffleSettings.keySet()) {

              fd.addInitParameter(waffleKey.substring(1), waffleSettings.get(waffleKey));

              logger.debug(waffleKey.substring(1) + "=" + waffleSettings.get(waffleKey));
            }

            fd.addInitParameter("principalFormat", "fqn");
            fd.addInitParameter("roleFormat", "both");
            fd.addInitParameter("allowGuestLogin", "false");

            logger.info(
                "Kerberos implementaton is WAFFLE (only work on Windows Operations system)");
          }

          ctx.addFilterDef(fd);
          final FilterMap fm = new FilterMap();
          fm.setFilterName("Waffle");
          fm.addURLPattern("/*");
          ctx.addFilterMap(fm);

        } else if ("spnegoad".equalsIgnoreCase(kerberosMode)) {

          // System.setProperty("sun.security.krb5.debug", "true"); // TODO
          // switch
          // off

          System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

          final SecurityConstraint constraint = new SecurityConstraint();
          constraint.addAuthRole("*");
          constraint.setAuthConstraint(true);
          constraint.setDisplayName("spnego_sc_all");
          final SecurityCollection col = new SecurityCollection();
          col.addPattern("/*");

          constraint.addCollection(col);
          ctx.addConstraint(constraint);

          final LoginConfig lc = new LoginConfig();
          lc.setAuthMethod("SPNEGO");
          lc.setRealmName("SPNEGO");
          ctx.setLoginConfig(lc);

          logger.info("Kerberos implementaton is SPNEGOAD");

          configureJndiRealm(ctx);

          final ExtendedSpnegoAuthenticator spnegoValve = new ExtendedSpnegoAuthenticator();
          // spnegoValve.setLoginConfigName("es-login");
          spnegoValve.setStoreDelegatedCredential(true);
          ctx.getPipeline().addValve(spnegoValve);

          // final SpnegoAuthenticator spnegoValve = new SpnegoAuthenticator();
          // spnegoValve.setLoginEntryName("es-login");
          // ctx.getPipeline().addValve(spnegoValve);

        } else if ("none".equalsIgnoreCase(kerberosMode)) {

          logger.warn(
              "Kerberos is not configured so user/roles are unavailable. Host based security, in contrast, is woking. ");

        } else {
          logger.error(
              "No Kerberos implementaion '"
                  + kerberosMode
                  + "' found. Kerberos is therefore not configured so user/roles are unavailable. Host based security, in contrast, is woking. ");
        }
      }

      tomcat.start();

      logger.info("Tomcat started");

      InetSocketAddress bindAddress;
      try {
        bindAddress =
            new InetSocketAddress(
                networkService.resolveBindHostAddress(bindHost),
                tomcat.getConnector().getLocalPort());
      } catch (final Exception e) {
        throw new BindTransportException("Failed to resolve bind address", e);
      }

      InetSocketAddress publishAddress;
      try {
        publishAddress =
            new InetSocketAddress(
                networkService.resolvePublishHostAddress(publishHost), bindAddress.getPort());
      } catch (final Exception e) {
        throw new BindTransportException("Failed to resolve publish address", e);
      }

      logger.debug("bindAddress " + bindAddress);
      logger.debug("publishAddress " + publishAddress);

      boundAddress =
          new BoundTransportAddress(
              new InetSocketTransportAddress(bindAddress),
              new InetSocketTransportAddress(publishAddress));

    } catch (final Exception e) {
      throw new ElasticsearchException("Unable to start Tomcat", e);
    }
  }
  /**
   * Return an <code>Enumeration</code> of the names of the initialization parameters for this
   * Filter.
   */
  public Enumeration getInitParameterNames() {

    Map map = filterDef.getParameterMap();
    if (map == null) return (new Enumerator(new ArrayList()));
    else return (new Enumerator(map.keySet()));
  }
  /**
   * Return a <code>String</code> containing the value of the named initialization parameter, or
   * <code>null</code> if the parameter does not exist.
   *
   * @param name Name of the requested initialization parameter
   */
  public String getInitParameter(String name) {

    Map map = filterDef.getParameterMap();
    if (map == null) return (null);
    else return ((String) map.get(name));
  }
  /** Return the name of the filter we are configuring. */
  public String getFilterName() {

    return (filterDef.getFilterName());
  }
 /** Return the class of the filter we are configuring. */
 public String getFilterClass() {
   return filterDef.getFilterClass();
 }
 public Map<String, String> getFilterInitParameterMap() {
   return Collections.unmodifiableMap(filterDef.getParameterMap());
 }