Example #1
0
 public NetworkThread(String server, String channel, int port) {
   try {
     this.channel = channel;
     if (Settings.ssl) {
       SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
       socket = (SSLSocket) sslsocketfactory.createSocket();
       List<String> limited = new LinkedList<String>();
       for (String suite : ((SSLSocket) socket).getEnabledCipherSuites()) {
         if (!suite.contains("_DHE_")) {
           limited.add(suite);
         }
       }
       ((SSLSocket) socket).setEnabledCipherSuites(limited.toArray(new String[limited.size()]));
       socket.connect(new InetSocketAddress(server, port));
     } else {
       socket = new Socket(server, port);
     }
     writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
     reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     uc = new Utilities();
     line = null;
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    for (int i = 0; i < 10; i++) {
      sslOS.write(280);
      sslOS.flush();
      sslIS.read();
    }

    sslSocket.close();
  }
Example #3
0
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    // enable TLSv1.1 only
    sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

    // enable a block cipher
    sslSocket.setEnabledCipherSuites(new String[] {"TLS_RSA_WITH_AES_128_CBC_SHA"});

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslOS.write('B');
    sslOS.flush();
    sslIS.read();

    sslSocket.close();
  }
Example #4
0
 public void call() {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   PrintStream out = System.out;
   SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
   try {
     SSLSocket c = (SSLSocket) f.createSocket("localhost", 8888);
     printSocketInfo(c);
     c.startHandshake();
     BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
     BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
     String m = null;
     while ((m = r.readLine()) != null) {
       out.println(m);
       m = in.readLine();
       w.write(m, 0, m.length());
       w.newLine();
       w.flush();
     }
     w.close();
     r.close();
     c.close();
   } catch (IOException e) {
     System.err.println(e.toString());
   }
 }
  public HTTPSConnectSocket(String host, int port, String urlString) throws IOException {

    URL url = null;
    try {
      url = new URL(urlString);
    } catch (MalformedURLException me) {
      System.out.println("Malformed url");
      System.exit(1);
    }

    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    ssl = (SSLSocket) ssf.createSocket(host, port);
    ssl.startHandshake();

    // Send the CONNECT request
    ssl.getOutputStream().write(("CONNECT " + url.getFile() + " HTTP/1.0\r\n\r\n").getBytes());

    // Read the first line of the response
    DataInputStream is = new DataInputStream(ssl.getInputStream());
    String str = is.readLine();

    // Check the HTTP error code -- it should be "200" on success
    if (!str.startsWith("HTTP/1.1 200 ")) {
      if (str.startsWith("HTTP/1.1 ")) str = str.substring(9);
      throw new IOException("Proxy reports \"" + str + "\"");
    }

    // Success -- skip remaining HTTP headers
    do {
      str = is.readLine();
    } while (str.length() != 0);
  }
  private static SocketFactory getSSLSocketFactory() {
    SocketFactory sslSocketFactory;
    try {
      final TrustManager[] trustAllCerts =
          new TrustManager[] {
            new X509TrustManager() {

              @Override
              public X509Certificate[] getAcceptedIssuers() {
                return null;
              }

              @Override
              public void checkServerTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              @Override
              public void checkClientTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}
            }
          };
      final SSLContext sslContext = SSLContext.getInstance("SSL");
      sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
      // Create an ssl socket factory with our all-trusting manager
      sslSocketFactory = sslContext.getSocketFactory();
      return sslSocketFactory;
    } catch (Exception ex) {
      logger.warn(
          "Unable to build ssl socket factory without certificate validation, using default instead.",
          ex);
    }
    return SSLSocketFactory.getDefault();
  }
Example #7
0
  private void connectToServer() {
    try {
      if (config.getServerSsl()) {
        this.connect(
            config.getServerAddress(),
            config.getServerPort(),
            config.getServerPassword(),
            config.getAcceptInvalidSsl()
                ? new UtilSSLSocketFactory().trustAllCertificates().disableDiffieHellman()
                : SSLSocketFactory.getDefault());
      } else {
        this.connect(config.getServerAddress(), config.getServerPort(), config.getServerPassword());
      }

      if (config.useNickserv()) {
        this.identify(config.getNickservPassword());
      }
    } catch (IOException | IrcException ex) {
      Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }

    for (String channel : config.getChannels()) {
      this.joinChannel(channel);
    }
  }
 /**
  * Run before every test. Chooses a vin number and makes the server speak https.
  *
  * @throws Exception
  */
 @Override
 public void setUp() throws Exception {
   super.setUp();
   server = new MockWebServer();
   server.useHttps((SSLSocketFactory) SSLSocketFactory.getDefault(), true);
   collector.chooseBus("Ericsson$Vin_Num_001");
 }
