@Test(expected = IllegalArgumentException.class)
 public void sendMessageWhileClosed() throws NoSuchAlgorithmException, URISyntaxException {
   TestMessageHandler handler = new TestMessageHandler();
   Configuration configuration =
       new Configuration(handler, "ws://echo.websocket.org", SSLContext.getDefault());
   WebSocket socket = new WebSocket(configuration);
   socket.sendMessage("some random message");
 }
  public void testProvider() throws Exception {
    SSLContextParameters scp = new SSLContextParameters();
    scp.createSSLContext();

    SSLContext context = scp.createSSLContext();

    SSLContext defaultContext = SSLContext.getDefault();

    assertEquals(defaultContext.getProvider().getName(), context.getProvider().getName());
  }
Example #3
0
 /**
  * Create a new SSL context, configured from an option map and the given parameters.
  *
  * @param keyManagers the key managers to use, or {@code null} to configure from the option map
  * @param trustManagers the trust managers to use, or {@code null} to configure from the option
  *     map
  * @param secureRandom the secure RNG to use, or {@code null} to choose a system default
  * @param optionMap the SSL context options
  * @return a new context
  * @throws NoSuchProviderException if there is no matching provider
  * @throws NoSuchAlgorithmException if there is no matching algorithm
  * @throws KeyManagementException if the context initialization fails
  */
 public static SSLContext createSSLContext(
     KeyManager[] keyManagers,
     TrustManager[] trustManagers,
     SecureRandom secureRandom,
     OptionMap optionMap)
     throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
   final String provider = optionMap.get(Options.SSL_PROVIDER);
   final String protocol = optionMap.get(Options.SSL_PROTOCOL);
   final SSLContext sslContext;
   if (protocol == null) {
     // Default context is initialized automatically
     return SSLContext.getDefault();
   } else if (provider == null) {
     sslContext = SSLContext.getInstance(protocol);
   } else {
     sslContext = SSLContext.getInstance(protocol, provider);
   }
   if (keyManagers == null) {
     final Sequence<Class<? extends KeyManager>> keyManagerClasses =
         optionMap.get(Options.SSL_JSSE_KEY_MANAGER_CLASSES);
     if (keyManagerClasses != null) {
       final int size = keyManagerClasses.size();
       keyManagers = new KeyManager[size];
       for (int i = 0; i < size; i++) {
         keyManagers[i] = instantiate(keyManagerClasses.get(i));
       }
     }
   }
   if (trustManagers == null) {
     final Sequence<Class<? extends TrustManager>> trustManagerClasses =
         optionMap.get(Options.SSL_JSSE_TRUST_MANAGER_CLASSES);
     if (trustManagerClasses != null) {
       final int size = trustManagerClasses.size();
       trustManagers = new TrustManager[size];
       for (int i = 0; i < size; i++) {
         trustManagers[i] = instantiate(trustManagerClasses.get(i));
       }
     }
   }
   sslContext.init(keyManagers, trustManagers, secureRandom);
   sslContext
       .getClientSessionContext()
       .setSessionCacheSize(optionMap.get(Options.SSL_CLIENT_SESSION_CACHE_SIZE, 0));
   sslContext
       .getClientSessionContext()
       .setSessionTimeout(optionMap.get(Options.SSL_CLIENT_SESSION_TIMEOUT, 0));
   sslContext
       .getServerSessionContext()
       .setSessionCacheSize(optionMap.get(Options.SSL_SERVER_SESSION_CACHE_SIZE, 0));
   sslContext
       .getServerSessionContext()
       .setSessionTimeout(optionMap.get(Options.SSL_SERVER_SESSION_TIMEOUT, 0));
   return sslContext;
 }
Example #4
0
  @Override
  public void configure(Binder binder) {
    JsonConfigProvider.bind(binder, "druid.emitter.http", HttpEmitterConfig.class);

    final SSLContext context;
    try {
      context = SSLContext.getDefault();
    } catch (NoSuchAlgorithmException e) {
      throw Throwables.propagate(e);
    }

    binder.bind(SSLContext.class).toProvider(Providers.of(context)).in(LazySingleton.class);
  }
  protected void logSupportedParameters() {
    if (LOGGED.compareAndSet(false, true)) {
      try {
        final SSLContext context = SSLContext.getDefault();
        final String[] protocols = context.getSupportedSSLParameters().getProtocols();
        final SSLSocketFactory factory = context.getSocketFactory();
        final String[] cipherSuites = factory.getSupportedCipherSuites();
        LOGGER.info("Supported protocols: {}", Arrays.toString(protocols));
        LOGGER.info("Supported cipher suites: {}", Arrays.toString(cipherSuites));
      } catch (NoSuchAlgorithmException ignored) {

      }
    }
  }
