Ejemplo n.º 1
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();
  }
Ejemplo n.º 2
0
  /**
   * SSL/TLS negotiation. Acquires an SSL socket of a control connection and carries out handshake
   * processing.
   *
   * @throws IOException If server negotiation fails
   */
  protected void sslNegotiation() throws IOException {
    plainSocket = _socket_;
    initSslContext();

    SSLSocketFactory ssf = context.getSocketFactory();
    String ip = _socket_.getInetAddress().getHostAddress();
    int port = _socket_.getPort();
    SSLSocket socket = (SSLSocket) ssf.createSocket(_socket_, ip, port, false);
    socket.setEnableSessionCreation(isCreation);
    socket.setUseClientMode(isClientMode);
    // server mode
    if (!isClientMode) {
      socket.setNeedClientAuth(isNeedClientAuth);
      socket.setWantClientAuth(isWantClientAuth);
    }

    if (protocols != null) {
      socket.setEnabledProtocols(protocols);
    }
    if (suites != null) {
      socket.setEnabledCipherSuites(suites);
    }
    socket.startHandshake();

    _socket_ = socket;
    _controlInput_ =
        new BufferedReader(new InputStreamReader(socket.getInputStream(), getControlEncoding()));
    _controlOutput_ =
        new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), getControlEncoding()));
  }
Ejemplo n.º 3
0
 private void connect() throws IOException {
   Socket tmp = null;
   try {
     tmp = socketFactory.createSocket();
     tmp.setTcpNoDelay(tcpNoDelay);
     if (sendBuffer > 0) tmp.setSendBufferSize(sendBuffer);
     tmp.bind(bindaddr);
     if (tmp instanceof SSLSocket) {
       SSLSocket sslsock = (SSLSocket) tmp;
       sslsock.setEnabledProtocols(new String[] {tlsProtocol});
       sslsock.setEnabledCipherSuites(tlsCiphers);
     }
     tmp.connect(addr, tcpConnectTimeout);
     if (tmp instanceof SSLSocket) {
       SSLSocket sslsock = (SSLSocket) tmp;
       sslsock.startHandshake();
     }
     sockout = new BufferedOutputStream(tmp.getOutputStream());
     sock = tmp;
     tmp = null;
   } finally {
     if (tmp != null)
       try {
         tmp.close();
       } catch (Exception ignore) {
       }
   }
 }
Ejemplo n.º 4
0
  /**
   * Returns a socket of the data connection. Wrapped as an {@link SSLSocket}, which carries out
   * handshake processing.
   *
   * @param command The textual representation of the FTP command to send.
   * @param arg The arguments to the FTP command. If this parameter is set to null, then the command
   *     is sent with no arguments.
   * @return corresponding to the established data connection. Null is returned if an FTP protocol
   *     error is reported at any point during the establishment and initialization of the
   *     connection.
   * @throws IOException If there is any problem with the connection.
   * @see FTPClient#_openDataConnection_(int, String)
   * @since 3.2
   */
  @Override
  protected Socket _openDataConnection_(String command, String arg) throws IOException {
    Socket socket = super._openDataConnection_(command, arg);
    _prepareDataSocket_(socket);
    if (socket instanceof SSLSocket) {
      SSLSocket sslSocket = (SSLSocket) socket;

      sslSocket.setUseClientMode(isClientMode);
      sslSocket.setEnableSessionCreation(isCreation);

      // server mode
      if (!isClientMode) {
        sslSocket.setNeedClientAuth(isNeedClientAuth);
        sslSocket.setWantClientAuth(isWantClientAuth);
      }
      if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
      }
      if (protocols != null) {
        sslSocket.setEnabledProtocols(protocols);
      }
      sslSocket.startHandshake();
    }

    return socket;
  }
Ejemplo n.º 5
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();
   }
 }
 public Socket createSocket(String host, int port) throws IOException {
   Socket s = this.factory.createSocket(host, port);
   if (s instanceof SSLSocket) {
     SSLSocket ssl = (SSLSocket) s;
     ssl.setEnabledCipherSuites(this.getNoAuthCiperSuites(ssl.getSupportedCipherSuites()));
   }
   return s;
 }