Example #9
0
  /**
   * Tests opening an SSL/TLS connection to redis with a custom hostname verifier. This test should
   * fail because "127.0.0.1" does not match the certificate subject common name and there are no
   * subject alternative names in the certificate.
   */
  @Test
  public void connectWithShardInfoAndCustomHostnameVerifierByIpAddress() {
    final URI uri = URI.create("rediss://127.0.0.1:6390");
    final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    final SSLParameters sslParameters = new SSLParameters();

    HostnameVerifier hostnameVerifier = new BasicHostnameVerifier();
    JedisShardInfo shardInfo =
        new JedisShardInfo(uri, sslSocketFactory, sslParameters, hostnameVerifier);
    shardInfo.setPassword("foobared");

    Jedis jedis = new Jedis(shardInfo);
    try {
      jedis.get("foo");
      Assert.fail("The code did not throw the expected JedisConnectionException.");
    } catch (JedisConnectionException e) {
      Assert.assertEquals(
          "The JedisConnectionException does not contain the expected message.",
          "The connection to '127.0.0.1' failed ssl/tls hostname verification.",
          e.getMessage());
    }

    try {
      jedis.close();
    } catch (Throwable e1) {
      // Expected.
    }
  }
 private static SSLSocketFactory sslFactory(final boolean verify) {
   if (verify) {
     return (SSLSocketFactory) SSLSocketFactory.getDefault();
   } else {
     return (SSLSocketFactory) BlindSSLSocketFactory.getDefault();
   }
 }
Example #11
0
  private CipherTest(PeerFactory peerFactory) throws IOException {
    THREADS = Integer.parseInt(System.getProperty("numThreads", "4"));
    factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket socket = (SSLSocket) factory.createSocket();
    String[] cipherSuites = socket.getSupportedCipherSuites();
    String[] protocols = socket.getSupportedProtocols();
    //      String[] clientAuths = {null, "RSA", "DSA"};
    String[] clientAuths = {null};
    tests =
        new ArrayList<TestParameters>(cipherSuites.length * protocols.length * clientAuths.length);
    for (int i = 0; i < cipherSuites.length; i++) {
      String cipherSuite = cipherSuites[i];

      for (int j = 0; j < protocols.length; j++) {
        String protocol = protocols[j];

        if (!peerFactory.isSupported(cipherSuite, protocol)) {
          continue;
        }

        for (int k = 0; k < clientAuths.length; k++) {
          String clientAuth = clientAuths[k];
          if ((clientAuth != null) && (cipherSuite.indexOf("DH_anon") != -1)) {
            // no client with anonymous ciphersuites
            continue;
          }
          tests.add(new TestParameters(cipherSuite, protocol, clientAuth));
        }
      }
    }
    testIterator = tests.iterator();
  }
Example #12
0
 private Socket getIncommingSocket() throws IOException {
   Socket s;
   if (info.isUseSSL()) {
     SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
     s = sslsocketfactory.createSocket(info.getIncomingServerName(), info.getIncomingPort());
   } else {
     s = new Socket(info.getIncomingServerName(), info.getIncomingPort());
   }
   return s;
 }
Example #13
0
  public static void main(String args[]) throws Exception {
    //        System.setProperty("javax.net.ssl.trustStore",
    //                   "clienttrust");

    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String x = in.readLine();
    System.out.println(x);
    in.close();
  }