Example #6
0
  /**
   * Get a <code>List</code> of available <code>Version</code> objects. The list will be sorted in
   * ascending order, so currently "TLSv1.2" will be the last element.
   *
   * @return a sorted list of supported <code>Version</code>s
   */
  private static List<Version> getVersions() {
    SSLParameters sslParams;
    List<Version> versions = new ArrayList<Version>();
    try {
      sslParams = SSLContext.getDefault().getSupportedSSLParameters();
      String[] protocols = sslParams.getProtocols();
      for (int i = 0; i < protocols.length; ++i) {
        if (protocols[i].startsWith("TLS")) versions.add(new Version(protocols[i]));
      }

      Collections.sort(versions);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      System.err.println("this client does not support TLS 1.2");
    }

    return versions;
  }
Example #7
0
  static HttpServer createDashboardHttpServer(Config config) throws IOException {
    boolean secure = config.isServerSecure();
    HttpServer server;
    if (!secure) {
      server = HttpServer.create();
    } else {
      server = HttpsServer.create();
      SSLContext defaultSslContext;
      try {
        defaultSslContext = SSLContext.getDefault();
      } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
      }
      HttpsConfigurator httpsConf = new HttpsConfigurator(defaultSslContext);
      ((HttpsServer) server).setHttpsConfigurator(httpsConf);
    }
    // The Dashboard is on a separate port to prevent malicious HTML documents
    // in the user's repository from performing admin actions with
    // XMLHttpRequest or the like, as the HTML page will then be blocked by
    // same-origin policies.
    try {
      server.bind(new InetSocketAddress(config.getServerDashboardPort()), 0);
    } catch (BindException ex) {
      log.log(
          Level.WARNING,
          "Server dashboard port {0,number,#} is in use.",
          config.getServerDashboardPort());
      throw ex;
    }

    // Use separate Executor for Dashboard to allow the administrator to
    // investigate why things are going wrong without waiting on the normal work
    // queue.
    int maxThreads = 4;
    Executor executor =
        new ThreadPoolExecutor(
            maxThreads, maxThreads, 10, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());
    server.setExecutor(executor);

    log.info("dashboard is listening on port #" + server.getAddress().getPort());

    return server;
  }
