コード例 #1
0
    public void run() {
      try {
        store = provideKeys ? getKeyStore(keys) : null;
        KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
        TrustManager[] trustManagers = new TrustManager[] {trustManager};

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

        SSLSocket socket = (SSLSocket) clientSslContext.getSocketFactory().createSocket();

        socket.connect(new InetSocketAddress(port));
        OutputStream ostream = socket.getOutputStream();
        ostream.write(testData.getBytes());
        ostream.flush();

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

        clientSession = socket.getSession();
        while (notFinished) {
          Thread.currentThread().sleep(500);
        }
        socket.close();

      } catch (Exception ex) {
        exception = ex;
      }
    }
  /*
   * 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();
  }
コード例 #3
0
  public static void main(String[] args) throws Exception {
    SSLContext sslContext = createSSLContext();
    SSLServerSocketFactory fact = sslContext.getServerSocketFactory();
    SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(Utils.PORT_NO);

    // client authenticate where possible
    sSock.setWantClientAuth(true);

    for (; ; ) {
      SSLSocket sslSock = (SSLSocket) sSock.accept();

      try {
        sslSock.startHandshake();
      } catch (IOException e) {
        continue;
      }

      readRequest(sslSock.getInputStream());

      SSLSession session = sslSock.getSession();

      try {
        Principal clientID = session.getPeerPrincipal();

        System.out.println("client identified as: " + clientID);
      } catch (SSLPeerUnverifiedException e) {
        System.out.println("client not authenticated");
      }

      sendResponse(sslSock.getOutputStream());

      sslSock.close();
    }
  }
コード例 #4
0
 /**
  * Send a message to a specified address.
  *
  * @param message Pre-formatted message to send.
  * @param receiverAddress Address to send it to.
  * @param receiverPort Receiver port.
  * @throws IOException If there is a problem connecting or sending.
  */
 public void sendMessage(
     byte message[], InetAddress receiverAddress, int receiverPort, boolean retry)
     throws IOException {
   if (message == null || receiverAddress == null)
     throw new IllegalArgumentException("Null argument");
   SSLSocket sock =
       (SSLSocket)
           this.stack.ioHandler.sendBytes(receiverAddress, receiverPort, "TLS", message, retry);
   //
   // Created a new socket so close the old one and s
   // Check for null (bug fix sent in by Christophe)
   if (sock != mySock && sock != null) {
     try {
       if (mySock != null) mySock.close();
     } catch (IOException ex) {
       /* ignore */
     }
     mySock = sock;
     this.myClientInputStream = mySock.getInputStream();
     this.myClientOutputStream = mySock.getOutputStream();
     // start a new reader on this end of the pipe.
     Thread mythread = new Thread(this);
     mythread.setDaemon(true);
     mythread.setName("TLSMessageChannelThread");
     mythread.start();
   }
 }
コード例 #5
0
ファイル: Utility.java プロジェクト: weicz/cpkcrypto
    @Override
    public void run() {
      SSLSocketFactory socFac = _sslCtx.getSocketFactory();
      SSLSocket socket = null;
      try {
        socket = (SSLSocket) socFac.createSocket(_targetAddr.getAddress(), _targetAddr.getPort());
        Utility.logOutConnection(socket, _selfId); // log connection
        BufferedWriter out =
            new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Utility.ENCODING));
        Utility.XMLDocToWriter(_doc, out);
        if (_bExpectACK) {
          BufferedReader in =
              new BufferedReader(new InputStreamReader(socket.getInputStream(), Utility.ENCODING));
          Document doc = Utility.ReaderToXMLDoc(in);
          if (!doc.getRootElement().getName().equals(ACK)) { // if not ACK
            _log.error("The Peer didn't send ACK back");
          }
        }

      } catch (Exception e) {
        _log.error("SendJob failed", e);
      } finally {
        try {
          if (null != socket) socket.close();
        } catch (IOException e) {
          _log.error("close sendjob socket failed", e);
        }
      }
    }
コード例 #6
0
  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);
  }
コード例 #7
0
ファイル: Call.java プロジェクト: lsnow2017/ChatterBox
 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());
   }
 }
コード例 #8
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();
  }
コード例 #9
0
ファイル: SSLServer.java プロジェクト: CarlousF/sslsocket
  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();
  }
コード例 #10
0
ファイル: SSLImpl.java プロジェクト: rhomobile/rhodes
  public boolean connect(int fd, boolean sslVerifyPeer, String hostname) {
    try {
      Logger.I(TAG, "SSL connect to " + hostname);

      RhoSockAddr remote = getRemoteSockAddr(fd);
      Socket s = new RhoSocket(fd, remote);
      SSLSocketFactory f = getFactory(sslVerifyPeer);

      StringTokenizer st = new StringTokenizer(hostname, ":");
      String host = st.nextToken();

      SSLSocket aSock = (SSLSocket) f.createSocket(s, host, remote.port, true);
      aSock.setUseClientMode(true);

      synchronized (this) {
        sock = aSock;
        os = sock.getOutputStream();
        is = sock.getInputStream();
        sockfd = fd;
      }
      return true;
    } catch (Exception e) {
      reportFail("connect", e);
      e.printStackTrace();
      return false;
    }
  }