Example #14
0
 /**
  * ** Opens the socket connection ** @param timeoutMS open timeout in milliseconds ** @throws
  * IOException if an error occurs while creating the socket
  */
 public void openSocket(long timeoutMS) throws IOException {
   // Print.logInfo("Openning socket - " + this.host + ":" + this.port);
   if (this.useSSL) {
     if (timeoutMS > 0L) {
       this.socket = SSLSocketFactory.getDefault().createSocket(this.host, this.port);
       // this.socket = SSLSocketFactory.getDefault().createSocket();
       // this.socket.connect(new InetSocketAddress(this.host, this.port), timeoutMS);
     } else {
       this.socket = SSLSocketFactory.getDefault().createSocket(this.host, this.port);
     }
   } else {
     if (timeoutMS > 0) {
       this.socket = new Socket();
       this.socket.connect(new InetSocketAddress(this.host, this.port), (int) timeoutMS);
     } else {
       // new Socket(InetAddress.getByName(host),port)
       this.socket = new Socket(this.host, this.port);
     }
   }
 }
  public static void main(String[] args) throws Exception {
    String host = "192.168.1.191";

    SocketFactory sf = SSLSocketFactory.getDefault();
    SSLSocket sock = (SSLSocket) sf.createSocket(host, PORT);
    System.out.println("Server connected");

    InputStream rawIn = sock.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(rawIn));
    System.out.println(in.readLine());
    sock.close();
  }
 private SSLSocketFactory makeSocketFactory(
     KeyManager[] keyManagers, TrustManager[] trustManagers) {
   try {
     OpenSSLContextImpl sslContext = new OpenSSLContextImpl();
     sslContext.engineInit(keyManagers, trustManagers, null);
     sslContext.engineGetClientSessionContext().setPersistentCache(mSessionCache);
     return sslContext.engineGetSocketFactory();
   } catch (KeyManagementException e) {
     Log.wtf(TAG, e);
     return (SSLSocketFactory) SSLSocketFactory.getDefault(); // Fallback
   }
 }
Example #17
0
  private static SSLSocketFactory getFactory(boolean verify)
      throws NoSuchAlgorithmException, KeyManagementException {
    if (verify) return (SSLSocketFactory) SSLSocketFactory.getDefault();

    if (factory == null) {
      SSLContext context = SSLContext.getInstance("TLS");
      TrustManager[] managers = {new MyTrustManager()};
      context.init(null, managers, new SecureRandom());
      factory = context.getSocketFactory();
    }
    return factory;
  }
Example #18
0
  /**
   * Creates the ssl collection
   *
   * @param ip - ip of the server
   * @return
   */
  private static SSLSocket handshake(String ip) {
    try {
      SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
      SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(ip, 9996);
      String[] enabledCipherSuites = {"SSL_DH_anon_WITH_RC4_128_MD5"};
      sslsocket.setEnabledCipherSuites(enabledCipherSuites);
      return sslsocket;

    } catch (Exception exception) {
      exception.printStackTrace();
      return null;
    }
  }
 public LogentriesClient(
     boolean httpPut, boolean ssl, boolean isUsingDataHub, String server, int port) {
   if (isUsingDataHub) {
     ssl_factory = null; // DataHub does not support input over SSL for now,
     ssl_choice = false; // so SSL flag is ignored
     useDataHub = isUsingDataHub;
     dataHubServer = server;
     dataHubPort = port;
   } else {
     ssl_factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
     ssl_choice = ssl;
     http_choice = httpPut;
   }
 }
  @Test
  @SuppressWarnings("deprecation")
  public void testCopy() throws Exception {

    MongoOptions options = new MongoOptions();

    options.connectionsPerHost = 100;
    options.threadsAllowedToBlockForConnectionMultiplier = 101;
    options.maxWaitTime = 102;
    options.connectTimeout = 103;
    options.socketTimeout = 104;
    options.socketKeepAlive = true;
    options.safe = true;
    options.w = 106;
    options.wtimeout = 107;
    options.fsync = true;
    options.j = false;
    options.dbDecoderFactory = null;
    options.dbEncoderFactory = null;
    options.description = "cool";
    options.readPreference = ReadPreference.secondary();
    options.cursorFinalizerEnabled = true;
    options.socketFactory = SSLSocketFactory.getDefault();
    options.alwaysUseMBeans = true;
    options.requiredReplicaSetName = "set1";

    MongoOptions copy = options.copy();
    assertEquals(options.connectionsPerHost, copy.connectionsPerHost);
    assertEquals(
        options.threadsAllowedToBlockForConnectionMultiplier,
        copy.threadsAllowedToBlockForConnectionMultiplier);
    assertEquals(options.maxWaitTime, copy.maxWaitTime);
    assertEquals(options.connectTimeout, copy.connectTimeout);
    assertEquals(options.socketTimeout, copy.socketTimeout);
    assertEquals(options.socketKeepAlive, copy.socketKeepAlive);
    assertEquals(options.safe, copy.safe);
    assertEquals(options.w, copy.w);
    assertEquals(options.wtimeout, copy.wtimeout);
    assertEquals(options.fsync, copy.fsync);
    assertEquals(options.j, copy.j);
    assertEquals(options.dbDecoderFactory, copy.dbDecoderFactory);
    assertEquals(options.dbEncoderFactory, copy.dbEncoderFactory);
    assertEquals(options.description, copy.description);
    assertEquals(options.readPreference, copy.readPreference);
    assertEquals(options.alwaysUseMBeans, copy.alwaysUseMBeans);
    assertEquals(options.socketFactory, copy.socketFactory);
    assertEquals(options.requiredReplicaSetName, copy.requiredReplicaSetName);
  }
