Exemplo n.º 1
0
  protected void bind() throws IOException {
    URI bind = getBindLocation();

    String host = bind.getHost();
    host = (host == null || host.length() == 0) ? "localhost" : host;
    InetAddress addr = InetAddress.getByName(host);

    try {
      if (host.trim().equals("localhost") || addr.equals(InetAddress.getLocalHost())) {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog);
      } else {
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog, addr);
      }
      this.serverSocket.setSoTimeout(2000);
    } catch (IOException e) {
      throw IOExceptionSupport.create(
          "Failed to bind to server socket: " + bind + " due to: " + e, e);
    }
    try {
      setConnectURI(
          new URI(
              bind.getScheme(),
              bind.getUserInfo(),
              resolveHostName(bind.getHost()),
              serverSocket.getLocalPort(),
              bind.getPath(),
              bind.getQuery(),
              bind.getFragment()));
    } catch (URISyntaxException e) {
      throw IOExceptionSupport.create(e);
    }
  }
Exemplo n.º 2
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;
  }
    @Override
    public void run() {

      List<Socket> inProgress = new ArrayList<>();
      ServerSocketFactory factory = ServerSocketFactory.getDefault();

      try {
        ss = factory.createServerSocket(0);
        ss.setSoTimeout(5000);

        socketReadyLatch.countDown();
        while (!interrupted()) {
          inProgress.add(ss.accept()); // eat socket
        }
      } catch (java.net.SocketTimeoutException expected) {
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          ss.close();
        } catch (IOException ignored) {
        }
        for (Socket s : inProgress) {
          try {
            s.close();
          } catch (IOException ignored) {
          }
        }
      }
    }
Exemplo n.º 4
0
  public FileSender(File file, InetAddress client) throws IOException {
    ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
    ssocket = ssocketFactory.createServerSocket();
    ssocket.bind(null);
    ssocket.setSoTimeout(timeout);

    this.file = file;
    this.client = client;
  }
  public JDSimpleWebserver() {
    SubConfiguration subConfig = SubConfiguration.getConfig("WEBINTERFACE");
    Boolean https = subConfig.getBooleanProperty(JDWebinterface.PROPERTY_HTTPS, false);
    AuthUser =
        "******"
            + Encoding.Base64Encode(
                subConfig.getStringProperty(JDWebinterface.PROPERTY_USER, "JD")
                    + ":"
                    + subConfig.getStringProperty(JDWebinterface.PROPERTY_PASS, "JD"));
    NeedAuth = subConfig.getBooleanProperty(JDWebinterface.PROPERTY_LOGIN, true);
    boolean localhostonly =
        subConfig.getBooleanProperty(JDWebinterface.PROPERTY_LOCALHOST_ONLY, false);
    int port = subConfig.getIntegerProperty(JDWebinterface.PROPERTY_PORT, 8765);
    try {
      if (!https) {
        if (localhostonly) {
          Server_Socket = new ServerSocket(port, -1, HttpServer.getLocalHost());
        } else {
          Server_Socket = new ServerSocket(port);
        }
      } else {
        try {
          ServerSocketFactory ssocketFactory = setupSSL();

          if (localhostonly) {
            Server_Socket = ssocketFactory.createServerSocket(port, -1, HttpServer.getLocalHost());
          } else {
            Server_Socket = ssocketFactory.createServerSocket(port);
          }
        } catch (Exception e) {
          logger.severe("WebInterface: Server failed to start (SSL Setup Failed)!");
          return;
        }
      }
      logger.info("Webinterface: Server started");
      start();
    } catch (IOException e) {
      logger.severe("WebInterface: Server failed to start!");
    }
  }
Exemplo n.º 6
0
  public static void main(String args[]) {

    int port = 6502;
    SSLServerSocket server;

    try {
      // get the keystore into memory
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), keyStorePass);

      // initialize the key manager factory with the keystore data
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, keyStorePass);

      // initialize the SSLContext engine
      // may throw NoSuchProvider or NoSuchAlgorithm exception
      // TLS - Transport Layer Security most generic

      SSLContext sslContext = SSLContext.getInstance("TLS");

      // Inititialize context with given KeyManagers, TrustManagers,
      // SecureRandom defaults taken if null

      sslContext.init(kmf.getKeyManagers(), null, null);

      // Get ServerSocketFactory from the context object
      ServerSocketFactory ssf = sslContext.getServerSocketFactory();
      //  Now like programming with normal server sockets
      ServerSocket serverSocket = ssf.createServerSocket(port);

      System.out.println("Accepting secure connections");

      Socket client = serverSocket.accept();
      System.out.println("Got connection");

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String username = in.readLine();
      String password = in.readLine();

      if (username.equals("Josh") && password.equals("GoBucs")) {
        out.write("Greeting Client");
      } else {
        out.write("Sorry, you are not authorized");
      }
      out.flush();
      in.close();
      out.close();
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }
 @Override
 public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress)
     throws IOException {
   ServerSocket serverSocket = delegate.createServerSocket(port, backlog, ifAddress);
   return configureServerSocket(serverSocket);
 }
 @Override
 public ServerSocket createServerSocket(int port) throws IOException {
   ServerSocket serverSocket = delegate.createServerSocket(port);
   return configureServerSocket(serverSocket);
 }
Exemplo n.º 9
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);
  }