Exemple #1
0
  public static void main(String[] args) throws IOException {

    System.out.println("opening a secure socket");

    SSLServerSocketFactory secSocketFactory =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket secSocket = (SSLServerSocket) secSocketFactory.createServerSocket(portNo);

    String[] enabledCipherSuites = {"SSL_DH_anon_WITH_RC4_128_MD5"};
    secSocket.setEnabledCipherSuites(enabledCipherSuites);

    System.out.println("Listening on port no: " + portNo);
    SSLSocket socket = (SSLSocket) secSocket.accept();

    System.out.println("Got a connection from: " + socket.getInetAddress().toString());
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    String line = in.readLine();
    while (line != null) {
      System.out.println(line);
      line = in.readLine();
    }

    out.close();
    in.close();
    socket.close();
    secSocket.close();
  }
Exemple #2
0
  // Method for creating a socket
  private static SSLServerSocket createSecureSocket() throws Exception {
    // Generate a generic server
    SSLServerSocket server =
        (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket(2877);
    // Enable ciphers
    server.setEnabledCipherSuites(server.getSupportedCipherSuites());
    // Return the socket
    return server;

    /*//Key password and file
    char[] keyPass = "******".toCharArray();
    InputStream keyStream = HID.class.getResourceAsStream(
    		"/com/arkazex/frc2877/signin/ssl.key");

    //Load the key store
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStream, keyPass);
    //Initialize the key manager factory
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
    		KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyPass);
    //Get the key managers
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    //Initialize the SSL context
    SSLContext sslContext = SSLContext.getDefault();
    sslContext.init(keyManagers, null, new SecureRandom());
    //Get the socket factory
    SSLServerSocketFactory factory = sslContext.getServerSocketFactory();

    //Get the socket
    return (SSLServerSocket) factory.createServerSocket(2877); */
  }
 public void testSetEnabledCipherSuitesAffectsGetter() throws Exception {
   SSLServerSocket socket =
       (SSLServerSocket) SSLServerSocketFactory.getDefault().createServerSocket();
   String[] cipherSuites = new String[] {socket.getSupportedCipherSuites()[0]};
   socket.setEnabledCipherSuites(cipherSuites);
   assertEquals(Arrays.asList(cipherSuites), Arrays.asList(socket.getEnabledCipherSuites()));
 }
  /**
   * Create an SSL server socket at the specified InetSocketAddress. If the type is SSL_MUTUALAUTH
   * then SSL client authentication is requested.
   */
  private ServerSocket createSSLServerSocket(String type, InetSocketAddress inetSocketAddress)
      throws IOException {

    if (inetSocketAddress == null) {
      throw new IOException(getFormatMessage("iiop.invalid_sslserverport", new Object[] {null}));
    }
    int port = inetSocketAddress.getPort();
    Integer iport = new Integer(port);
    SSLInfo sslInfo = (SSLInfo) portToSSLInfo.get(iport);
    if (sslInfo == null) {
      throw new IOException(getFormatMessage("iiop.invalid_sslserverport", new Object[] {iport}));
    }
    SSLServerSocketFactory ssf = sslInfo.getContext().getServerSocketFactory();
    String[] ssl3TlsCiphers = sslInfo.getSsl3TlsCiphers();
    String[] ssl2Ciphers = sslInfo.getSsl2Ciphers();
    String[] ciphers = null;
    if (ssl3TlsCiphers != null || ssl2Ciphers != null) {
      String[] socketCiphers = ssf.getDefaultCipherSuites();
      ciphers = mergeCiphers(socketCiphers, ssl3TlsCiphers, ssl2Ciphers);
    }

    String cs[] = null;

    if (_logger.isLoggable(Level.FINE)) {
      cs = ssf.getSupportedCipherSuites();
      for (int i = 0; i < cs.length; ++i) {
        _logger.log(Level.FINE, "Cipher Suite: " + cs[i]);
      }
    }
    ServerSocket ss = null;
    try {
      // bugfix for 6349541
      // specify the ip address to bind to, 50 is the default used
      // by the ssf implementation when only the port is specified
      ss = ssf.createServerSocket(port, BACKLOG, inetSocketAddress.getAddress());
      if (ciphers != null) {
        ((SSLServerSocket) ss).setEnabledCipherSuites(ciphers);
      }
    } catch (IOException e) {
      _logger.log(
          Level.SEVERE, "iiop.createsocket_exception", new Object[] {type, String.valueOf(port)});
      _logger.log(Level.SEVERE, "", e);
      throw e;
    }

    try {
      if (type.equals(SSL_MUTUALAUTH)) {
        _logger.log(Level.FINE, "Setting Mutual auth");
        ((SSLServerSocket) ss).setNeedClientAuth(true);
      }
    } catch (Exception e) {
      _logger.log(Level.SEVERE, "iiop.cipher_exception", e);
      throw new IOException(e.getMessage());
    }
    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(Level.FINE, "Created server socket:" + ss);
    }
    return ss;
  }
  /**
   * Configures the given SSL server socket with the requested cipher suites, protocol versions, and
   * need for client authentication
   */
  private void initServerSocket(ServerSocket ssocket) {

    SSLServerSocket socket = (SSLServerSocket) ssocket;

    socket.setEnabledCipherSuites(enabledCiphers);
    socket.setEnabledProtocols(enabledProtocols);

    // we don't know if client auth is needed -
    // after parsing the request we may re-handshake
    configureClientAuth(socket);
    configureUseServerCipherSuitesOrder(socket);
  }
  public void go() throws Exception {
    // Create a SSLServerSocketFactory with configured Key Store
    SSLServerSocketFactory socketFac = createServerSocketFactory();

    // Create a server socket to use
    SSLServerSocket serverSocket = (SSLServerSocket) socketFac.createServerSocket(0, 0);

    // Configure the server socket with a cipher suite (optional)
    serverSocket.setEnabledCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});

    // Wait for a connection from a client
    serverSocket.accept();
  }