Example #21
0
  public static void main(String[] args) throws Exception {
    try {
      Class.forName("javax.security.auth.kerberos.KerberosPrincipal");
      System.out.println("Kerberos is present, nothing to test");
      return;
    } catch (ClassNotFoundException okay) {
    }

    // test SSLSocket
    try (Socket s = SSLSocketFactory.getDefault().createSocket()) {
      SSLSocket sslSocket = (SSLSocket) s;

      checkNotSupported(sslSocket.getSupportedCipherSuites());

      // attempt to enable each of the Kerberos cipher suites
      for (String kcs : KERBEROS_CIPHER_SUITES) {
        String[] suites = {kcs};
        try {
          sslSocket.setEnabledCipherSuites(suites);
          throw new RuntimeException(
              "SSLSocket.setEnabledCipherSuitessuites allowed "
                  + kcs
                  + " but Kerberos not supported");
        } catch (IllegalArgumentException expected) {
        }
      }
    }

    // test SSLServerSocket
    try (ServerSocket ss = SSLServerSocketFactory.getDefault().createServerSocket()) {
      SSLServerSocket sslSocket = (SSLServerSocket) ss;

      checkNotSupported(sslSocket.getSupportedCipherSuites());

      // attempt to enable each of the Kerberos cipher suites
      for (String kcs : KERBEROS_CIPHER_SUITES) {
        String[] suites = {kcs};
        try {
          sslSocket.setEnabledCipherSuites(suites);
          throw new RuntimeException(
              "SSLSocket.setEnabledCipherSuitessuites allowed "
                  + kcs
                  + " but Kerberos not supported");
        } catch (IllegalArgumentException expected) {
        }
      }
    }
  }