Ejemplo n.º 7
0
 private static void hardenSocket(SSLSocket sock) {
   if (ENABLED_CIPHERS != null) {
     sock.setEnabledCipherSuites(ENABLED_CIPHERS);
   }
   if (ENABLED_PROTOCOLS != null) {
     sock.setEnabledProtocols(ENABLED_PROTOCOLS);
   }
 }
 public Socket createSocket(
     InetAddress address, int port, InetAddress clientAddress, int clientPort) throws IOException {
   Socket s = this.factory.createSocket(address, port, clientAddress, clientPort);
   if (s instanceof SSLSocket) {
     SSLSocket ssl = (SSLSocket) s;
     ssl.setEnabledCipherSuites(this.getNoAuthCiperSuites(ssl.getSupportedCipherSuites()));
   }
   return s;
 }
Ejemplo n.º 9
0
  /** Applies this spec to {@code sslSocket}. */
  void apply(SSLSocket sslSocket, boolean isFallback) {
    ConnectionSpec specToApply = supportedSpec(sslSocket, isFallback);

    if (specToApply.tlsVersions != null) {
      sslSocket.setEnabledProtocols(specToApply.tlsVersions);
    }
    if (specToApply.cipherSuites != null) {
      sslSocket.setEnabledCipherSuites(specToApply.cipherSuites);
    }
  }
Ejemplo n.º 10
0
  public void afterConnect() throws IOException, UnknownHostException {
    if (!isCachedConnection()) {
      SSLSocket s = null;
      SSLSocketFactory factory;
      factory = sslSocketFactory;
      try {
        if (!(serverSocket instanceof SSLSocket)) {
          s = (SSLSocket) factory.createSocket(serverSocket, host, port, true);
        } else {
          s = (SSLSocket) serverSocket;
        }
      } catch (IOException ex) {
        // If we fail to connect through the tunnel, try it
        // locally, as a last resort.  If this doesn't work,
        // throw the original exception.
        try {
          s = (SSLSocket) factory.createSocket(host, port);
        } catch (IOException ignored) {
          throw ex;
        }
      }

      SSLSocketFactoryImpl.checkCreate(s);

      //
      // Force handshaking, so that we get any authentication.
      // Register a handshake callback so our session state tracks any
      // later session renegotiations.
      //
      String[] protocols = getProtocols();
      String[] ciphers = getCipherSuites();
      if (protocols != null) s.setEnabledProtocols(protocols);
      if (ciphers != null) s.setEnabledCipherSuites(ciphers);
      s.addHandshakeCompletedListener(this);
      s.startHandshake();
      session = s.getSession();
      // change the serverSocket and serverOutput
      serverSocket = s;
      try {
        serverOutput =
            new PrintStream(
                new BufferedOutputStream(serverSocket.getOutputStream()), false, encoding);
      } catch (UnsupportedEncodingException e) {
        throw new InternalError(encoding + " encoding not found");
      }

      // check URL spoofing
      checkURLSpoofing(hv);
    } else {
      // if we are reusing a cached https session,
      // we don't need to do handshaking etc. But we do need to
      // set the ssl session
      session = ((SSLSocket) serverSocket).getSession();
    }
  }
Ejemplo n.º 11
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;
    }
  }
Ejemplo n.º 12
0
  @Override
  public void handshake(Socket sock) throws IOException {
    // We do getSession instead of startHandshake() so we can call this multiple times
    SSLSession session = ((SSLSocket) sock).getSession();
    if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL"))
      throw new IOException(
          "SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL");

    if (!allowUnsafeLegacyRenegotiation && !rfc5746Supported) {
      // Prevent further handshakes by removing all cipher suites
      ((SSLSocket) sock).setEnabledCipherSuites(new String[0]);
    }
  }