Exemple #7
0
  JSSEServer(CipherTest cipherTest) throws Exception {
    super(cipherTest);
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(
        new KeyManager[] {cipherTest.keyManager},
        new TrustManager[] {cipherTest.trustManager},
        cipherTest.secureRandom);

    SSLServerSocketFactory factory =
        (SSLServerSocketFactory) serverContext.getServerSocketFactory();
    serverSocket = (SSLServerSocket) factory.createServerSocket(cipherTest.serverPort);
    cipherTest.serverPort = serverSocket.getLocalPort();
    serverSocket.setEnabledCipherSuites(factory.getSupportedCipherSuites());
    serverSocket.setWantClientAuth(true);
  }
  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) {
        }
      }
    }
  }
  @Override
  public void run() {
    SSLServerSocketFactory sslserversocketfactory =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslserversocket;
    try {
      System.out.println("Desktop starting at port " + PORT);
      sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket();
      // certificate is made with: "keytool -genkey keystore -keyalg RSA"
      // this below is a 'hack' (the hack was adding all cipher suites, this is the only one we need
      sslserversocket.setEnabledCipherSuites(new String[] {"SSL_DH_anon_WITH_3DES_EDE_CBC_SHA"});

      sslserversocket.bind(new InetSocketAddress(localhost, PORT));

      SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();

      InputStream inputstream = sslsocket.getInputStream();
      OutputStream outputstream = sslsocket.getOutputStream();

      outgoingSerial = new ObjectOutputStream(outputstream);
      incomingSerial =
          new ObjectInputStream(inputstream) {
            //    			@Override
            //				public Object readObject(){
            //
            //    			}
          };
    } catch (IOException e) {
      e.printStackTrace();
    }
    sendNewTicketType();
    //		executor.scheduleAtFixedRate(new Runnable() {
    //
    //			@Override
    //			public void run() {
    while (true) {
      waitForMessages();
    }
    //				System.out.println("are we finished?");
    //
    //			}
    //		}, 0, 50, TimeUnit.MILLISECONDS);

    // in the rest of the lifetime...

  }
    private void doQRPCGTest(boolean sendTLS, boolean settingOn, boolean listenTLS) throws Exception {
        if(settingOn)
            networkManagerStub.setOutgoingTLSEnabled(true);
        
    	setAccepted(false);
        BlockingConnectionUtils.drain(testUP[0]);

        // make sure leaf is sharing
        assertEquals(2, gnutellaFileView.size());
        assertEquals(1, connectionManager.getNumConnections());

        // send a query that should be answered
        QueryRequest query = queryRequestFactory.createQueryRequest(GUID.makeGuid(), (byte) 1,
                "berkeley", null, null, null, false, Network.UNKNOWN, false, 0);
        testUP[0].send(query);
        testUP[0].flush();

        // await a response
        Message m;
        do {
            m = testUP[0].receive(TIMEOUT);
        } while (!(m instanceof QueryReply));

        // confirm it has proxy info
        QueryReply reply = (QueryReply) m;
        assertNotNull(reply.getPushProxies());

        // check out PushProxy info
        Set proxies = reply.getPushProxies();
        assertEquals(1, proxies.size());
        Iterator iter = proxies.iterator();
        IpPort ppi = (IpPort) iter.next();
        assertEquals(ppi.getPort(), 6355);
        assertTrue(ppi.getInetAddress().equals(testUP[0].getInetAddress()));

        // set up a ServerSocket to get give on
        ServerSocket ss;
        if(listenTLS) {
            SSLContext context = SSLUtils.getTLSContext();
            SSLServerSocket sslServer = (SSLServerSocket)context.getServerSocketFactory().createServerSocket();
            sslServer.setNeedClientAuth(false);
            sslServer.setWantClientAuth(false);
            sslServer.setEnabledCipherSuites(new String[] {"TLS_DH_anon_WITH_AES_128_CBC_SHA"});
            ss = sslServer;
        } else {
            ss = new ServerSocket();
        }

        try {
            ss.setReuseAddress(true);        
            ss.setSoTimeout(TIMEOUT);
            ss.bind(new InetSocketAddress(9000));
            // test that the client responds to a PushRequest
            PushRequest pr = new PushRequestImpl(GUID.makeGuid(), (byte) 1, 
                                             applicationServices.getMyGUID(),
                                             0, 
                                             InetAddress.getLocalHost().getAddress(),
                                             9000,
                                             Network.TCP,
                                             sendTLS);

            // send the PR off
            testUP[0].send(pr);
            testUP[0].flush();

            // we should get a incoming GIV
            Socket givSock = ss.accept();
            try {
                assertNotNull(givSock);

                // start reading and confirming the HTTP request
                String currLine;
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(givSock.getInputStream()));

                // confirm a GIV
                currLine = reader.readLine();
                GUID guid = new GUID(
                        applicationServices.getMyGUID());
                String givLine = "GIV 0:" + guid.toHexString();
                assertTrue(currLine.startsWith(givLine));
            } finally {
                givSock.close();
            }
        } finally {
            ss.close();
        }
    }
 public void setEnabledCipherSuites(String[] suites) {
   s.setEnabledCipherSuites(suites);
 }