Example #8
0
  static HttpServer createHttpServer(Config config) throws IOException {
    HttpServer server;
    if (!config.isServerSecure()) {
      server = HttpServer.create();
    } else {
      server = HttpsServer.create();
      try {
        HttpsConfigurator httpsConf =
            new HttpsConfigurator(SSLContext.getDefault()) {
              public void configure(HttpsParameters params) {
                SSLParameters sslParams = getSSLContext().getDefaultSSLParameters();
                // Allow verifying the GSA and other trusted computers.
                sslParams.setWantClientAuth(true);
                params.setSSLParameters(sslParams);
              }
            };
        ((HttpsServer) server).setHttpsConfigurator(httpsConf);
      } catch (java.security.NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
      }
    }

    int maxThreads = config.getServerMaxWorkerThreads();
    int queueCapacity = config.getServerQueueCapacity();
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(queueCapacity);
    // The Executor can't reject jobs directly, because HttpServer does not
    // appear to handle that case.
    RejectedExecutionHandler policy = new SuggestHandlerAbortPolicy(HttpExchanges.abortImmediately);
    Executor executor =
        new ThreadPoolExecutor(maxThreads, maxThreads, 1, TimeUnit.MINUTES, blockingQueue, policy);
    server.setExecutor(executor);

    try {
      server.bind(new InetSocketAddress(config.getServerPort()), 0);
    } catch (BindException ex) {
      log.log(Level.WARNING, "Server port {0,number,#} is in use.", config.getServerPort());
      throw ex;
    }
    log.info("GSA host name: " + config.getGsaHostname());
    log.info("server is listening on port #" + server.getAddress().getPort());
    return server;
  }
  /**
   * Disables the default strict hostname verification in this client and instead uses a browser
   * compatible hostname verification strategy (i.e. cert hostname wildcards are evaulated more
   * liberally).
   */
  public void disableStrictHostnameVerification() {

    /*
     * If SSL cert checking for endpoints is disabled, we don't need
     * to do any changes to the SSL context.
     */
    if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
      return;
    }

    try {
      SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

      SSLSocketFactory sf =
          new SSLSocketFactory(
              SSLContext.getDefault(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
      Scheme https = new Scheme("https", 443, sf);

      schemeRegistry.register(https);
    } catch (NoSuchAlgorithmException e) {
      throw new AmazonClientException(
          "Unable to access default SSL context to disable strict hostname verification");
    }
  }
Example #10
0
  public static void init(ArrayList<String> volumes) throws IOException {
    HCServiceProxy.init(volumes);
    // Initialization section:
    // Try to open a server socket on port port_number (default 2222)
    // Note that we can't choose a port less than 1023 if we are not
    // privileged users (root)
    try {
      InetSocketAddress addr = new InetSocketAddress(Main.serverHostName, Main.serverPort);
      if (Main.serverUseSSL) {
        String keydir = Main.hashDBStore + File.separator + "keys";
        String key = keydir + File.separator + "dse_server.keystore";
        if (!new File(key).exists()) {
          new File(keydir).mkdirs();
          KeyStore keyStore = KeyStore.getInstance("JKS");
          keyStore.load(null, null);

          CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);

          X500Name x500Name =
              new X500Name(
                  InetAddress.getLocalHost().getCanonicalHostName(),
                  "sdfs_dse",
                  "opendedup",
                  "portland",
                  "or",
                  "US");

          keypair.generate(1024);
          PrivateKey privKey = keypair.getPrivateKey();

          X509Certificate[] chain = new X509Certificate[1];

          chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long) 1096 * 24 * 60 * 60);

          keyStore.setKeyEntry("sdfs", privKey, "sdfs".toCharArray(), chain);

          keyStore.store(new FileOutputStream(key), "sdfs".toCharArray());
          SDFSLogger.getLog().info("generated certificate for ssl communication at " + key);
        }
        FileInputStream keyFile = new FileInputStream(key);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keyFile, "sdfs".toCharArray());
        // init KeyManagerFactory
        KeyManagerFactory keyManagerFactory =
            KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "sdfs".toCharArray());
        // init KeyManager
        KeyManager keyManagers[] = keyManagerFactory.getKeyManagers();
        // init the SSL context
        SSLContext sslContext = SSLContext.getDefault();
        sslContext.init(keyManagers, null, new SecureRandom());
        // get the socket factory
        SSLServerSocketFactory socketFactory = sslContext.getServerSocketFactory();

        // and finally, get the socket
        serverSocket = socketFactory.createServerSocket();
        serverSocket.bind(addr);
        SDFSLogger.getLog().info("listening on encryted channel " + addr.toString());
      } else {
        serverSocket = new ServerSocket();
        serverSocket.bind(addr);
        SDFSLogger.getLog().info("listening on unencryted channel " + addr.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
      SDFSLogger.getLog().fatal("unable to open network ports", e);
      System.exit(-1);
    }

    // Create a socket object from the ServerSocket to listen and accept
    // connections.
    // Open input and output streams for this socket will be created in
    // client's thread since every client is served by the server in
    // an individual thread

    while (true) {
      try {
        clientSocket = serverSocket.accept();
        clientSocket.setKeepAlive(true);
        clientSocket.setTcpNoDelay(true);
        new ClientThread(clientSocket).start();
      } catch (IOException e) {
        if (!serverSocket.isClosed())
          SDFSLogger.getLog().error("Unable to open port " + e.toString(), e);
      }
    }
  }
 @Test
 public void shouldNotOverrideDefaultSSLContextIfKeystoreIsSet() throws Exception {
   System.setProperty("javax.net.ssl.keyStore", "NONE");
   SlaveConnectionManager instance = SlaveConnectionManager.getInstance();
   assertEquals(defaultContext, SSLContext.getDefault());
 }
 @Test
 public void shouldOverrideDefaultSSLContextByDefault() throws Exception {
   System.clearProperty("javax.net.ssl.keyStore");
   SlaveConnectionManager instance = SlaveConnectionManager.getInstance();
   assertNotEquals(defaultContext, SSLContext.getDefault());
 }
 @Before
 public void setUp() throws Exception {
   SlaveConnectionManager.reset();
   defaultContext = SSLContext.getDefault();
 }
 /**
  * Convenience method for setting up a SSL socket factory/engine, using the DEFAULT_SSL_PROTOCOL
  * and a trusting TrustManager.
  */
 public void useSslProtocol() throws NoSuchAlgorithmException, KeyManagementException {
   useSslProtocol(
       computeDefaultTlsProcotol(
           SSLContext.getDefault().getSupportedSSLParameters().getProtocols()));
 }
  @Override
  public List<Attribute> getMonitorData() {
    ArrayList<Attribute> attrs = new ArrayList<>(13);

    attrs.add(createAttribute("javaVersion", System.getProperty("java.version")));
    attrs.add(createAttribute("javaVendor", System.getProperty("java.vendor")));
    attrs.add(createAttribute("jvmVersion", System.getProperty("java.vm.version")));
    attrs.add(createAttribute("jvmVendor", System.getProperty("java.vm.vendor")));
    attrs.add(createAttribute("javaHome", System.getProperty("java.home")));
    attrs.add(createAttribute("classPath", System.getProperty("java.class.path")));
    attrs.add(createAttribute("workingDirectory", System.getProperty("user.dir")));

    String osInfo =
        System.getProperty("os.name")
            + " "
            + System.getProperty("os.version")
            + " "
            + System.getProperty("os.arch");
    attrs.add(createAttribute("operatingSystem", osInfo));
    String sunOsArchDataModel = System.getProperty("sun.arch.data.model");
    if (sunOsArchDataModel != null) {
      String jvmArch = sunOsArchDataModel;
      if (!sunOsArchDataModel.toLowerCase().equals("unknown")) {
        jvmArch += "-bit";
      }
      attrs.add(createAttribute("jvmArchitecture", jvmArch));
    } else {
      attrs.add(createAttribute("jvmArchitecture", "unknown"));
    }

    try {
      attrs.add(createAttribute("systemName", InetAddress.getLocalHost().getCanonicalHostName()));
    } catch (Exception e) {
      logger.traceException(e);
    }

    Runtime runtime = Runtime.getRuntime();
    attrs.add(createAttribute("availableCPUs", runtime.availableProcessors()));
    attrs.add(createAttribute("maxMemory", runtime.maxMemory()));
    attrs.add(createAttribute("usedMemory", runtime.totalMemory()));
    attrs.add(createAttribute("freeUsedMemory", runtime.freeMemory()));
    String installPath = DirectoryServer.getServerRoot();
    if (installPath != null) {
      attrs.add(createAttribute("installPath", installPath));
    }
    String instancePath = DirectoryServer.getInstanceRoot();
    if (instancePath != null) {
      attrs.add(createAttribute("instancePath", instancePath));
    }

    // Get the JVM input arguments.
    RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean();
    List<String> jvmArguments = rtBean.getInputArguments();
    if (jvmArguments != null && !jvmArguments.isEmpty()) {
      StringBuilder argList = new StringBuilder();
      for (String jvmArg : jvmArguments) {
        if (argList.length() > 0) {
          argList.append(" ");
        }

        argList.append("\"");
        argList.append(jvmArg);
        argList.append("\"");
      }

      attrs.add(createAttribute("jvmArguments", argList.toString()));
    }

    // Get the list of supported SSL protocols and ciphers.
    Collection<String> supportedTlsProtocols;
    Collection<String> supportedTlsCiphers;
    try {
      final SSLContext context = SSLContext.getDefault();
      final SSLParameters parameters = context.getSupportedSSLParameters();
      supportedTlsProtocols = Arrays.asList(parameters.getProtocols());
      supportedTlsCiphers = Arrays.asList(parameters.getCipherSuites());
    } catch (Exception e) {
      // A default SSL context should always be available.
      supportedTlsProtocols = Collections.emptyList();
      supportedTlsCiphers = Collections.emptyList();
    }

    addAttribute(attrs, ATTR_SUPPORTED_TLS_PROTOCOLS, supportedTlsProtocols);
    addAttribute(attrs, ATTR_SUPPORTED_TLS_CIPHERS, supportedTlsCiphers);

    return attrs;
  }