コード例 #11
0
ファイル: FTPSClient.java プロジェクト: agilepro/photegrity
  /**
   * 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()));
  }
コード例 #12
0
 public OutputStream getOutputStream() throws IOException {
   if (sslSocket != null) {
     if (sslOutputStream == null) {
       sslOutputStream = sslSocket.getOutputStream();
     }
     return sslOutputStream;
   } else if (outputStream == null) {
     outputStream = socket.getOutputStream();
   }
   return outputStream;
 }
コード例 #13
0
 public Client(SSLSocket s) {
   this.socket = s;
   try {
     br = new BufferedReader(new InputStreamReader(s.getInputStream()));
     bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
     bConnected = true;
     DBAccess = DataBaseThread.DBAccess;
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #14
0
ファイル: HISPagent.java プロジェクト: josephleong/hie
  public static void main(String[] args) {
    try {
      if (args.length != 0) ip = args[0];
      InputStream inputstream = System.in;
      InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
      BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

      SSLSocket sslsocket = handshake(ip);

      OutputStream sslOut = sslsocket.getOutputStream();
      ObjectOutputStream objOut = new ObjectOutputStream(sslOut);

      InputStream sslIn = sslsocket.getInputStream();
      ObjectInputStream objIn = new ObjectInputStream(sslIn);
      if (!verifyAuthServer(objOut, objIn)) {
        System.out.println("Couldn't Verify");
        return;
      }

      Reply response = null;
      Request request = null;
      String username = "";
      String password = "";

      do {
        System.out.println("Username?");
        username = bufferedreader.readLine();
        System.out.println("Password?");
        password = bufferedreader.readLine();
        objOut.writeObject(new HISPLogin(username, password));
        response = (Reply) objIn.readObject();
        System.out.println(response.getMessage());
        System.out.println();
      } while (response.equals(new Reply("Invalid User Login")));

      while (true) {
        System.out.println("");
        request = createRequest(username, password);
        if (request != null) {
          long startTime = System.currentTimeMillis();
          objOut.writeObject(request);
          response = (Reply) objIn.readObject();
          long endTime = System.currentTimeMillis();
          System.out.println(response.getMessage());
          System.out.println("Time: " + (endTime - startTime) + " ms");
          System.out.println("\nPress ENTER to continue.");
          bufferedreader.read();
        }
      }

    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }
コード例 #15
0
ファイル: SocketIO.java プロジェクト: paulina-bucekova/oblak
  /**
   * Constructor.
   *
   * @param sslSocket Socket to wrap.
   * @throws IOException
   */
  public SocketIO(SSLSocket sslSocket) throws IOException {
    socket = sslSocket;
    inputStream = socket.getInputStream();
    inputStreamReader = new InputStreamReader(inputStream);
    bufferedReader = new BufferedReader(inputStreamReader);
    dataInputStream = new DataInputStream(inputStream);

    outputStream = socket.getOutputStream();
    outputStreamWriter = new OutputStreamWriter(outputStream);
    dataOutputStream = new DataOutputStream(outputStream);
  }
コード例 #16
0
ファイル: Cliente.java プロジェクト: kaiomagalhaes/Seguranca
 @Override
 public void sinalizarAlteracaoLocal(Map<String, Object> requisicao) throws Exception {
   try {
     String evento = (String) requisicao.get("evento");
     System.out.println("Cliente sinalizando alteração local:" + evento);
     PrintStream saidaCliente = new PrintStream(socket.getOutputStream());
     saidaCliente.write(Utils.getBytes(requisicao));
     saidaCliente.flush();
   } catch (Exception e) {
     System.out.println("Falha ao sinalizar a alteração local, cliente.Falha:" + e.getMessage());
   }
 }
コード例 #17
0
  void doTest(SSLSocket sslSocket) throws Exception {
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    System.out.println("  Writing");
    sslOS.write(280);
    sslOS.flush();
    System.out.println("  Reading");
    sslIS.read();

    sslSocket.close();
  }
コード例 #18
0
ファイル: ClienteTCP.java プロジェクト: spierr/Lab6
  public static void main(String[] args) {

    try {
      SSLClient client = new SSLClient();
      SSLSocket s = (SSLSocket) client.createSocket("localhost", 7443);
      PrintWriter writer = new PrintWriter(s.getOutputStream());
      InputStream reader = s.getInputStream();
      writer.println("Hola");
    } catch (Exception exception) {

    }
  }