Exemple #12
0
  public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
      throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
          UnrecoverableKeyException, KeyManagementException, IOException {
    keepAlive = !noKeepAlive;
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null) port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null) backlog = new Integer(s).intValue();

    if (keepAlive) {
      s = (String) props.get("keepAlive");
      if (s != null) keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
      KeyManager[] keyManagers = null;
      TrustManager[] trustManagers = null;

      String keyManager = (String) props.get("keyManager");

      if (keyManager != null && keyManager.length() > 0) {
        try {
          KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
          keyManagers = new KeyManager[] {manager};
        } catch (Exception e) {
          e.printStackTrace();
        }
      } else {
        String keystore = (String) props.get("keyStore");
        String keystoreType = (String) props.get("keyStoreType");
        String keystorePassword = (String) props.get("keyStorePassword");
        String keyPassword = (String) props.get("keyPassword");

        if (keystore != null) {
          if (keystoreType == null) keystoreType = "pkcs12";

          KeyStore ks = KeyStore.getInstance(keystoreType);
          ks.load(
              new FileInputStream(keystore),
              keystorePassword == null ? null : keystorePassword.toCharArray());

          KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
          kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
          keyManagers = kmf.getKeyManagers();
        }
      }

      String trustManager = (String) props.get("trustManager");

      if (trustManager != null && trustManager.length() > 0) {
        try {
          TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
          trustManagers = new TrustManager[] {manager};
        } catch (Exception e) {
          e.printStackTrace();
        }
      } else if ("true".equalsIgnoreCase(trustAll)) {
        trustManagers =
            new TrustManager[] {
              new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {}

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

                public X509Certificate[] getAcceptedIssuers() {
                  return new X509Certificate[0];
                }
              }
            };
      } else {
        String keystore = (String) props.get("caStore");
        String keystoreType = (String) props.get("caStoreType");
        String keystorePassword = (String) props.get("caStorePassword");

        if (keystore != null) {
          if (keystoreType == null) keystoreType = "pkcs12";

          KeyStore caKeys = KeyStore.getInstance(keystoreType);
          caKeys.load(
              new FileInputStream(keystore),
              keystorePassword == null ? null : keystorePassword.toCharArray());
          TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
          tmf.init(caKeys);
          trustManagers = tmf.getTrustManagers();
        }
      }

      SSLContext sslContext = SSLContext.getInstance("SSLv3");
      sslContext.init(keyManagers, trustManagers, null);

      ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
      SSLServerSocket sslServerSocket =
          (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
      serverSocket = sslServerSocket;

      if (sslWantClientAuth) sslServerSocket.setWantClientAuth(true);

      if (sslNeedClientAuth) sslServerSocket.setNeedClientAuth(true);

      if (sslEnabledProtocols != null) sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

      if (sslEnabledCiphers != null) sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

      usingSSL = true;
    } else {
      serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
  }