Ejemplo n.º 13
0
 // Server loop
 private static void serverLoop() throws Exception {
   // Check if client is connected
   if (hidOut == null && !busy) {
     // Busy
     busy = true;
     // Notify
     // System.out.println("Awaiting HID client...");
     // No client is connected - accept connection
     SSLSocket client = (SSLSocket) server.accept();
     // Require auth
     // client.setNeedClientAuth(true);
     // Enable ciphers
     client.setEnabledCipherSuites(client.getEnabledCipherSuites());
     // Add a handshake listener
     client.addHandshakeCompletedListener(
         new HandshakeCompletedListener() {
           @Override
           public void handshakeCompleted(HandshakeCompletedEvent event) {
             handleClient(event);
           }
         });
     // Start handshake
     client.startHandshake();
   } else {
     // Check client status
     try {
       // System.out.print("Checking HID client status...");
       if (!connected) {
         // System.out.println(Color.YELLOW + " Connecting..." +
         //		Color.RESET);
         return;
       }
       // Send a ping to the client
       hidOut.write(0x01);
       // System.out.println(Color.GREEN + " Connected!" + Color.RESET);
       Thread.sleep(1000);
     } catch (Exception e) {
       // System.out.println(Color.RED + " Not Connected!" + Color.RESET);
       // Reset variables
       hidClient = null;
       hidOut = null;
       busy = false;
       connected = false;
       // Reset display
       Display.readyMessage = Display.defaultReadyMessage;
       Display.ready();
       // Notify
       System.out.println(Color.BLUE + "NOTICE: " + Color.RESET + "HID client has disconnected");
     }
   }
 }
 /*     */ public Socket createSocket(String paramString, int paramInt)
     /*     */ throws IOException
       /*     */ {
   /* 117 */ SocketFactory localSocketFactory = getDefaultClientSocketFactory();
   /*     */
   /* 120 */ SSLSocket localSSLSocket =
       (SSLSocket) localSocketFactory.createSocket(paramString, paramInt);
   /*     */
   /* 124 */ String str = System.getProperty("javax.rmi.ssl.client.enabledCipherSuites");
   /*     */
   /* 126 */ if (str != null) {
     /* 127 */ localObject = new StringTokenizer(str, ",");
     /* 128 */ int i = ((StringTokenizer) localObject).countTokens();
     /* 129 */ String[] arrayOfString1 = new String[i];
     /* 130 */ for (int k = 0; k < i; k++)
       /* 131 */ arrayOfString1[k] = ((StringTokenizer) localObject).nextToken();
     /*     */ try
     /*     */ {
       /* 134 */ localSSLSocket.setEnabledCipherSuites(arrayOfString1);
       /*     */ } catch (IllegalArgumentException localIllegalArgumentException1) {
       /* 136 */ throw ((IOException)
           new IOException(localIllegalArgumentException1.getMessage())
               .initCause(localIllegalArgumentException1));
       /*     */ }
     /*     */
     /*     */ }
   /*     */
   /* 142 */ Object localObject = System.getProperty("javax.rmi.ssl.client.enabledProtocols");
   /*     */
   /* 144 */ if (localObject != null) {
     /* 145 */ StringTokenizer localStringTokenizer =
         new StringTokenizer((String) localObject, ",");
     /* 146 */ int j = localStringTokenizer.countTokens();
     /* 147 */ String[] arrayOfString2 = new String[j];
     /* 148 */ for (int m = 0; m < j; m++)
       /* 149 */ arrayOfString2[m] = localStringTokenizer.nextToken();
     /*     */ try
     /*     */ {
       /* 152 */ localSSLSocket.setEnabledProtocols(arrayOfString2);
       /*     */ } catch (IllegalArgumentException localIllegalArgumentException2) {
       /* 154 */ throw ((IOException)
           new IOException(localIllegalArgumentException2.getMessage())
               .initCause(localIllegalArgumentException2));
       /*     */ }
     /*     */
     /*     */ }
   /*     */
   /* 160 */ return localSSLSocket;
   /*     */ }
Ejemplo n.º 15
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) {
        }
      }
    }
  }
