コード例 #1
0
  protected static void initSsl(
      Tomcat tomcat, String keystore, String keystorePass, String keyPass) {

    String protocol = tomcat.getConnector().getProtocolHandlerClassName();
    if (protocol.indexOf("Apr") == -1) {
      Connector connector = tomcat.getConnector();
      connector.setProperty("sslProtocol", "tls");
      File keystoreFile = new File("test/org/apache/tomcat/util/net/" + keystore);
      connector.setAttribute("keystoreFile", keystoreFile.getAbsolutePath());
      File truststoreFile = new File("test/org/apache/tomcat/util/net/ca.jks");
      connector.setAttribute("truststoreFile", truststoreFile.getAbsolutePath());
      if (keystorePass != null) {
        connector.setAttribute("keystorePass", keystorePass);
      }
      if (keyPass != null) {
        connector.setAttribute("keyPass", keyPass);
      }
    } else {
      File keystoreFile = new File("test/org/apache/tomcat/util/net/localhost-cert.pem");
      tomcat.getConnector().setAttribute("SSLCertificateFile", keystoreFile.getAbsolutePath());
      keystoreFile = new File("test/org/apache/tomcat/util/net/localhost-key.pem");
      tomcat.getConnector().setAttribute("SSLCertificateKeyFile", keystoreFile.getAbsolutePath());
    }
    tomcat.getConnector().setSecure(true);
    tomcat.getConnector().setProperty("SSLEnabled", "true");
  }
コード例 #2
0
  @Before
  @Override
  public void setUp() throws Exception {
    super.setUp();

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    File appBase = new File(getTemporaryDirectory(), "webapps");
    if (!appBase.exists() && !appBase.mkdir()) {
      fail("Unable to create appBase for test");
    }

    tomcat = new TomcatWithFastSessionIDs();

    String protocol = getProtocol();
    Connector connector = new Connector(protocol);
    // Listen only on localhost
    connector.setAttribute("address", InetAddress.getByName("localhost").getHostAddress());
    // Use random free port
    connector.setPort(0);
    // Mainly set to reduce timeouts during async tests
    connector.setAttribute("connectionTimeout", "3000");
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    // Add AprLifecycleListener if we are using the Apr connector
    if (protocol.contains("Apr")) {
      StandardServer server = (StandardServer) tomcat.getServer();
      AprLifecycleListener listener = new AprLifecycleListener();
      listener.setSSLRandomSeed("/dev/urandom");
      server.addLifecycleListener(listener);
      connector.setAttribute("pollerThreadCount", Integer.valueOf(1));
    }

    File catalinaBase = getTemporaryDirectory();
    tomcat.setBaseDir(catalinaBase.getAbsolutePath());
    tomcat.getHost().setAppBase(appBase.getAbsolutePath());

    accessLogEnabled = Boolean.parseBoolean(System.getProperty("tomcat.test.accesslog", "false"));
    if (accessLogEnabled) {
      AccessLogValve alv = new AccessLogValve();
      alv.setDirectory(getBuildDirectory() + "/logs");
      alv.setPattern("%h %l %u %t \"%r\" %s %b %I %D");
      tomcat.getHost().getPipeline().addValve(alv);
    }

    // Cannot delete the whole tempDir, because logs are there,
    // but delete known subdirectories of it.
    addDeleteOnTearDown(new File(catalinaBase, "webapps"));
    addDeleteOnTearDown(new File(catalinaBase, "work"));
  }
コード例 #3
0
  // Needs to be protected so it can be used by subclasses
  protected void customizeConnector(Connector connector) {
    int port = (getPort() >= 0 ? getPort() : 0);
    connector.setPort(port);
    if (StringUtils.hasText(this.getServerHeader())) {
      connector.setAttribute("server", this.getServerHeader());
    }
    if (connector.getProtocolHandler() instanceof AbstractProtocol) {
      customizeProtocol((AbstractProtocol<?>) connector.getProtocolHandler());
    }
    if (getUriEncoding() != null) {
      connector.setURIEncoding(getUriEncoding().name());
    }

    // If ApplicationContext is slow to start we want Tomcat not to bind to the socket
    // prematurely...
    connector.setProperty("bindOnInit", "false");

    if (getSsl() != null && getSsl().isEnabled()) {
      customizeSsl(connector);
    }
    if (getCompression() != null && getCompression().getEnabled()) {
      customizeCompression(connector);
    }
    for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) {
      customizer.customize(connector);
    }
  }