コード例 #19
0
ファイル: Cliente.java プロジェクト: kaiomagalhaes/Seguranca
 public void run() {
   try {
     iniciarMonitoramentoArquivos(enderecoPasta);
     System.out.println("Monitoramento sendo realizado na pasta:" + enderecoPasta);
     iniciarTratadorRedundancia();
     PrintStream out = new PrintStream(socket.getOutputStream());
     System.out.println("Enviando o nome:" + nome);
     out.write(Utils.getBytes(nome));
     out.flush();
     this.escutarRequisicoes(socket);
   } catch (Exception e) {
     System.out.println("Excessão durante o run do cliente.Erro: " + e.getMessage());
   }
 }
コード例 #20
0
  private boolean sendLoginRequest(String userName, String password) throws Exception {
    boolean result = false;

    try {
      sslsocket = (SSLSocket) factory.createSocket(BURRITOPOS_SERVER_IP, BURRITOPOS_SERVER_PORT);
      in = new ObjectInputStream(sslsocket.getInputStream());
      out = new ObjectOutputStream(sslsocket.getOutputStream());

      String str = (String) in.readObject();
      dLog.trace("Got : " + str);
      out.writeObject(userName);
      str = (String) in.readObject();
      dLog.trace("Got : " + str);
      out.writeObject(password);
      str = (String) in.readObject();
      dLog.trace("Got : " + str);
      dLog.trace("good? " + str.split(" ")[0]);

      // check our input
      if (str.split(" ")[0].equals("OK")) {
        result = true;
      }

      out.writeObject("exit");
    } catch (Exception e1) {
      dLog.error("Exception in sendLoginRequest", e1);
    } finally {
      try {
        dLog.trace("Trying to close input stream");
        if (in != null) {
          in.close();
        }
        dLog.trace("Trying to close output stream");
        if (out != null) {
          out.close();
        }
        dLog.trace("Trying to close socket");
        if (sslsocket != null) {
          sslsocket.close();
        }
      } catch (Exception e2) {
        dLog.error("Exception closing socket", e2);
        throw (e2);
      }
    }

    dLog.trace("Returning result: " + result);
    return result;
  }
コード例 #21
0
ファイル: Connection.java プロジェクト: evilfate/okhttp
  /** Create an {@code SSLSocket} and perform the TLS handshake and certificate validation. */
  private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
    Platform platform = Platform.get();

    // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
    if (requiresTunnel()) {
      makeTunnel(tunnelRequest);
    }

    // Create the wrapper over connected socket.
    socket =
        route.address.sslSocketFactory.createSocket(
            socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
    SSLSocket sslSocket = (SSLSocket) socket;
    if (route.modernTls) {
      platform.enableTlsExtensions(sslSocket, route.address.uriHost);
    } else {
      platform.supportTlsIntolerantServer(sslSocket);
    }

    boolean useNpn = route.modernTls && route.address.transports.contains("spdy/3");
    if (useNpn) {
      platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
    }

    // Force handshake. This can throw!
    sslSocket.startHandshake();

    // Verify that the socket's certificates are acceptable for the target host.
    if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
      throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
    }

    out = sslSocket.getOutputStream();
    in = sslSocket.getInputStream();

    byte[] selectedProtocol;
    if (useNpn && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
      if (Arrays.equals(selectedProtocol, SPDY3)) {
        sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
        spdyConnection =
            new SpdyConnection.Builder(route.address.getUriHost(), true, in, out).build();
        spdyConnection.sendConnectionHeader();
      } else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
        throw new IOException(
            "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
      }
    }
  }
コード例 #22
0
  @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...

  }
コード例 #23
0
ファイル: SSLImpl.java プロジェクト: pyodor/rhodes
 public boolean connect(int fd, boolean sslVerifyPeer) {
   try {
     sockfd = fd;
     RhoSockAddr remote = getRemoteSockAddr(sockfd);
     Socket s = new RhoSocket(sockfd, remote);
     SSLSocketFactory f = getFactory(sslVerifyPeer);
     sock = (SSLSocket) f.createSocket(s, remote.host.toString(), remote.port, true);
     sock.setUseClientMode(true);
     os = sock.getOutputStream();
     is = sock.getInputStream();
     return true;
   } catch (Exception e) {
     reportFail("connect", e);
     e.printStackTrace();
     return false;
   }
 }