Ejemplo n.º 16
0
  public SSLSocket clientNoHandshake(String hostName, int hostPort, boolean useClientCert)
      throws IOException {

    SSLSocket socket = null;
    // SSL Strong Cipher Hack

    // SSL Strong Cipher Hack

    if (useClientCert) {
      socket = (SSLSocket) clientSSLSockCertFactory.createSocket(hostName, hostPort);
    } else {
      socket = (SSLSocket) clientSSLSockFactory.createSocket(hostName, hostPort);
    }
    socket.setEnabledProtocols(new String[] {"SSLv3"});
    socket.setEnabledCipherSuites(new String[] {"SSL_RSA_WITH_DES_CBC_SHA"});

    return socket;
  }
Ejemplo n.º 17
0
  @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);
    }
  }
Ejemplo n.º 18
0
 public void supportTlsIntolerantServer(SSLSocket socket) {
   String fallbackScsv = "TLS_FALLBACK_SCSV";
   boolean socketSupportsFallbackScsv = false;
   String[] supportedCipherSuites = socket.getSupportedCipherSuites();
   for (int i = supportedCipherSuites.length - 1; i >= 0; i--) {
     if ("TLS_FALLBACK_SCSV".equals(supportedCipherSuites[i])) {
       socketSupportsFallbackScsv = true;
       break;
     }
   }
   if (socketSupportsFallbackScsv) {
     String[] enabledCipherSuites = socket.getEnabledCipherSuites();
     String[] newEnabledCipherSuites = new String[(enabledCipherSuites.length + 1)];
     System.arraycopy(
         enabledCipherSuites, 0, newEnabledCipherSuites, 0, enabledCipherSuites.length);
     newEnabledCipherSuites[newEnabledCipherSuites.length - 1] = "TLS_FALLBACK_SCSV";
     socket.setEnabledCipherSuites(newEnabledCipherSuites);
   }
   socket.setEnabledProtocols(new String[] {"SSLv3"});
 }
Ejemplo n.º 19
0
  @Test
  public void tls_defaultCiphers_withFallbackIndicator() throws Exception {
    ConnectionSpec tlsSpec =
        new ConnectionSpec.Builder(true)
            .tlsVersions(TlsVersion.TLS_1_2)
            .supportsTlsExtensions(false)
            .build();

    SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    socket.setEnabledCipherSuites(
        new String[] {
          CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
          CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
        });
    socket.setEnabledProtocols(
        new String[] {
          TlsVersion.TLS_1_2.javaName, TlsVersion.TLS_1_1.javaName,
        });

    Route route =
        new Route(
            HTTPS_ADDRESS,
            PROXY,
            INET_SOCKET_ADDRESS,
            tlsSpec,
            true /* shouldSendTlsFallbackIndicator */);
    tlsSpec.apply(socket, route);

    assertEquals(createSet(TlsVersion.TLS_1_2.javaName), createSet(socket.getEnabledProtocols()));

    Set<String> expectedCipherSet =
        createSet(
            CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
            CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName);
    if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
      expectedCipherSet.add("TLS_FALLBACK_SCSV");
    }
    assertEquals(expectedCipherSet, expectedCipherSet);
  }
  /**
   * Discover if the desired service is available at a specified host.
   *
   * @param serviceProvider address of the service provider.
   * @throws FederationServiceDiscoveryFailed if the required service is unavailable on the
   *     specified host
   * @return an valid instance of FederationRequest that can be consumed by a valid instance of this
   *     calss
   */
  @Override
  public FederationRequest discover(InetAddress serviceProvider)
      throws FederationServiceDiscoveryFailed {
    try {
      // first establish a connection
      int port = FederationService.getInstance().getFederatingPort();

      Socket sock = new Socket(serviceProvider, port);
      SSLSocketFactory sockFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
      SSLSocket federatingSocket =
          (SSLSocket) sockFactory.createSocket(sock, serviceProvider.getHostAddress(), port, true);
      SSLServerSocketFactory serverFactory =
          (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
      federatingSocket.setEnabledCipherSuites(serverFactory.getSupportedCipherSuites());

      // next check if the required service is provided
      BufferedWriter writer =
          new BufferedWriter(new OutputStreamWriter(federatingSocket.getOutputStream()));
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(federatingSocket.getInputStream()));
      writer.write(FederationRequestType.VOICE_TALK.toString() + '\n');
      writer.flush();

      String responce = reader.readLine();
      if (FederationServiceMessageCodes.valueOf(responce)
          != FederationServiceMessageCodes.SERVICE_AVAILABLE) {
        throw new IOException("Unexpected responce: " + responce);
      } // end if

      // form the federation request object and send the stuff, if the
      // required service is found
      return new FederationRequest(
          federatingSocket, reader, writer, FederationRequestType.VOICE_TALK);
    } catch (IOException ioe) {
      throw new FederationServiceDiscoveryFailed("Error while discovery: " + ioe.toString());
    } // end of try .. catch block
  }