コード例 #4
0
ファイル: KerberosTest.java プロジェクト: hzbarcea/cxf-fediz
  private static void initIdp() {
    try {
      idpServer = new Tomcat();
      idpServer.setPort(0);
      String currentDir = new File(".").getCanonicalPath();
      idpServer.setBaseDir(currentDir + File.separator + "target");

      idpServer.getHost().setAppBase("tomcat/idp/webapps");
      idpServer.getHost().setAutoDeploy(true);
      idpServer.getHost().setDeployOnStartup(true);

      Connector httpsConnector = new Connector();
      httpsConnector.setPort(Integer.parseInt(idpHttpsPort));
      httpsConnector.setSecure(true);
      httpsConnector.setScheme("https");
      // httpsConnector.setAttribute("keyAlias", keyAlias);
      httpsConnector.setAttribute("keystorePass", "tompass");
      httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
      httpsConnector.setAttribute("truststorePass", "tompass");
      httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
      httpsConnector.setAttribute("clientAuth", "want");
      // httpsConnector.setAttribute("clientAuth", "false");
      httpsConnector.setAttribute("sslProtocol", "TLS");
      httpsConnector.setAttribute("SSLEnabled", true);

      idpServer.getService().addConnector(httpsConnector);

      idpServer.addWebapp("/fediz-idp-sts", "fediz-idp-sts");
      idpServer.addWebapp("/fediz-idp", "fediz-idp");

      idpServer.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #5
0
ファイル: KerberosTest.java プロジェクト: hzbarcea/cxf-fediz
  private static void initRp() {
    try {
      rpServer = new Tomcat();
      rpServer.setPort(0);
      String currentDir = new File(".").getCanonicalPath();
      rpServer.setBaseDir(currentDir + File.separator + "target");

      rpServer.getHost().setAppBase("tomcat/rp/webapps");
      rpServer.getHost().setAutoDeploy(true);
      rpServer.getHost().setDeployOnStartup(true);

      Connector httpsConnector = new Connector();
      httpsConnector.setPort(Integer.parseInt(rpHttpsPort));
      httpsConnector.setSecure(true);
      httpsConnector.setScheme("https");
      // httpsConnector.setAttribute("keyAlias", keyAlias);
      httpsConnector.setAttribute("keystorePass", "tompass");
      httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
      httpsConnector.setAttribute("truststorePass", "tompass");
      httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
      // httpsConnector.setAttribute("clientAuth", "false");
      httpsConnector.setAttribute("clientAuth", "want");
      httpsConnector.setAttribute("sslProtocol", "TLS");
      httpsConnector.setAttribute("SSLEnabled", true);

      rpServer.getService().addConnector(httpsConnector);

      // Context ctx =
      Context cxt = rpServer.addWebapp("/fedizhelloworld", "simpleWebapp");
      FederationAuthenticator fa = new FederationAuthenticator();
      fa.setConfigFile(
          currentDir
              + File.separator
              + "target"
              + File.separator
              + "test-classes"
              + File.separator
              + "fediz_config.xml");
      cxt.getPipeline().addValve(fa);

      rpServer.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #6
0
ファイル: TomcatContainer.java プロジェクト: kicktipp/jlot
 private static void configureHttpsConnector(Tomcat tomcat, TomcatConfig tomcatConfig) {
   Connector connector = new Connector();
   connector.setProperty("server", "jlot");
   connector.setPort(tomcatConfig.getSslPort());
   connector.setSecure(true);
   connector.setEnableLookups(false);
   connector.setScheme("https");
   connector.setAttribute("SSLEnabled", true);
   File file = new File("../kicktipp.org.keystore");
   String keystoreFile = file.getAbsolutePath();
   connector.setAttribute("keystoreFile", keystoreFile);
   connector.setAttribute("keyAlias", "tomcat");
   connector.setAttribute("keystorePass", "tomcat");
   connector.setAttribute("clientAuth", "false");
   connector.setAttribute("sslProtocol", "TLS");
   addCompression(connector);
   tomcat.getService().addConnector(connector);
 }
コード例 #7
0
  /**
   * Start the instance using the ports provided
   *
   * @param port the http port to use
   * @param securePort the secure https port to use
   */
  @SuppressWarnings("unchecked")
  public T start(final Integer port, final Integer securePort) {
    if (port == null && securePort == null)
      throw new IllegalStateException("You must specify a port or a secure port");
    if (isRunning()) throw new IllegalStateException("Server already running");
    final String startedMessage =
        "Started "
            + this.getClass().getSimpleName().replace("Runner", "")
            + " listening on:"
            + (port != null ? " standard port " + port : "")
            + (securePort != null ? " secure port " + securePort : "");

    try {
      String servletContext = "";

      tomcat = new Tomcat();
      tomcat.setBaseDir(
          new File(".").getCanonicalPath()
              + File.separatorChar
              + "tomcat"
              + (servletContext.length() > 0 ? "_" + servletContext : ""));

      // add http port
      tomcat.setPort(port != null ? port : securePort);

      if (securePort != null) {
        // add https connector
        SSLFactory.buildKeyStore();
        Connector httpsConnector = new Connector();
        httpsConnector.setPort(securePort);
        httpsConnector.setSecure(true);
        httpsConnector.setAttribute("keyAlias", SSLFactory.KEY_STORE_ALIAS);
        httpsConnector.setAttribute("keystorePass", SSLFactory.KEY_STORE_PASSWORD);
        logger.trace(
            "Loading key store from file ["
                + new File(SSLFactory.KEY_STORE_FILENAME).getAbsoluteFile()
                + "]");
        httpsConnector.setAttribute(
            "keystoreFile", new File(SSLFactory.KEY_STORE_FILENAME).getAbsoluteFile());
        httpsConnector.setAttribute("clientAuth", "false");
        httpsConnector.setAttribute("sslProtocol", "TLS");
        httpsConnector.setAttribute("SSLEnabled", true);

        Service service = tomcat.getService();
        service.addConnector(httpsConnector);

        Connector defaultConnector = tomcat.getConnector();
        defaultConnector.setRedirectPort(securePort);
      }

      // add servlet
      Context ctx = tomcat.addContext("/" + servletContext, new File(".").getAbsolutePath());
      tomcat.addServlet("/" + servletContext, "mockServerServlet", getServlet());
      ctx.addServletMapping("/*", "mockServerServlet");

      // start server
      tomcat.start();

      // create and start shutdown thread
      shutdownThread = new ShutdownThread(stopPort(port, securePort));
      shutdownThread.start();
      serverStarted(port, securePort);

      logger.info(startedMessage);
      System.out.println(startedMessage);

      join();
    } catch (Throwable t) {
      logger.error("Exception while starting server", t);
    }

    return (T) this;
  }
  @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);
    }
  }