コード例 #24
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 {

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

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

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    DataOutputStream out = new DataOutputStream(sslSocket.getOutputStream());

    try {
      // get path to class file from header
      DataInputStream in = new DataInputStream(sslSocket.getInputStream());
      String path = getPath(in);
      // retrieve bytecodes
      byte[] bytecodes = getBytes(path);
      // send bytecodes in response (assumes HTTP/1.0 or later)
      try {
        out.writeBytes("HTTP/1.0 200 OK\r\n");
        out.writeBytes("Content-Length: " + bytecodes.length + "\r\n");
        out.writeBytes("Content-Type: text/html\r\n\r\n");
        out.write(bytecodes);
        out.flush();
      } catch (IOException ie) {
        ie.printStackTrace();
        return;
      }

    } catch (Exception e) {
      e.printStackTrace();
      // write out error response
      out.writeBytes("HTTP/1.0 400 " + e.getMessage() + "\r\n");
      out.writeBytes("Content-Type: text/html\r\n\r\n");
      out.flush();
    } finally {
      // close the socket
      System.out.println("Server closing socket");
      sslSocket.close();
      serverReady = false;
    }
  }
コード例 #25
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;
      }
    }
コード例 #26
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 {
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

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

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

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

    sslSocket.close();
  }
コード例 #27
0
 /**
  * Send message to whoever is connected to us. Uses the topmost via address to send to.
  *
  * @param msg is the message to send.
  * @param retry
  */
 private void sendMessage(byte[] msg, boolean retry) throws IOException {
   SSLSocket sock =
       (SSLSocket)
           this.stack.ioHandler.sendBytes(
               this.peerAddress, this.peerPort, this.peerProtocol, msg, retry);
   // Created a new socket so close the old one and stick the new
   // one in its place but dont do this if it is a datagram socket.
   // (could have replied via udp but received via tcp!).
   if (sock != mySock && sock != null) {
     try {
       if (mySock != null) mySock.close();
     } catch (IOException ex) {
     }
     mySock = sock;
     this.myClientInputStream = mySock.getInputStream();
     this.myClientOutputStream = mySock.getOutputStream();
     Thread thread = new Thread(this);
     thread.setDaemon(true);
     thread.setName("TLSMessageChannelThread");
     thread.start();
   }
 }
コード例 #28
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 {
    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

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

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    try {
      InputStream sslIS = sslSocket.getInputStream();
      OutputStream sslOS = sslSocket.getOutputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(sslIS));
      PrintStream ps = new PrintStream(sslOS);

      // process HTTP POST request from client
      System.out.println("status line: " + br.readLine());
      String msg = null;
      while ((msg = br.readLine()) != null && msg.length() > 0) ;

      msg = br.readLine();
      if (msg.equals(postMsg)) {
        ps.println("HTTP/1.1 200 OK\n\n");
      } else {
        ps.println("HTTP/1.1 500 Not OK\n\n");
      }
      ps.flush();

      // close the socket
      while (!closeReady) {
        Thread.sleep(50);
      }
    } finally {
      sslSocket.close();
      sslServerSocket.close();
    }
  }
コード例 #29
0
  /**
   * @param s newly connected socket from (hopefully) a client
   * @param callback object which will be called asynchonously as messages come in
   * @param pass password hash to authenticate with
   * @throws IOException
   */
  public ClientConnection(SSLSocket s, IServer callback, PasswordHash pass) throws IOException {
    if (pass == null) throw new NullPointerException("Seibert LIED TO ME!");
    /** unique id for this client connection */
    ID = claimID();

    pw = pass;
    server = callback;

    out = s.getOutputStream();
    InputStream in = s.getInputStream();

    /** authenticate */
    byte[] clientPwHash = new byte[20];
    NetUtils.readFully(in, clientPwHash, 0, 20);

    if (!(new PasswordHash(clientPwHash).equals(pw)))
      throw new SecurityException("Incorrect password recieved");

    ccct = new ClientConnectionCallbackThread(in, server, this, ID);

    /** start up the callback thread */
    new Thread(ccct).start();
  }
コード例 #30
0
ファイル: RWTelnet.java プロジェクト: nka11/freehost3270
  /**
   * Performs a direct connection to the terminal server ommiting <code>SessionServer</code> relay.
   * added 5/12/98 to facilitate packaging of the 3270 Servlet Developer's Toolkit
   *
   * @param host destination server host name.
   * @param port destination terminal server port number.
   * @throws UnknownHostException DOCUMENT ME!
   * @throws IOException DOCUMENT ME!
   */
  protected void connect(String host, int port) throws UnknownHostException, IOException {
    log.info("connecting to " + host + ":" + port);
    if (encryption) {

      log.info("encrypted connection");
      SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory.getDefault();
      tnSocketSSL = (SSLSocket) sslFact.createSocket();
      tnSocketSSL.connect(new InetSocketAddress(host, port), connectionTimeout * 1000);

      is = tnSocketSSL.getInputStream();
      os = tnSocketSSL.getOutputStream();

    } else {

      tnSocket = new Socket();
      tnSocket.connect(new InetSocketAddress(host, port), connectionTimeout * 1000);

      is = tnSocket.getInputStream();
      os = tnSocket.getOutputStream();
    }
    sessionThread = new Thread(this);
    sessionThread.start();
  }