Ejemplo n.º 21
0
  /**
   * Prepares a TLS/SSL connection socket by: - setting reasonable TLS protocol versions - setting
   * reasonable cipher suites (if required)
   *
   * @param socket unconnected SSLSocket to prepare
   */
  private void setTlsParameters(SSLSocket socket) {
    // Android 5.0+ (API level21) provides reasonable default settings
    // but it still allows SSLv3
    // https://developer.android.com/about/versions/android-5.0-changes.html#ssl

    /* set reasonable protocol versions */
    // - enable all supported protocols (enables TLSv1.1 and TLSv1.2 on Android <5.0)
    // - remove all SSL versions (especially SSLv3) because they're insecure now
    final List<String> protocols = new LinkedList<String>();
    for (String protocol : socket.getSupportedProtocols()) {
      if (!protocol.toUpperCase().contains("SSL")) {
        protocols.add(protocol);
      }
    }
    Log.v(TAG, "Setting allowed TLS protocols: " + TextUtils.join(", ", protocols));
    socket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));

    /* set reasonable cipher suites */
    if (Build.VERSION.SDK_INT < VERSION_CODES_LOLLIPOP) {
      // choose secure cipher suites

      final List<String> availableCiphers = Arrays.asList(socket.getSupportedCipherSuites());

      // preferred ciphers = allowed Ciphers \ availableCiphers
      final Set<String> preferredCiphers = new HashSet<String>(ALLOWED_CIPHERS);
      preferredCiphers.retainAll(availableCiphers);

      // add enabled ciphers to preferred ciphers
      // for maximum security, preferred ciphers should *replace* enabled ciphers,
      // but for the security level of ACRA, disabling of insecure
      // ciphers should be a server-side task
      preferredCiphers.addAll(Arrays.asList(socket.getEnabledCipherSuites()));

      Log.v(TAG, "Setting allowed TLS ciphers: " + TextUtils.join(", ", preferredCiphers));
      socket.setEnabledCipherSuites(preferredCiphers.toArray(new String[preferredCiphers.size()]));
    }
  }
  /**
   * Create an SSL socket at the specified host and port.
   *
   * @param the host
   * @param the port
   * @return the socket.
   */
  private Socket createSSLSocket(String host, int port) throws IOException {

    SSLSocket socket = null;
    SSLSocketFactory factory = null;
    try {
      // get socketfactory+sanity check
      // clientSslInfo is never null
      factory = clientSslInfo.getContext().getSocketFactory();

      if (_logger.isLoggable(Level.FINE)) {
        _logger.log(Level.FINE, "Creating SSL Socket for host:" + host + " port:" + port);
      }
      String[] ssl3TlsCiphers = clientSslInfo.getSsl3TlsCiphers();
      String[] ssl2Ciphers = clientSslInfo.getSsl2Ciphers();
      String[] clientCiphers = null;
      if (ssl3TlsCiphers != null || ssl2Ciphers != null) {
        String[] socketCiphers = factory.getDefaultCipherSuites();
        clientCiphers = mergeCiphers(socketCiphers, ssl3TlsCiphers, ssl2Ciphers);
      }

      socket = (SSLSocket) factory.createSocket(host, port);
      if (clientCiphers != null) {
        socket.setEnabledCipherSuites(clientCiphers);
      }
    } catch (Exception e) {
      if (_logger.isLoggable(Level.FINE)) {
        _logger.log(
            Level.FINE, "iiop.createsocket_exception", new Object[] {host, String.valueOf(port)});
        _logger.log(Level.FINE, "", e);
      }
      IOException e2 =
          new IOException("Error opening SSL socket to host=" + host + " port=" + port);
      e2.initCause(e);
      throw e2;
    }
    return socket;
  }