Example #22
0
  /** Tests opening an SSL/TLS connection to redis with a custom hostname verifier. */
  @Test
  public void connectWithShardInfoAndCustomHostnameVerifier() {
    final URI uri = URI.create("rediss://localhost:6390");
    final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    final SSLParameters sslParameters = new SSLParameters();

    HostnameVerifier hostnameVerifier = new BasicHostnameVerifier();
    JedisShardInfo shardInfo =
        new JedisShardInfo(uri, sslSocketFactory, sslParameters, hostnameVerifier);
    shardInfo.setPassword("foobared");

    Jedis jedis = new Jedis(shardInfo);
    jedis.get("foo");
    jedis.disconnect();
    jedis.close();
  }
  public void connect() throws UnknownHostException, IOException {
    if (ssl_choice) {
      if (http_choice) {
        SSLSocket s = (SSLSocket) ssl_factory.createSocket(getAddress(), getPort());
        s.setTcpNoDelay(true);
        s.startHandshake();
        socket = s;
      } else {
        socket = SSLSocketFactory.getDefault().createSocket(getAddress(), getPort());
      }
    } else {
      socket = new Socket(getAddress(), getPort());
    }

    this.stream = socket.getOutputStream();
  }
  private MongoClientOptions createOptions(
      Map<String, List<String>> optionsMap, MongoClientOptions.Builder builder) {
    for (String key : generalOptionsKeys) {
      String value = getLastValue(optionsMap, key);
      if (value == null) {
        continue;
      }

      if (key.equals("maxpoolsize")) {
        builder.connectionsPerHost(Integer.parseInt(value));
      } else if (key.equals("minpoolsize")) {
        builder.minConnectionsPerHost(Integer.parseInt(value));
      } else if (key.equals("maxidletimems")) {
        builder.maxConnectionIdleTime(Integer.parseInt(value));
      } else if (key.equals("maxlifetimems")) {
        builder.maxConnectionLifeTime(Integer.parseInt(value));
      } else if (key.equals("waitqueuemultiple")) {
        builder.threadsAllowedToBlockForConnectionMultiplier(Integer.parseInt(value));
      } else if (key.equals("waitqueuetimeoutms")) {
        builder.maxWaitTime(Integer.parseInt(value));
      } else if (key.equals("connecttimeoutms")) {
        builder.connectTimeout(Integer.parseInt(value));
      } else if (key.equals("sockettimeoutms")) {
        builder.socketTimeout(Integer.parseInt(value));
      } else if (key.equals("autoconnectretry")) {
        builder.autoConnectRetry(_parseBoolean(value));
      } else if (key.equals("replicaset")) {
        builder.requiredReplicaSetName(value);
      } else if (key.equals("ssl")) {
        if (_parseBoolean(value)) {
          builder.socketFactory(SSLSocketFactory.getDefault());
        }
      }
    }

    WriteConcern writeConcern = createWriteConcern(optionsMap);
    ReadPreference readPreference = createReadPreference(optionsMap);

    if (writeConcern != null) {
      builder.writeConcern(writeConcern);
    }
    if (readPreference != null) {
      builder.readPreference(readPreference);
    }

    return builder.build();
  }
  /**
   * Represents a single connection to a League of Legends chatserver.
   *
   * @param server The chatserver of the region you want to connect to
   * @param friendRequestPolicy Determines how new Friend requests are treated.
   * @param riotApiKey Your apiKey used to convert summonerId's to name. You can get your key here
   *     <a href="https://developer.riotgames.com/">developer .riotgames.com</a>
   * @see LolChat#setFriendRequestPolicy(FriendRequestPolicy)
   * @see LolChat#setFriendRequestListener(FriendRequestListener)
   */
  public LolChat(
      ChatServer server, FriendRequestPolicy friendRequestPolicy, RiotApiKey riotApiKey) {
    this.friendRequestPolicy = friendRequestPolicy;
    this.server = server;
    if (riotApiKey != null && server.api != null) {
      this.riotApi = RiotApi.build(riotApiKey, server);
    }
    Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
    final ConnectionConfiguration config =
        new ConnectionConfiguration(server.host, 5223, "pvp.net");
    config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
    config.setSocketFactory(SSLSocketFactory.getDefault());
    config.setCompressionEnabled(true);
    connection = new XMPPTCPConnection(config);

    addListeners();
  }
  @Test
  @SuppressWarnings("deprecation")
  public void testGetterSetters() throws Exception {

    MongoOptions options = new MongoOptions();

    options.setConnectionsPerHost(100);
    options.setThreadsAllowedToBlockForConnectionMultiplier(101);
    options.setMaxWaitTime(102);
    options.setConnectTimeout(103);
    options.setSocketTimeout(104);
    options.setSocketKeepAlive(true);
    options.setSafe(true);
    options.setW(106);
    options.setWtimeout(107);
    options.setFsync(true);
    options.setJ(false);
    options.setDbDecoderFactory(null);
    options.setDbEncoderFactory(null);
    options.setDescription("very cool");
    options.setReadPreference(ReadPreference.secondary());
    options.setSocketFactory(SSLSocketFactory.getDefault());
    options.setAlwaysUseMBeans(true);
    options.setCursorFinalizerEnabled(false);
    options.requiredReplicaSetName = "set1";

    assertEquals(options.getConnectionsPerHost(), 100);
    assertEquals(options.getThreadsAllowedToBlockForConnectionMultiplier(), 101);
    assertEquals(options.getMaxWaitTime(), 102);
    assertEquals(options.getConnectTimeout(), 103);
    assertEquals(options.getSocketTimeout(), 104);
    assertEquals(options.isSocketKeepAlive(), true);
    assertEquals(options.isSafe(), true);
    assertEquals(options.getW(), 106);
    assertEquals(options.getWtimeout(), 107);
    assertEquals(options.isFsync(), true);
    assertEquals(options.isJ(), false);
    assertEquals(options.getDbDecoderFactory(), null);
    assertEquals(options.getDbEncoderFactory(), null);
    assertEquals(options.getDescription(), "very cool");
    assertEquals(options.getReadPreference(), ReadPreference.secondary());
    assertEquals(options.isAlwaysUseMBeans(), true);
    assertEquals(options.getSocketFactory(), options.socketFactory);
    assertEquals(options.isCursorFinalizerEnabled(), false);
    assertEquals(options.getRequiredReplicaSetName(), "set1");
  }
