예제 #1
0
  protected ServerSocket createSocket(URI uri)
      throws IOException, NoSuchAlgorithmException, KeyManagementException {
    SslConnector cnn = null;
    ServerSocketFactory ssf = null;
    cnn = (SslConnector) connector;
    // An SSLContext is an environment for implementing JSSE
    // It is used to create a ServerSocketFactory
    SSLContext sslc = SSLContext.getInstance(cnn.getProtocol().toLowerCase());

    // Initialize the SSLContext to work with our key managers
    sslc.init(cnn.getKeyManagerFactory().getKeyManagers(), null, null);

    ssf = sslc.getServerSocketFactory();

    String host = StringUtils.defaultIfEmpty(uri.getHost(), "localhost");
    int backlog = cnn.getBacklog();
    SSLServerSocket serverSocket = null;

    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost())
        || inetAddress.isLoopbackAddress()
        || host.trim().equals("localhost")) {
      serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog);
    } else {
      serverSocket = (SSLServerSocket) ssf.createServerSocket(uri.getPort(), backlog, inetAddress);
    }
    // Authenticate the client?
    serverSocket.setNeedClientAuth(cnn.isRequireClientAuthentication());
    return serverSocket;
  }
예제 #2
0
 /**
  * Configure Client authentication for this version of JSSE. The JSSE included in Java 1.4
  * supports the 'want' value. Prior versions of JSSE will treat 'want' as 'false'.
  *
  * @param socket the SSLServerSocket
  */
 protected void configureClientAuth(SSLServerSocket socket) {
   if (wantClientAuth) {
     socket.setWantClientAuth(wantClientAuth);
   } else {
     socket.setNeedClientAuth(requireClientAuth);
   }
 }
예제 #3
0
  /**
   * @param p_address
   * @param p_acceptQueueSize
   * @return
   * @exception IOException
   */
  protected ServerSocket newServerSocket(InetAddrPort p_address, int p_acceptQueueSize)
      throws IOException {
    SSLServerSocketFactory factory = null;
    SSLServerSocket socket = null;

    try {
      factory = createFactory();

      if (p_address == null) {
        socket = (SSLServerSocket) factory.createServerSocket(0, p_acceptQueueSize);
      } else {
        socket =
            (SSLServerSocket)
                factory.createServerSocket(
                    p_address.getPort(), p_acceptQueueSize, p_address.getInetAddress());
      }

      socket.setNeedClientAuth(_needClientAuth);
      log.info("JsseListener.needClientAuth=" + _needClientAuth);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      log.warn(LogSupport.EXCEPTION, e);
      throw new IOException("Could not create JsseListener: " + e.toString());
    }
    return socket;
  }
  /**
   * 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;
  }
예제 #5
0
파일: Main.java 프로젝트: beroal/forum
 void main1() throws SQLException, IOException, KeyManagementException, NoSuchAlgorithmException {
   netNodeTable.connectToFedAll();
   SSLContext context = SSLContext.getInstance("TLS");
   context.init(
       defaultKmf.getKeyManagers(), new TrustManager[] {new AnyClientTrustManager()}, null);
   SSLServerSocket serverSocket =
       (SSLServerSocket) context.getServerSocketFactory().createServerSocket(port);
   serverSocket.setNeedClientAuth(true);
   userInputThread.start();
   while (true) {
     SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
     fingTable.addAndStart(new FingThread(myDb.create(), netNodeTable, fingTable, clientSocket));
   }
 }
예제 #6
0
 static void accept(KeyStore keyStore, char[] keyPassword, KeyStore trustStore, int port)
     throws GeneralSecurityException, IOException {
   SSLContext sslContext = SSLContexts.create(keyStore, keyPassword, trustStore);
   SSLServerSocket serverSocket =
       (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port);
   try {
     serverSocket.setNeedClientAuth(true);
     SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
     javax.security.cert.X509Certificate peer =
         clientSocket.getSession().getPeerCertificateChain()[0];
     logger.info("peer: " + peer.getSubjectDN().getName());
     ServerThread.handle(clientSocket);
   } finally {
     serverSocket.close();
   }
 }
예제 #7
0
    public void run() {
      try {
        store = provideKeys ? getKeyStore(keys) : null;
        KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
        TrustManager[] trustManagers = new TrustManager[] {trustManager};

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

        SSLServerSocket serverSocket =
            (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();

        if (clientAuth == CLIENT_AUTH_WANTED) {
          serverSocket.setWantClientAuth(true);
        } else if (clientAuth == CLIENT_AUTH_NEEDED) {
          serverSocket.setNeedClientAuth(true);
        } else {
          serverSocket.setWantClientAuth(false);
        }

        serverSocket.bind(new InetSocketAddress(port));

        SSLSocket clientSocket = (SSLSocket) serverSocket.accept();

        InputStream istream = clientSocket.getInputStream();
        byte[] buffer = new byte[1024];
        istream.read(buffer);

        OutputStream ostream = clientSocket.getOutputStream();
        ostream.write(testData.getBytes());
        ostream.flush();

        while (notFinished) {
          Thread.currentThread().sleep(500);
        }

        clientSocket.close();
        serverSocket.close();

      } catch (Exception ex) {
        exception = ex;
      }
    }
    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();
        }
    }
예제 #9
0
 public void setNeedClientAuth(boolean flag) {
   if (ss instanceof SSLServerSocket) {
     ((SSLServerSocket) ss).setNeedClientAuth(flag);
   }
 }
 public void setNeedClientAuth(boolean need) {
   s.setNeedClientAuth(need);
 }
예제 #11
0
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    com.sun.net.ssl.SSLContext ctx = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");

    ks.load(new FileInputStream(keyFilename), cpasswd);
    kmf.init(ks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) ctx.getServerSocketFactory();

    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    sslServerSocket.setNeedClientAuth(true);

    /*
     * Create using the other type.
     */
    SSLContext ctx1 = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf1 = KeyManagerFactory.getInstance("SunX509");

    TrustManager[] tms1 = new TrustManager[] {new MyJavaxX509TrustManager()};

    kmf1.init(ks, cpasswd);

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslssf = (SSLServerSocketFactory) ctx1.getServerSocketFactory();

    SSLServerSocket sslServerSocket1 = (SSLServerSocket) sslssf.createServerSocket(serverPort1);
    serverPort1 = sslServerSocket1.getLocalPort();
    sslServerSocket1.setNeedClientAuth(true);

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    sslServerSocket.close();
    serverReady = false;

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

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    sslSocket = (SSLSocket) sslServerSocket1.accept();
    sslIS = sslSocket.getInputStream();
    sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    System.out.println("Server exiting!");
    System.out.flush();
  }
 public ServerSocket createServerSocket(int port, boolean clientAuth) throws IOException {
   SSLServerSocket socket = (SSLServerSocket) serverSocketFactory.createServerSocket(port);
   socket.setNeedClientAuth(clientAuth);
   return socket;
 }
예제 #13
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);
  }