Ejemplo n.º 23
0
  /**
   * SSL/TLS negotiation. Acquires an SSL socket of a connection and carries out handshake
   * processing.
   *
   * @throws java.io.IOException If server negotiation fails.
   */
  private void performSSLNegotiation() throws IOException {
    initSSLContext();

    SSLSocketFactory ssf = context.getSocketFactory();
    String ip = getRemoteAddress().getHostAddress();
    int port = getRemotePort();
    SSLSocket socket = (SSLSocket) ssf.createSocket(_socket_, ip, port, true);
    socket.setEnableSessionCreation(true);
    socket.setUseClientMode(true);

    if (protocols != null) {
      socket.setEnabledProtocols(protocols);
    }
    if (suites != null) {
      socket.setEnabledCipherSuites(suites);
    }
    socket.startHandshake();

    _socket_ = socket;
    _input_ = socket.getInputStream();
    _output_ = socket.getOutputStream();
    _reader = new CRLFLineReader(new InputStreamReader(_input_, encoding));
    _writer = new BufferedWriter(new OutputStreamWriter(_output_, encoding));
  }
Ejemplo n.º 24
0
  /** @return {@link DefaultHttpClient} instance. */
  private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
      SchemeSocketFactory ssf = null;
      if (props.getProtocol().equals("https")) {
        TrustManager trustManager =
            new X509TrustManager() {
              public void checkClientTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

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

              public X509Certificate[] getAcceptedIssuers() {
                return null;
              }
            };
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] {trustManager}, null);
        ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SSLSocket socket = (SSLSocket) ssf.createSocket(null);
        socket.setEnabledCipherSuites(new String[] {"SSL_RSA_WITH_RC4_128_MD5"});
      } else {
        ssf = PlainSocketFactory.getSocketFactory();
      }
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
      PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
      httpclient = new DefaultHttpClient(ccm);
      host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
      context = new BasicHttpContext();
      // Http params
      httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout());
      int maxConnections = props.getMaxConnections();
      if (maxConnections != 0) {
        ccm.setMaxTotal(maxConnections);
        ccm.setDefaultMaxPerRoute(maxConnections);
      }
      if (props.getProxyHost() != null) {
        HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      // basic authentication
      if (props.getUsername() != null && props.getPassword() != null) {
        httpclient
            .getCredentialsProvider()
            .setCredentials(
                new AuthScope(props.getHost(), props.getPort()),
                new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
        props.clearPassword();
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
      }
      // request interceptor
      httpclient.addRequestInterceptor(
          new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                throws IOException {
              if (log.isInfoEnabled()) {
                RequestLine requestLine = request.getRequestLine();
                try {
                  log.info(
                      ">> "
                          + (new StringBuilder())
                              .append(">> ")
                              .append(requestLine.getMethod())
                              .append(" ")
                              .append(urlCodec.decode(requestLine.getUri()))
                              .toString());
                } catch (DecoderException e) {
                  log.error(e, e);
                }
              }
            }
          });
      // response interceptor
      httpclient.addResponseInterceptor(
          new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context)
                throws IOException {
              validate(response);
              if (log.isInfoEnabled())
                log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
          });
    } catch (Exception e) {
      log.error("Error Creating HTTP client. " + e.getMessage());
      throw new IllegalStateException(e);
    }
    return httpclient;
  }
 public void setEnabledCipherSuites(final String[] suites) {
   delegate.setEnabledCipherSuites(suites);
 }