Example #27
0
  public SimpleRawTcpClient(String hostname, int port, boolean useSsl, int bufferSize)
      throws IOException {
    addr = InetAddress.getByName(hostname);
    responseBuffer = new byte[bufferSize];

    if (useSsl) {
      SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
      conn = f.createSocket(addr, port);
      SSLSocket c = (SSLSocket) conn;
      printSocketInfo(c);
      c.startHandshake();
      SSLSession session = c.getSession();
      SessionInfo.logSessionInfo(session, "Server");
    } else {
      conn = new Socket(addr, port);
    }
  }
Example #28
0
  /**
   * Tests opening an SSL/TLS connection to redis. NOTE: This test relies on a feature that is only
   * available as of Java 7 and later. It is commented out but not removed in case support for Java
   * 6 is dropped or we find a way to have the CI run a specific set of tests on Java 7 and above.
   */
  @Test
  public void connectWithShardInfo() throws Exception {
    final URI uri = URI.create("rediss://localhost:6390");
    final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    // These SSL parameters ensure that we use the same hostname verifier used
    // for HTTPS.
    // Note: this options is only available in Java 7.
    final SSLParameters sslParameters = new SSLParameters();
    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");

    JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, null);
    shardInfo.setPassword("foobared");

    Jedis jedis = new Jedis(shardInfo);
    jedis.get("foo");
    jedis.disconnect();
    jedis.close();
  }
Example #29
0
  public synchronized void open(
      String host, int port, String username, String password, boolean ssl)
      throws IOException, ProtocolException {
    if (username == null || password == null) {
      Authenticate auth = getAuthenticator();

      if (auth != null) {
        if (username == null) {
          User user = auth.getUser(host, "pop3", null);

          if (user != null) {
            username = user.getUsername();
            password = user.getPassword();
          }
        } else {
          password = auth.getPassword(host, "pop3", username);
        }
      }
    }

    Socket socket =
        ssl ? SSLSocketFactory.getDefault().createSocket(host, port) : new Socket(host, port);

    in = new ReadLineInputStream(socket.getInputStream());
    out = socket.getOutputStream();

    checkLine(readLine());
    sendCommand("user " + username);
    sendCommand("pass " + password);

    String s = sendCommand("stat");

    try {
      messages = new Message[getNumberOfMessages(s)];
    } catch (NumberFormatException e) {
      close();
      throw e;
    }

    for (int i = 0; i < messages.length; ++i) {
      messages[i] = new Message(i + 1);
    }
  }
  @Override
  public void execute(String commandString, Session sess) throws IOException {
    if (!commandString.trim().toUpperCase().equals(this.getName())) {
      sess.sendResponse("501 Syntax error (no parameters allowed)");
      return;
    }

    try {
      Socket socket = sess.getSocket();
      if (socket instanceof SSLSocket) {
        sess.sendResponse("454 TLS not available due to temporary reason: TLS already active");
        return;
      }

      sess.sendResponse("220 Ready to start TLS");

      InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
      SSLSocketFactory sf = ((SSLSocketFactory) SSLSocketFactory.getDefault());
      SSLSocket s =
          (SSLSocket)
              (sf.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));

      // we are a server
      s.setUseClientMode(false);

      // allow all supported cipher suites
      s.setEnabledCipherSuites(s.getSupportedCipherSuites());

      s.startHandshake();

      sess.setSocket(s);
      sess.resetMessageState(); // clean slate
    } catch (SSLHandshakeException ex) {
      // "no cipher suites in common" is common and puts a lot of crap in the logs.
      // This will at least limit it to a single WARN line and not a whole stacktrace.
      // Unfortunately it might catch some other types of SSLHandshakeException (if
      // in fact other types exist), but oh well.
      log.warn("startTLS() failed: " + ex);
    } catch (IOException ex) {
      log.warn("startTLS() failed: " + ex.getMessage(), ex);
    }
  }