Java Examples for javax.net.ssl.SSLServerSocket
The following java examples will help you to understand the usage of javax.net.ssl.SSLServerSocket. These source code samples are taken from different open source projects.
Example 1
| Project: android-libcore64-master File: SSLServerSocketTest.java View source code |
/**
* javax.net.ssl.SSLServerSocket#SSLServerSocket(int port)
*/
public void testConstructor_I() throws Exception {
int[] port_invalid = { -1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE };
SSLServerSocket ssl = new mySSLServerSocket(0);
for (int i = 0; i < port_invalid.length; i++) {
try {
new mySSLServerSocket(port_invalid[i]);
fail("IllegalArgumentException should be thrown");
} catch (IllegalArgumentException expected) {
}
}
try {
new mySSLServerSocket(ssl.getLocalPort());
fail("IOException Expected when opening an already opened port");
} catch (IOException expected) {
}
}Example 2
| Project: android-sdk-sources-for-api-level-23-master File: SSLServerSocketTest.java View source code |
/**
* javax.net.ssl.SSLServerSocket#SSLServerSocket(int port)
*/
public void testConstructor_I() throws Exception {
int[] port_invalid = { -1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE };
SSLServerSocket ssl = new mySSLServerSocket(0);
for (int i = 0; i < port_invalid.length; i++) {
try {
new mySSLServerSocket(port_invalid[i]);
fail("IllegalArgumentException should be thrown");
} catch (IllegalArgumentException expected) {
}
}
try {
new mySSLServerSocket(ssl.getLocalPort());
fail("IOException Expected when opening an already opened port");
} catch (IOException expected) {
}
}Example 3
| Project: android_platform_libcore-master File: SSLServerSocketTest.java View source code |
/**
* javax.net.ssl.SSLServerSocket#SSLServerSocket(int port)
*/
public void testConstructor_I() throws Exception {
int[] port_invalid = { -1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE };
SSLServerSocket ssl = new mySSLServerSocket(0);
for (int i = 0; i < port_invalid.length; i++) {
try {
new mySSLServerSocket(port_invalid[i]);
fail("IllegalArgumentException should be thrown");
} catch (IllegalArgumentException expected) {
}
}
try {
new mySSLServerSocket(ssl.getLocalPort());
fail("IOException Expected when opening an already opened port");
} catch (IOException expected) {
}
}Example 4
| Project: ARTPart-master File: SSLDefaultConfigurationAsserts.java View source code |
/**
* Asserts that the provided {@link SSLServerSocketFactory} has the expected default
* configuration.
*/
public static void assertSSLServerSocketFactory(SSLServerSocketFactory sslServerSocketFactory) throws IOException {
StandardNames.assertDefaultCipherSuites(sslServerSocketFactory.getDefaultCipherSuites());
StandardNames.assertSupportedCipherSuites(sslServerSocketFactory.getSupportedCipherSuites());
assertContainsAll("Unsupported default cipher suites", sslServerSocketFactory.getSupportedCipherSuites(), sslServerSocketFactory.getDefaultCipherSuites());
assertSSLServerSocket((SSLServerSocket) sslServerSocketFactory.createServerSocket());
}Example 5
| Project: robovm-master File: SSLServerSocketTest.java View source code |
/**
* javax.net.ssl.SSLServerSocket#SSLServerSocket(int port)
*/
public void testConstructor_I() throws Exception {
int[] port_invalid = { -1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE };
SSLServerSocket ssl = new mySSLServerSocket(0);
for (int i = 0; i < port_invalid.length; i++) {
try {
new mySSLServerSocket(port_invalid[i]);
fail("IllegalArgumentException should be thrown");
} catch (IllegalArgumentException expected) {
}
}
try {
new mySSLServerSocket(ssl.getLocalPort());
fail("IOException Expected when opening an already opened port");
} catch (IOException expected) {
}
}Example 6
| Project: fitnesse-master File: SslServerSocketFactory.java View source code |
@Override
public ServerSocket createServerSocket(int port) throws IOException {
ServerSocket socket;
LOG.log(Level.FINER, "Creating SSL socket on port: " + port);
SSLServerSocketFactory ssf = SslParameters.setSslParameters(sslParameterClassName).createSSLServerSocketFactory();
socket = ssf.createServerSocket(port);
if (needClientAuth) {
((SSLServerSocket) socket).setNeedClientAuth(true);
}
return socket;
}Example 7
| Project: android_libcore-master File: SSLServerSocketTest.java View source code |
/**
* @tests javax.net.ssl.SSLServerSocket#SSLServerSocket(int port)
*/
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "SSLServerSocket", args = { int.class })
public void testConstructor_02() {
SSLServerSocket ssl;
int portNumber = Support_PortManager.getNextPort();
int[] port_invalid = { -1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE };
try {
ssl = new mySSLServerSocket(portNumber);
assertEquals(portNumber, ssl.getLocalPort());
} catch (Exception ex) {
fail("Unexpected exception was thrown " + ex);
}
for (int i = 0; i < port_invalid.length; i++) {
try {
ssl = new mySSLServerSocket(port_invalid[i]);
fail("IllegalArgumentException should be thrown");
} catch (IllegalArgumentException iae) {
} catch (Exception e) {
fail(e + " was thrown instead of IllegalArgumentException");
}
}
try {
ssl = new mySSLServerSocket(portNumber);
new mySSLServerSocket(portNumber);
fail("IOException Expected when opening an already opened port");
} catch (IOException ioe) {
} catch (Exception ex) {
fail("Unexpected exception was thrown " + ex);
}
}Example 8
| Project: hadoop-master File: SslSocketConnectorSecure.java View source code |
/**
* Create a new ServerSocket that will not accept SSLv3 connections,
* but will accept TLSv1.x connections.
*/
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
SSLServerSocket socket = (SSLServerSocket) super.newServerSocket(host, port, backlog);
ArrayList<String> nonSSLProtocols = new ArrayList<String>();
for (String p : socket.getEnabledProtocols()) {
if (!p.contains("SSLv3")) {
nonSSLProtocols.add(p);
}
}
socket.setEnabledProtocols(nonSSLProtocols.toArray(new String[nonSSLProtocols.size()]));
return socket;
}Example 9
| Project: hops-master File: SslSocketConnectorSecure.java View source code |
/**
* Create a new ServerSocket that will not accept SSLv3 connections,
* but will accept TLSv1.x connections.
*/
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
SSLServerSocket socket = (SSLServerSocket) super.newServerSocket(host, port, backlog);
ArrayList<String> nonSSLProtocols = new ArrayList<String>();
for (String p : socket.getEnabledProtocols()) {
if (!p.contains("SSLv3")) {
nonSSLProtocols.add(p);
}
}
socket.setEnabledProtocols(nonSSLProtocols.toArray(new String[nonSSLProtocols.size()]));
return socket;
}Example 10
| Project: jdk7u-jdk-master File: CookieHttpsClientTest.java View source code |
/*
* 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 = null;
try {
sslSocket = (SSLSocket) sslServerSocket.accept();
sslSocket.setSoTimeout(TIMEOUT);
readOneRequest(sslSocket.getInputStream());
sslSocket.getOutputStream().write(replyString.getBytes());
readOneRequest(sslSocket.getInputStream());
sslSocket.getOutputStream().write(replyString.getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (sslSocket != null) {
sslSocket.close();
}
sslServerSocket.close();
} catch (IOException unused) {
}
}
}Example 11
| Project: jetty-alpn-master File: SSLSocketALPNTest.java View source code |
@Override
protected SSLResult<SSLSocket> performTLSHandshake(SSLResult<SSLSocket> handshake, ALPN.ClientProvider clientProvider, final ALPN.ServerProvider serverProvider) throws Exception {
SSLContext sslContext = handshake == null ? SSLSupport.newSSLContext() : handshake.context;
final CountDownLatch latch = new CountDownLatch(2);
final SSLResult<SSLSocket> sslResult = new SSLResult<>();
sslResult.context = sslContext;
final int readTimeout = 5000;
if (handshake == null) {
acceptor = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();
acceptor.bind(new InetSocketAddress("localhost", 0));
}
new Thread() {
@Override
public void run() {
try {
SSLSocket serverSSLSocket = (SSLSocket) acceptor.accept();
System.err.println(serverSSLSocket);
sslResult.server = serverSSLSocket;
serverSSLSocket.setUseClientMode(false);
serverSSLSocket.setSoTimeout(readTimeout);
ALPN.put(serverSSLSocket, serverProvider);
serverSSLSocket.startHandshake();
latch.countDown();
} catch (Exception x) {
x.printStackTrace();
}
}
}.start();
SSLSocket clientSSLSocket = (SSLSocket) sslContext.getSocketFactory().createSocket("localhost", acceptor.getLocalPort());
sslResult.client = clientSSLSocket;
latch.countDown();
clientSSLSocket.setUseClientMode(true);
clientSSLSocket.setSoTimeout(readTimeout);
ALPN.put(clientSSLSocket, clientProvider);
clientSSLSocket.startHandshake();
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
return sslResult;
}Example 12
| Project: jetty-npn-master File: SSLSocketNextProtoNegoTest.java View source code |
@Test
public void testSSLSocket() throws Exception {
NextProtoNego.debug = true;
SSLContext context = SSLSupport.newSSLContext();
final int readTimeout = 5000;
final String data = "data";
final String protocolName = "test";
final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(4));
final SSLServerSocket server = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
server.bind(new InetSocketAddress("localhost", 0));
final CountDownLatch handshakeLatch = new CountDownLatch(2);
new Thread() {
@Override
public void run() {
try {
SSLSocket socket = (SSLSocket) server.accept();
socket.setUseClientMode(false);
socket.setSoTimeout(readTimeout);
NextProtoNego.put(socket, new NextProtoNego.ServerProvider() {
@Override
public void unsupported() {
}
@Override
public List<String> protocols() {
latch.get().countDown();
return Arrays.asList(protocolName);
}
@Override
public void protocolSelected(String protocol) {
Assert.assertEquals(protocolName, protocol);
latch.get().countDown();
}
});
socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
handshakeLatch.countDown();
}
});
socket.startHandshake();
InputStream serverInput = socket.getInputStream();
for (int i = 0; i < data.length(); ++i) {
int read = serverInput.read();
Assert.assertEquals(data.charAt(i), read);
}
OutputStream serverOutput = socket.getOutputStream();
serverOutput.write(data.getBytes("UTF-8"));
serverOutput.flush();
for (int i = 0; i < data.length(); ++i) {
int read = serverInput.read();
Assert.assertEquals(data.charAt(i), read);
}
serverOutput.write(data.getBytes("UTF-8"));
serverOutput.flush();
// Re-handshake
socket.startHandshake();
for (int i = 0; i < data.length(); ++i) {
int read = serverInput.read();
Assert.assertEquals(data.charAt(i), read);
}
serverOutput.write(data.getBytes("UTF-8"));
serverOutput.flush();
Assert.assertEquals(4, latch.get().getCount());
socket.close();
} catch (Exception x) {
x.printStackTrace();
}
}
}.start();
SSLSocket client = (SSLSocket) context.getSocketFactory().createSocket("localhost", server.getLocalPort());
client.setUseClientMode(true);
client.setSoTimeout(readTimeout);
NextProtoNego.put(client, new NextProtoNego.ClientProvider() {
@Override
public boolean supports() {
latch.get().countDown();
return true;
}
@Override
public void unsupported() {
}
@Override
public String selectProtocol(List<String> protocols) {
Assert.assertEquals(1, protocols.size());
String protocol = protocols.get(0);
Assert.assertEquals(protocolName, protocol);
latch.get().countDown();
return protocol;
}
});
client.addHandshakeCompletedListener(new HandshakeCompletedListener() {
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
handshakeLatch.countDown();
}
});
client.startHandshake();
Assert.assertTrue(latch.get().await(5, TimeUnit.SECONDS));
Assert.assertTrue(handshakeLatch.await(5, TimeUnit.SECONDS));
// Check whether we can write real data to the connection
OutputStream clientOutput = client.getOutputStream();
clientOutput.write(data.getBytes("UTF-8"));
clientOutput.flush();
InputStream clientInput = client.getInputStream();
for (int i = 0; i < data.length(); ++i) {
int read = clientInput.read();
Assert.assertEquals(data.charAt(i), read);
}
// Re-handshake
latch.set(new CountDownLatch(4));
client.startHandshake();
Assert.assertEquals(4, latch.get().getCount());
clientOutput.write(data.getBytes("UTF-8"));
clientOutput.flush();
for (int i = 0; i < data.length(); ++i) {
int read = clientInput.read();
Assert.assertEquals(data.charAt(i), read);
}
clientOutput.write(data.getBytes("UTF-8"));
clientOutput.flush();
for (int i = 0; i < data.length(); ++i) {
int read = clientInput.read();
Assert.assertEquals(data.charAt(i), read);
}
int read = clientInput.read();
Assert.assertEquals(-1, read);
client.close();
server.close();
}Example 13
| Project: ManagedRuntimeInitiative-master File: Timeout.java View source code |
public static void main(String[] args) throws Exception {
// try {
SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket();
String[] protocols = ss.getSupportedProtocols();
for (int i = 0; i < protocols.length; i++) {
// try {
if (protocols[i].equals("SSLv2Hello")) {
continue;
}
SSLContext sslc = SSLContext.getInstance(protocols[i]);
SSLSessionContext sslsc = sslc.getServerSessionContext();
System.out.println("Protocol: " + protocols[i]);
sslsc.setSessionTimeout(Integer.MAX_VALUE);
int newtime = sslsc.getSessionTimeout();
if (newtime != Integer.MAX_VALUE) {
throw new Exception("Expected timeout: " + Integer.MAX_VALUE + ", got instead: " + newtime);
}
// } catch (Exception e) {
// }
}
// } catch (Exception e) {
// System.out.println(e);
// }
System.out.println("Finished");
}Example 14
| Project: nuntius-android-master File: SslNetworkConnectionProvider.java View source code |
@Override
public ServerSocket getServerSocket() throws Exception {
SSLContext sslContext = SslUtils.getSSLContext(trustStore);
SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
SSLServerSocket serverSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(port);
serverSocket.setNeedClientAuth(true);
return serverSocket;
}Example 15
| Project: pbase-master File: SslSocketConnectorSecure.java View source code |
/**
* Create a new ServerSocket that will not accept SSLv3 connections,
* but will accept TLSv1.x connections.
*/
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
SSLServerSocket socket = (SSLServerSocket) super.newServerSocket(host, port, backlog);
ArrayList<String> nonSSLProtocols = new ArrayList<String>();
for (String p : socket.getEnabledProtocols()) {
if (!p.contains("SSLv3")) {
nonSSLProtocols.add(p);
}
}
socket.setEnabledProtocols(nonSSLProtocols.toArray(new String[nonSSLProtocols.size()]));
return socket;
}Example 16
| Project: sockso-master File: HttpsServer.java View source code |
/**
* returns a standard server socket
*
* @param port
*
* @return
*
* @throws java.io.IOException
*
*/
@Override
protected SSLServerSocket getServerSocket(final int port) throws IOException {
System.setProperty("javax.net.ssl.keyStore", sslKeystore);
System.setProperty("javax.net.ssl.keyStorePassword", sslKeystorePassword);
SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket) sslserversocketfactory.createServerSocket(port);
return ss;
}Example 17
| Project: ssl_npn-master File: Timeout.java View source code |
public static void main(String[] args) throws Exception {
// try {
SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket();
String[] protocols = ss.getSupportedProtocols();
for (int i = 0; i < protocols.length; i++) {
// try {
if (protocols[i].equals("SSLv2Hello")) {
continue;
}
SSLContext sslc = SSLContext.getInstance(protocols[i]);
SSLSessionContext sslsc = sslc.getServerSessionContext();
System.out.println("Protocol: " + protocols[i]);
sslsc.setSessionTimeout(Integer.MAX_VALUE);
int newtime = sslsc.getSessionTimeout();
if (newtime != Integer.MAX_VALUE) {
throw new Exception("Expected timeout: " + Integer.MAX_VALUE + ", got instead: " + newtime);
}
// } catch (Exception e) {
// }
}
// } catch (Exception e) {
// System.out.println(e);
// }
System.out.println("Finished");
}Example 18
| Project: yajsync-master File: SSLServerChannelFactory.java View source code |
@Override
public ServerChannel open(InetAddress address, int port, int timeout) throws IOException {
SSLServerSocket sock = (SSLServerSocket) _factory.createServerSocket(port, _backlog, address);
try {
sock.setReuseAddress(_isReuseAddress);
sock.setWantClientAuth(_isWantClientAuth);
return new SSLServerChannel(sock, timeout);
} catch (Throwable t) {
if (!sock.isClosed()) {
try {
sock.close();
} catch (Throwable tt) {
t.addSuppressed(tt);
}
}
throw t;
}
}Example 19
| Project: bc-java-master File: HttpResponder.java View source code |
public void run() {
Random rand = new Random();
Socket sock = null;
try {
int t = 10;
for (; t >= 0; t--) {
port = 8000 + rand.nextInt(1000);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, "password".toCharArray());
if (creds == null) {
creds = readCertAndKey(ESTServerUtils.makeRelativeToServerHome("estCA/private/estservercertandkey.pem"));
ks.setKeyEntry("server", KeyFactory.getInstance("EC").generatePrivate(((PKCS8EncodedKeySpec) creds[1])), "password".toCharArray(), new Certificate[] { (Certificate) creds[0] });
} else {
ks.setKeyEntry("server", (Key) creds[1], "password".toCharArray(), new Certificate[] { (Certificate) creds[0] });
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(ks, "password".toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
SSLServerSocketFactory fact = sslContext.getServerSocketFactory();
serverSocket = sslContext.getServerSocketFactory().createServerSocket();
if (cipherSuites != null) {
((SSLServerSocket) serverSocket).setEnabledCipherSuites(cipherSuites);
}
if (tlsProtocol != null) {
((SSLServerSocket) serverSocket).setEnabledProtocols(new String[] { tlsProtocol });
}
try {
serverSocket.bind(new InetSocketAddress(port));
} catch (IOException ioex) {
continue;
}
break;
}
if (t <= 0) {
throw new RuntimeException("Could not open test server socket.");
}
ready.countDown();
sock = serverSocket.accept();
if (lineBuffer != null) {
BufferedReader bin = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line = null;
while ((line = bin.readLine()) != null && line.length() > 0) {
lineBuffer.add(line);
}
}
if (response != null) {
OutputStream os = sock.getOutputStream();
os.write(response);
os.flush();
close.await(60, TimeUnit.SECONDS);
os.close();
sock.close();
}
} catch (InterruptedException ie) {
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
finished.countDown();
}
}Example 20
| Project: dc---master File: HTTPSServerThread.java View source code |
public void run() {
try {
SSLContext sslContext = createSSLContext();
SSLServerSocketFactory fact = sslContext.getServerSocketFactory();
SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(PORT_NO);
SSLSocket sslSock = (SSLSocket) sSock.accept();
sslSock.startHandshake();
readRequest(sslSock.getInputStream());
SSLSession session = sslSock.getSession();
sendResponse(sslSock.getOutputStream());
sslSock.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 21
| Project: fred-master File: SSLNetworkInterface.java View source code |
/**
* {@inheritDoc}
*/
@Override
protected ServerSocket createServerSocket() throws IOException {
SSLServerSocket serverSocket = (SSLServerSocket) SSL.createServerSocket();
serverSocket.setNeedClientAuth(false);
serverSocket.setUseClientMode(false);
serverSocket.setWantClientAuth(false);
serverSocket.setEnabledCipherSuites(new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" });
return serverSocket;
}Example 22
| Project: hermesftp-master File: PassiveModeSocketProvider.java View source code |
/**
* Creates the server socket that accepts the data connection.
*
* @param localIp The local IP address.
* @param port The port.
* @return The server socket.
* @throws IOException Error on creating server socket.
*/
private ServerSocket createServerSocket(InetAddress localIp, int port) throws IOException {
ServerSocket sock;
Boolean dataProtection = (Boolean) ctx.getAttribute(FtpConstants.ATTR_DATA_PROT);
boolean ssl = dataProtection != null && dataProtection;
if (ssl) {
SSLServerSocketFactory factory = ctx.getOptions().getSslContext().getServerSocketFactory();
SSLServerSocket sslServerSocket = (SSLServerSocket) factory.createServerSocket(port, 1, localIp);
sslServerSocket.setUseClientMode(false);
enableCipherSuites(sslServerSocket);
sock = sslServerSocket;
} else {
sock = ServerSocketFactory.getDefault().createServerSocket(port, 1, localIp);
}
sock.setSoTimeout(DATA_CHANNEL_TIMEOUT);
return sock;
}Example 23
| Project: irma_future_id-master File: HTTPSServerThread.java View source code |
public void run() {
try {
SSLContext sslContext = createSSLContext();
SSLServerSocketFactory fact = sslContext.getServerSocketFactory();
SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(PORT_NO);
SSLSocket sslSock = (SSLSocket) sSock.accept();
sslSock.startHandshake();
readRequest(sslSock.getInputStream());
SSLSession session = sslSock.getSession();
sendResponse(sslSock.getOutputStream());
sslSock.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 24
| Project: nanohttpd-master File: SSLServerSocketFactoryTest.java View source code |
@Test
public void testCreatePassesTheProtocolsToServerSocket() throws IOException {
// first find the supported protocols
SecureServerSocketFactory secureServerSocketFactory = new SecureServerSocketFactory(NanoHTTPD.makeSSLSocketFactory("/keystore.jks", "password".toCharArray()), null);
SSLServerSocket socket = (SSLServerSocket) secureServerSocketFactory.create();
String[] protocols = socket.getSupportedProtocols();
// remove one element from supported protocols
if (protocols.length > 0) {
protocols = Arrays.copyOfRange(protocols, 0, protocols.length - 1);
}
// test
secureServerSocketFactory = new SecureServerSocketFactory(NanoHTTPD.makeSSLSocketFactory("/keystore.jks", "password".toCharArray()), protocols);
socket = (SSLServerSocket) secureServerSocketFactory.create();
Assert.assertArrayEquals("Enabled protocols specified in the factory were not set to the socket.", protocols, socket.getEnabledProtocols());
}Example 25
| Project: openjdk-master File: LargePacketAfterHandshakeTest.java View source code |
public static void runServer() {
try {
System.out.println("Server: Started server thread.");
SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(0);
serverport = s.getLocalPort();
System.out.println("Server: Started, listening on port " + serverport + ".");
serverReady = true;
SSLSocket c = (SSLSocket) s.accept();
s.close();
System.out.println("Server: Accepted client connection and closed server socket.");
BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
String echostring = r.readLine();
System.out.println("Server: Read " + echostring.length() + " chars of input data.");
c.startHandshake();
System.out.println("Server: Kicked new handshake.");
w.write(echostring);
w.newLine();
w.flush();
System.out.println("Server: Echoed " + echostring.length() + " chars of input data.");
while (!clientDone) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println("Server: Caught InterruptedException.");
}
}
r.close();
w.close();
c.close();
System.out.println("Server: Closed streams and client socket, exiting.");
} catch (Exception e) {
System.out.println("Server: Caught Exception.");
e.printStackTrace();
serverReady = true;
serverException = e;
}
}Example 26
| Project: openjdk8-jdk-master File: CookieHttpsClientTest.java View source code |
/*
* 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 = null;
try {
sslSocket = (SSLSocket) sslServerSocket.accept();
sslSocket.setSoTimeout(TIMEOUT);
readOneRequest(sslSocket.getInputStream());
sslSocket.getOutputStream().write(replyString.getBytes());
readOneRequest(sslSocket.getInputStream());
sslSocket.getOutputStream().write(replyString.getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (sslSocket != null) {
sslSocket.close();
}
sslServerSocket.close();
} catch (IOException unused) {
}
}
}Example 27
| Project: sockslib-master File: SSLSocksProxyServer.java View source code |
public ServerSocket createSSLServer(int port, InetAddress bindAddr) throws Exception {
SSLServerSocket serverSocket = (SSLServerSocket) configuration.getSSLServerSocketFactory().createServerSocket(port, 50, bindAddr);
if (configuration.isNeedClientAuth()) {
serverSocket.setNeedClientAuth(true);
} else {
serverSocket.setNeedClientAuth(false);
}
return serverSocket;
}Example 28
| Project: tomcat70-master File: Jre8Compat.java View source code |
@Override
public void setUseServerCipherSuitesOrder(SSLServerSocket socket, boolean useCipherSuitesOrder) {
try {
Object sslParameters = getSSLParametersMethod.invoke(socket);
setUseCipherSuitesOrderMethod.invoke(sslParameters, Boolean.valueOf(useCipherSuitesOrder));
setSSLParametersMethod.invoke(socket, sslParameters);
return;
} catch (IllegalArgumentException e) {
throw new UnsupportedOperationException(e);
} catch (IllegalAccessException e) {
throw new UnsupportedOperationException(e);
} catch (InvocationTargetException e) {
throw new UnsupportedOperationException(e);
}
}Example 29
| Project: wildfly-elytron-master File: ConfiguredSSLServerSocketFactory.java View source code |
private ServerSocket wrap(ServerSocket original) throws IOException {
if (original instanceof SSLServerSocket) {
final SSLServerSocket sslServerSocket = (SSLServerSocket) original;
final SSLContext sslContext = this.sslContext;
final SSLConfigurator sslConfigurator = this.sslConfigurator;
sslConfigurator.configure(sslContext, sslServerSocket);
return wrap ? new ConfiguredSSLServerSocket(sslServerSocket, sslContext, sslConfigurator) : sslServerSocket;
} else {
return original;
}
}Example 30
| Project: wildfly-security-master File: ConfiguredSSLServerSocketFactory.java View source code |
private ServerSocket wrap(ServerSocket original) throws IOException {
if (original instanceof SSLServerSocket) {
final SSLServerSocket sslServerSocket = (SSLServerSocket) original;
final SSLContext sslContext = this.sslContext;
final SSLConfigurator sslConfigurator = this.sslConfigurator;
sslConfigurator.configure(sslContext, sslServerSocket);
return wrap ? new ConfiguredSSLServerSocket(sslServerSocket, sslContext, sslConfigurator) : sslServerSocket;
} else {
return original;
}
}Example 31
| Project: activemq-master File: JaasDualAuthenticationBrokerTest.java View source code |
@Override
protected void setUp() throws Exception {
receiveBroker = new StubBroker();
authBroker = new JaasDualAuthenticationBroker(receiveBroker, "activemq-domain", "activemq-ssl-domain");
connectionContext = new ConnectionContext();
SSLServerSocket sslServerSocket = new StubSSLServerSocket();
StubSSLSocketFactory socketFactory = new StubSSLSocketFactory(sslServerSocket);
try {
sslTransportServer = new SslTransportServer(null, new URI("ssl://localhost:61616?needClientAuth=true"), socketFactory);
} catch (Exception e) {
fail("Unable to create SslTransportServer.");
}
sslTransportServer.setNeedClientAuth(true);
sslTransportServer.bind();
try {
nonSslTransportServer = new TcpTransportServer(null, new URI("tcp://localhost:61613"), socketFactory);
} catch (Exception e) {
fail("Unable to create TcpTransportServer.");
}
connectionInfo = new ConnectionInfo();
createLoginConfig();
}Example 32
| Project: cassa-master File: SSLFactory.java View source code |
public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port) throws IOException { SSLContext ctx = createSSLContext(options, true); SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(); try { serverSocket.setReuseAddress(true); prepareSocket(serverSocket, options); serverSocket.bind(new InetSocketAddress(address, port), 500); return serverSocket; } catch (IllegalArgumentExceptionSecurityException | IOException | e) { serverSocket.close(); throw e; } }
Example 33
| Project: Cassandra-KVPM-master File: SSLFactory.java View source code |
public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port) throws IOException { SSLContext ctx = createSSLContext(options); SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(); serverSocket.setReuseAddress(true); serverSocket.setEnabledCipherSuites(options.cipherSuites); serverSocket.bind(new InetSocketAddress(address, port), 100); return serverSocket; }
Example 34
| Project: cassandra-master File: SSLFactory.java View source code |
public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port) throws IOException { SSLContext ctx = createSSLContext(options, true); SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(); try { serverSocket.setReuseAddress(true); prepareSocket(serverSocket, options); serverSocket.bind(new InetSocketAddress(address, port), 500); return serverSocket; } catch (IllegalArgumentExceptionSecurityException | IOException | e) { serverSocket.close(); throw e; } }
Example 35
| Project: deskcon-android-master File: ControlService.java View source code |
@Override
public void run() {
Log.d("Control: ", "start Server");
try {
// create SSLServerSocket
sslServerSocket = Connection.createSSLServerSocket(getApplicationContext(), PORT);
} catch (Exception e) {
e.printStackTrace();
Log.d("Control: ", "could not start");
return;
}
//begin serving
while (!isStopped) {
try {
socket = (SSLSocket) sslServerSocket.accept();
socket.startHandshake();
} catch (IOException e) {
e.printStackTrace();
}
if (socket != null && socket.isConnected()) {
try {
handleClientSocket(socket);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}Example 36
| Project: encryption-jvm-bootcamp-master File: HTTPFileServer.java View source code |
static void startSocketServer(int serverSocketFactoryPort, String serverSocketFactoryType, String docroot, boolean needClientAuth) {
//Create the server socket
try {
ServerSocketFactory ssf = buildServerSocketFactory(serverSocketFactoryType);
ServerSocket ss = ssf.createServerSocket(serverSocketFactoryPort);
if (needClientAuth) {
((SSLServerSocket) ss).setNeedClientAuth(true);
}
new HTTPFileServer(ss, docroot);
System.out.println("Server started successfully. Listening for requests.");
} catch (IOException e) {
System.out.println("Unable to start HTTPServer: " + e.getMessage());
e.printStackTrace();
}
}Example 37
| Project: ofbiz-master File: SSLServerSocketFactory.java View source code |
public ServerSocket createServerSocket(int port) throws IOException {
char[] passphrase = null;
if (ksPass != null) {
passphrase = ksPass.toCharArray();
}
KeyStore ks = null;
if (keystore != null) {
try {
ks = KeyStore.getInstance(ksType);
ks.load(new FileInputStream(keystore), passphrase);
} catch (NoSuchAlgorithmException e) {
Debug.logError(e, module);
throw new IOException(e.getMessage());
} catch (CertificateException e) {
Debug.logError(e, module);
throw new IOException(e.getMessage());
} catch (KeyStoreException e) {
Debug.logError(e, module);
throw new IOException(e.getMessage());
}
}
if (alias == null) {
throw new IOException("SSL certificate alias cannot be null; MUST be set for SSLServerSocketFactory!");
}
javax.net.ssl.SSLServerSocketFactory factory = null;
try {
if (ks != null) {
factory = SSLUtil.getSSLServerSocketFactory(ks, ksPass, alias);
} else {
factory = SSLUtil.getSSLServerSocketFactory(alias);
}
} catch (GeneralSecurityException e) {
Debug.logError(e, "Error getting javax.net.ssl.SSLServerSocketFactory instance for Service Engine RMI calls: " + e.toString(), module);
throw new IOException(e.toString());
} catch (GenericConfigException e) {
Debug.logError(e, "Error getting javax.net.ssl.SSLServerSocketFactory instance for Service Engine RMI calls: " + e.toString(), module);
}
if (factory == null) {
throw new IOException("Unable to obtain SSLServerSocketFactory for provided KeyStore");
}
SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(port);
socket.setNeedClientAuth(clientAuth);
return socket;
}Example 38
| Project: openshift-java-client-master File: HttpsServerFake.java View source code |
@Override
protected ServerSocket createServerSocket(int port) throws Exception {
KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
keyStore.load(getClass().getResourceAsStream(KEYSTORE_FILE), KEYSTORE_PASSWORD.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD.toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, null, null);
SSLServerSocket sslServerSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port);
sslServerSocket.setEnabledCipherSuites(sslContext.getServerSocketFactory().getSupportedCipherSuites());
return sslServerSocket;
}Example 39
| Project: openshift-restclient-java-master File: HttpsServerFake.java View source code |
@Override
protected ServerSocket createServerSocket(int port) throws Exception {
KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
keyStore.load(getClass().getResourceAsStream(KEYSTORE_FILE), KEYSTORE_PASSWORD.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD.toCharArray());
KeyManager keyManagers[] = keyManagerFactory.getKeyManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, null, null);
SSLServerSocket sslServerSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port);
sslServerSocket.setEnabledCipherSuites(sslContext.getServerSocketFactory().getSupportedCipherSuites());
return sslServerSocket;
}Example 40
| Project: restlet-framework-java-master File: WrapperSslServerSocketFactory.java View source code |
/**
* Initializes the SSL server socket. Configures the certificate request
* (need or want) and the enabled cipher suites.
*
* @param sslServerSocket
* The server socket to initialize.
* @return The initialized server socket.
*/
protected SSLServerSocket initSslServerSocket(SSLServerSocket sslServerSocket) {
if (getContextFactory().isNeedClientAuthentication()) {
sslServerSocket.setNeedClientAuth(true);
} else if (getContextFactory().isWantClientAuthentication()) {
sslServerSocket.setWantClientAuth(true);
}
if ((getContextFactory().getEnabledCipherSuites() != null) || (getContextFactory().getDisabledCipherSuites() != null)) {
sslServerSocket.setEnabledCipherSuites(getContextFactory().getSelectedCipherSuites(sslServerSocket.getSupportedCipherSuites()));
}
if ((getContextFactory().getEnabledProtocols() != null) || (getContextFactory().getDisabledProtocols() != null)) {
sslServerSocket.setEnabledProtocols(getContextFactory().getSelectedSslProtocols(sslServerSocket.getSupportedProtocols()));
}
return sslServerSocket;
}Example 41
| Project: scylla-tools-java-master File: SSLFactory.java View source code |
public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port) throws IOException { SSLContext ctx = createSSLContext(options, true); SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(); serverSocket.setReuseAddress(true); String[] suites = filterCipherSuites(serverSocket.getSupportedCipherSuites(), options.cipher_suites); serverSocket.setEnabledCipherSuites(suites); serverSocket.setNeedClientAuth(options.require_client_auth); serverSocket.setEnabledProtocols(ACCEPTED_PROTOCOLS); serverSocket.bind(new InetSocketAddress(address, port), 500); return serverSocket; }
Example 42
| Project: tomcat60-master File: Jre8Compat.java View source code |
@Override
public void setUseServerCipherSuitesOrder(SSLServerSocket socket, boolean useCipherSuitesOrder) {
try {
Object sslParameters = getSSLParametersMethod.invoke(socket);
setUseCipherSuitesOrderMethod.invoke(sslParameters, Boolean.valueOf(useCipherSuitesOrder));
setSSLParametersMethod.invoke(socket, sslParameters);
return;
} catch (IllegalArgumentException e) {
throw new UnsupportedOperationException(e);
} catch (IllegalAccessException e) {
throw new UnsupportedOperationException(e);
} catch (InvocationTargetException e) {
throw new UnsupportedOperationException(e);
}
}Example 43
| Project: carbon-analytics-master File: BinaryDataReceiver.java View source code |
private void startSecureTransmission() throws IOException, DataBridgeException {
String keyStore = dataBridgeReceiverService.getInitialConfig().getKeyStoreLocation();
if (keyStore == null) {
ServerConfiguration serverConfig = ServerConfiguration.getInstance();
keyStore = serverConfig.getFirstProperty("Security.KeyStore.Location");
if (keyStore == null) {
keyStore = System.getProperty("Security.KeyStore.Location");
if (keyStore == null) {
throw new DataBridgeException("Cannot start binary agent server, not valid Security.KeyStore.Location is null");
}
}
}
String keyStorePassword = dataBridgeReceiverService.getInitialConfig().getKeyStorePassword();
if (keyStorePassword == null) {
ServerConfiguration serverConfig = ServerConfiguration.getInstance();
keyStorePassword = serverConfig.getFirstProperty("Security.KeyStore.Password");
if (keyStorePassword == null) {
keyStorePassword = System.getProperty("Security.KeyStore.Password");
if (keyStorePassword == null) {
throw new DataBridgeException("Cannot start binary agent server, not valid Security.KeyStore.Password is null ");
}
}
}
System.setProperty("javax.net.ssl.keyStore", keyStore);
System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(binaryDataReceiverConfiguration.getSSLPort());
String sslProtocols = binaryDataReceiverConfiguration.getSslProtocols();
if (sslProtocols != null && sslProtocols.length() != 0) {
String[] sslProtocolsArray = sslProtocols.split(",");
sslserversocket.setEnabledProtocols(sslProtocolsArray);
}
String ciphers = binaryDataReceiverConfiguration.getCiphers();
if (ciphers != null && ciphers.length() != 0) {
String[] ciphersArray = ciphers.split(",");
sslserversocket.setEnabledCipherSuites(ciphersArray);
} else {
sslserversocket.setEnabledCipherSuites(sslserversocket.getSupportedCipherSuites());
}
Thread thread = new Thread(new BinarySecureEventServerAcceptor(sslserversocket));
thread.start();
log.info("Started Binary SSL Transport on port : " + binaryDataReceiverConfiguration.getSSLPort());
}Example 44
| Project: ACaZoo-master File: SSLFactory.java View source code |
public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port) throws IOException { SSLContext ctx = createSSLContext(options, true); SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(); serverSocket.setReuseAddress(true); String[] suits = filterCipherSuites(serverSocket.getSupportedCipherSuites(), options.cipher_suites); serverSocket.setEnabledCipherSuites(suits); serverSocket.setNeedClientAuth(options.require_client_auth); serverSocket.bind(new InetSocketAddress(address, port), 100); return serverSocket; }
Example 45
| Project: Android-SDK-Samples-master File: SecureWebServer.java View source code |
@Override
public void run() {
Log.d(TAG, "Secure Web Server is starting up on port 8080");
try {
// Create the secure server socket
sss = (SSLServerSocket) sssf.createServerSocket(8080);
} catch (Exception e) {
System.out.println("Error: " + e);
return;
}
Log.d(TAG, "Waiting for connection");
while (isRunning) {
try {
// Wait for an SSL connection
Socket socket = sss.accept();
// Got a connection
Log.d(TAG, "Connected, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
// Read the data until a blank line is reached which
// signifies the end of the client HTTP headers
String str = ".";
while (!str.equals("")) str = in.readLine();
// Send a HTTP response
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: Android KeyChainiDemo SSL Server");
// this blank line signals the end of the headers
out.println("");
// Send the HTML page
out.println("<H1>Welcome to Android!</H1>");
// Add an embedded Android image
out.println("<img src='data:image/png;base64," + base64Image + "'/>");
out.flush();
socket.close();
} catch (Exception e) {
Log.d(TAG, "Error: " + e);
}
}
}Example 46
| Project: aries-master File: IntrospectionSupport.java View source code |
public static boolean setProperty(Object target, String name, Object value) {
try {
Class<?> clazz = target.getClass();
if (target instanceof SSLServerSocket) {
// overcome illegal access issues with internal implementation class
clazz = SSLServerSocket.class;
}
Method setter = findSetterMethod(clazz, name);
if (setter == null) {
return false;
}
// value directly
if (value == null || value.getClass() == setter.getParameterTypes()[0]) {
setter.invoke(target, value);
} else {
// We need to convert it
setter.invoke(target, convert(value, setter.getParameterTypes()[0]));
}
return true;
} catch (Exception e) {
LOG.error(String.format("Could not set property %s on %s", name, target), e);
return false;
}
}Example 47
| Project: bugvm-master File: HttpServer.java View source code |
public void start() throws IOException {
if (this.status.compareAndSet(Status.READY, Status.ACTIVE)) {
this.serverSocket = this.serverSocketFactory.createServerSocket(this.port, this.socketConfig.getBacklogSize(), this.ifAddress);
this.serverSocket.setReuseAddress(this.socketConfig.isSoReuseAddress());
if (this.socketConfig.getRcvBufSize() > 0) {
this.serverSocket.setReceiveBufferSize(this.socketConfig.getRcvBufSize());
}
if (this.sslSetupHandler != null && this.serverSocket instanceof SSLServerSocket) {
this.sslSetupHandler.initialize((SSLServerSocket) this.serverSocket);
}
this.requestListener = new RequestListener(this.socketConfig, this.serverSocket, this.httpService, this.connectionFactory, this.exceptionLogger, this.workerExecutorService);
this.listenerExecutorService.execute(this.requestListener);
}
}Example 48
| Project: cassandra-cqlMod-master File: SSLFactory.java View source code |
public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port) throws IOException { SSLContext ctx = createSSLContext(options, true); SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(); serverSocket.setReuseAddress(true); String[] suits = filterCipherSuites(serverSocket.getSupportedCipherSuites(), options.cipher_suites); serverSocket.setEnabledCipherSuites(suits); serverSocket.setNeedClientAuth(options.require_client_auth); serverSocket.bind(new InetSocketAddress(address, port), 100); return serverSocket; }
Example 49
| Project: CloudStack-archive-master File: ConsoleProxySecureServerFactoryImpl.java View source code |
public SSLServerSocket createSSLServerSocket(int port) throws IOException { try { SSLServerSocket srvSock = null; SSLServerSocketFactory ssf = sslContext.getServerSocketFactory(); srvSock = (SSLServerSocket) ssf.createServerSocket(port); s_logger.info("create SSL server socket on port: " + port); return srvSock; } catch (Exception ioe) { s_logger.error(ioe.toString(), ioe); } return null; }
Example 50
| Project: cloudstack-master File: ConsoleProxySecureServerFactoryImpl.java View source code |
@Override public SSLServerSocket createSSLServerSocket(int port) throws IOException { try { SSLServerSocket srvSock = null; SSLServerSocketFactory ssf = sslContext.getServerSocketFactory(); srvSock = (SSLServerSocket) ssf.createServerSocket(port); srvSock.setEnabledProtocols(SSLUtils.getSupportedProtocols(srvSock.getEnabledProtocols())); s_logger.info("create SSL server socket on port: " + port); return srvSock; } catch (Exception ioe) { s_logger.error(ioe.toString(), ioe); } return null; }
Example 51
| Project: crux-security-core-master File: SSLConfiguratorTest.java View source code |
private SSLServerSocket startServer(SSLConfigurator config) throws GlobusSSLConfigurationException, IOException { SSLServerSocketFactory sslserversocketfactory = config.createServerFactory(); final SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(9999); ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(new Runnable() { /** * When an object implementing interface <code>Runnable</code> is * used to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p/> * The general contract of the method <code>run</code> is that it * may take any action whatsoever. * * @see Thread#run() */ public void run() { latch.countDown(); try { SSLSocket sslsocket = (SSLSocket) sslserversocket.accept(); InputStream inputstream = sslsocket.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String line; while ((line = bufferedreader.readLine()) != null) { builder.append(line); } assertEquals(builder.toString().trim(), "hello"); } catch (IOException e) { e.printStackTrace(); } } }); return sslserversocket; }
Example 52
| Project: dcm4che-master File: TCPListener.java View source code |
private ServerSocket createTLSServerSocket(Connection conn) throws IOException, GeneralSecurityException {
SSLContext sslContext = conn.getDevice().sslContext();
SSLServerSocketFactory ssf = sslContext.getServerSocketFactory();
SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket();
ss.setEnabledProtocols(conn.tlsProtocols());
ss.setEnabledCipherSuites(conn.getTlsCipherSuites());
ss.setNeedClientAuth(conn.isTlsNeedClientAuth());
return ss;
}Example 53
| Project: DrupalLoadTest-master File: TCPProxySSLSocketFactoryImplementation.java View source code |
/**
* Factory method for server sockets.
*
* @param localEndPoint Local host and port.
* @param timeout Socket timeout.
* @return A new <code>ServerSocket</code>.
* @exception IOException If an error occurs.
*/
public ServerSocket createServerSocket(EndPoint localEndPoint, int timeout) throws IOException {
final SSLServerSocket socket = (SSLServerSocket) m_serverSocketFactory.createServerSocket(localEndPoint.getPort(), 50, InetAddress.getByName(localEndPoint.getHost()));
socket.setSoTimeout(timeout);
socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());
socket.setEnabledProtocols(socket.getSupportedProtocols());
return socket;
}Example 54
| Project: ftpapi-master File: SSLDataConnection.java View source code |
/**
* Binds a server socket on the local host on a free port. This server
* socket is used for transmitting data in active mode.
*
* @exception ConnectionException
* If could not bind a server.
*/
@Override
public synchronized int bind() throws ConnectionException {
try {
SSLContext ctx = client.getSSLContext();
SSLServerSocketFactory factory = ctx.getServerSocketFactory();
// server = new ServerSocket(0, 0, client.getLocalAddress());
server = factory.createServerSocket(0, 0, client.getLocalAddress());
((SSLServerSocket) server).setUseClientMode(true);
return server.getLocalPort();
} catch (IOException exp) {
throw new ConnectionException(exp.toString());
}
}Example 55
| Project: haox-master File: Java14.java View source code |
protected final void wantClientAuth(Object o, boolean wantClientAuth) {
SSLSocket s;
SSLServerSocket ss;
if (o instanceof SSLSocket) {
s = (SSLSocket) o;
s.setWantClientAuth(wantClientAuth);
} else if (o instanceof SSLServerSocket) {
ss = (SSLServerSocket) o;
ss.setWantClientAuth(wantClientAuth);
} else {
throw new ClassCastException("need SSLSocket or SSLServerSocket");
}
}Example 56
| Project: hive-master File: HiveAuthUtils.java View source code |
public static TServerSocket getServerSSLSocket(String hiveHost, int portNum, String keyStorePath, String keyStorePassWord, List<String> sslVersionBlacklist) throws TTransportException, UnknownHostException {
TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters();
params.setKeyStore(keyStorePath, keyStorePassWord);
InetSocketAddress serverAddress;
if (hiveHost == null || hiveHost.isEmpty()) {
// Wildcard bind
serverAddress = new InetSocketAddress(portNum);
} else {
serverAddress = new InetSocketAddress(hiveHost, portNum);
}
TServerSocket thriftServerSocket = TSSLTransportFactory.getServerSocket(portNum, 0, serverAddress.getAddress(), params);
if (thriftServerSocket.getServerSocket() instanceof SSLServerSocket) {
List<String> sslVersionBlacklistLocal = new ArrayList<String>();
for (String sslVersion : sslVersionBlacklist) {
sslVersionBlacklistLocal.add(sslVersion.trim().toLowerCase());
}
SSLServerSocket sslServerSocket = (SSLServerSocket) thriftServerSocket.getServerSocket();
List<String> enabledProtocols = new ArrayList<String>();
for (String protocol : sslServerSocket.getEnabledProtocols()) {
if (sslVersionBlacklistLocal.contains(protocol.toLowerCase())) {
LOG.debug("Disabling SSL Protocol: " + protocol);
} else {
enabledProtocols.add(protocol);
}
}
sslServerSocket.setEnabledProtocols(enabledProtocols.toArray(new String[0]));
LOG.info("SSL Server Socket Enabled Protocols: " + Arrays.toString(sslServerSocket.getEnabledProtocols()));
}
return thriftServerSocket;
}Example 57
| Project: iNotes-exporter-master File: POP3Server.java View source code |
/**
* @param args
*/
public static void main(String[] args) throws IOException {
POP3Properties pop3Properties = new POP3Properties(PropertiesFileSupplier.Util.get());
lockOutFilter = new LockOutFilter(pop3Properties);
Thread pop3Thread = null, pop3sThread = null;
if (pop3Properties.getPOP3ServerPort() >= 0) {
//ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(pop3Properties.getPOP3ServerPort());
//FIXME allow to bind to a specific interface
ServerSocket serverSocket = new ServerSocket(pop3Properties.getPOP3ServerPort());
pop3Thread = new ServerAcceptorThread(serverSocket, pop3Properties);
pop3Thread.start();
} else {
logger.info("No POP3 server port found in configuration!");
}
if (pop3Properties.getPOP3SServerPort() >= 0 && StringUtils.isNotBlank(pop3Properties.getPOP3SKeyStoreName())) {
SSLServerSocketFactory sslServerSocketFactory = SSLSockets.getSSLServerSocketFactory(pop3Properties.getPOP3SKeyStoreName(), pop3Properties.getPOP3SKeyStorePassword(), pop3Properties.getPOP3SKeyStoreType(), pop3Properties.getPOP3SKeyPassword(), pop3Properties.getPOP3STrustStoreName(), pop3Properties.getPOP3STrustStorePassword(), pop3Properties.getPOP3STrustStoreType());
//FIXME allow to bind to a specific interface
SSLServerSocket serverSSLSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(pop3Properties.getPOP3SServerPort());
serverSSLSocket.setNeedClientAuth(StringUtils.isNotBlank(pop3Properties.getPOP3STrustStoreName()));
pop3sThread = new ServerAcceptorThread(serverSSLSocket, pop3Properties);
pop3sThread.start();
} else {
logger.info("No POP3S server port or KeyStoreName found in configuration!");
}
try {
if (pop3Thread != null) {
pop3Thread.join();
}
if (pop3sThread != null) {
pop3sThread.join();
}
} catch (InterruptedException ignore) {
logger.trace("serverThread.join()", ignore);
}
}Example 58
| Project: inotes-master File: POP3Server.java View source code |
/**
* @param args
*/
public static void main(String[] args) throws IOException {
POP3Properties pop3Properties = new POP3Properties(PropertiesFileSupplier.Util.get());
lockOutFilter = new LockOutFilter(pop3Properties);
Thread pop3Thread = null, pop3sThread = null;
if (pop3Properties.getPOP3ServerPort() >= 0) {
//ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(pop3Properties.getPOP3ServerPort());
//FIXME allow to bind to a specific interface
ServerSocket serverSocket = new ServerSocket(pop3Properties.getPOP3ServerPort());
pop3Thread = new ServerAcceptorThread(serverSocket, pop3Properties);
pop3Thread.start();
} else {
logger.info("No POP3 server port found in configuration!");
}
if (pop3Properties.getPOP3SServerPort() >= 0 && StringUtils.isNotBlank(pop3Properties.getPOP3SKeyStoreName())) {
SSLServerSocketFactory sslServerSocketFactory = SSLSockets.getSSLServerSocketFactory(pop3Properties.getPOP3SKeyStoreName(), pop3Properties.getPOP3SKeyStorePassword(), pop3Properties.getPOP3SKeyStoreType(), pop3Properties.getPOP3SKeyPassword(), pop3Properties.getPOP3STrustStoreName(), pop3Properties.getPOP3STrustStorePassword(), pop3Properties.getPOP3STrustStoreType());
//FIXME allow to bind to a specific interface
SSLServerSocket serverSSLSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(pop3Properties.getPOP3SServerPort());
serverSSLSocket.setNeedClientAuth(StringUtils.isNotBlank(pop3Properties.getPOP3STrustStoreName()));
pop3sThread = new ServerAcceptorThread(serverSSLSocket, pop3Properties);
pop3sThread.start();
} else {
logger.info("No POP3S server port or KeyStoreName found in configuration!");
}
try {
if (pop3Thread != null) {
pop3Thread.join();
}
if (pop3sThread != null) {
pop3sThread.join();
}
} catch (InterruptedException ignore) {
logger.trace("serverThread.join()", ignore);
}
}Example 59
| Project: jelectrum-master File: StratumServer.java View source code |
public void start() throws java.net.SocketException, java.io.IOException, java.security.GeneralSecurityException {
getEventLog().log("SERVER START");
new TimeoutThread().start();
if (config.isSet("tcp_port")) {
List<String> ports = config.getList("tcp_port");
for (String s : ports) {
int port = Integer.parseInt(s);
if (tcp_port < 0)
tcp_port = port;
ServerSocket ss = new ServerSocket(port, 256);
ss.setReuseAddress(true);
new ListenThread(ss).start();
}
}
if (config.isSet("ssl_port")) {
char ks_pass[] = config.get("keystore_store_password").toCharArray();
char key_pass[] = config.get("keystore_key_password").toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(config.get("keystore_path")), ks_pass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, key_pass);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
List<String> ports = config.getList("ssl_port");
for (String s : ports) {
int port = Integer.parseInt(s);
if (ssl_port < 0)
ssl_port = port;
SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(port, 256);
ss.setWantClientAuth(false);
ss.setNeedClientAuth(false);
ss.setReuseAddress(true);
new ListenThread(ss).start();
}
}
}Example 60
| Project: jetty-plugin-support-master File: SslBytesClientTest.java View source code |
@Before
public void init() throws Exception {
threadPool = Executors.newCachedThreadPool();
client = new HttpClient();
client.setMaxConnectionsPerAddress(1);
client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
File keyStore = MavenTestingUtils.getTestResourceFile("keystore");
SslContextFactory cf = client.getSslContextFactory();
cf.setKeyStorePath(keyStore.getAbsolutePath());
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
client.start();
SSLContext sslContext = cf.getSslContext();
acceptor = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(0);
int serverPort = acceptor.getLocalPort();
proxy = new SimpleProxy(threadPool, "localhost", serverPort);
proxy.start();
logger.debug(":{} <==> :{}", proxy.getPort(), serverPort);
}Example 61
| Project: jetty-spdy-master File: SslBytesClientTest.java View source code |
@Before
public void init() throws Exception {
threadPool = Executors.newCachedThreadPool();
client = new HttpClient();
client.setMaxConnectionsPerAddress(1);
client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
File keyStore = MavenTestingUtils.getTestResourceFile("keystore");
SslContextFactory cf = client.getSslContextFactory();
cf.setKeyStorePath(keyStore.getAbsolutePath());
cf.setKeyStorePassword("storepwd");
cf.setKeyManagerPassword("keypwd");
client.start();
SSLContext sslContext = cf.getSslContext();
acceptor = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(0);
int serverPort = acceptor.getLocalPort();
proxy = new SimpleProxy(threadPool, "localhost", serverPort);
proxy.start();
logger.debug(":{} <==> :{}", proxy.getPort(), serverPort);
}Example 62
| Project: JGlobus-master File: SSLConfiguratorTest.java View source code |
private SSLServerSocket startServer(SSLConfigurator config) throws GlobusSSLConfigurationException, IOException { SSLServerSocketFactory sslserversocketfactory = config.createServerFactory(); final SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(9991); ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(new Runnable() { /** * When an object implementing interface <code>Runnable</code> is * used to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p/> * The general contract of the method <code>run</code> is that it * may take any action whatsoever. * * @see Thread#run() */ public void run() { latch.countDown(); try { SSLSocket sslsocket = (SSLSocket) sslserversocket.accept(); InputStream inputstream = sslsocket.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String line; while ((line = bufferedreader.readLine()) != null) { builder.append(line); } assertEquals(builder.toString().trim(), "hello"); } catch (IOException e) { e.printStackTrace(); } } }); return sslserversocket; }
Example 63
| Project: logging-log4j2-master File: TlsSyslogAppenderTest.java View source code |
private void initTlsTestEnvironment(final int numberOfMessages, final TlsSyslogMessageFormat messageFormat) throws IOException {
this.messageFormat = messageFormat;
final SSLServerSocket sslServerSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(PORTNUM);
syslogServer = MockSyslogServerFactory.createTLSSyslogServer(numberOfMessages, messageFormat, sslServerSocket);
syslogServer.start();
initAppender();
}Example 64
| Project: MULE-master File: TlsConfigurationTestCase.java View source code |
@Test
public void testCipherSuitesFromConfigFile() throws Exception {
File configFile = createDefaultConfigFile();
try {
TlsConfiguration tlsConfiguration = new TlsConfiguration(TlsConfiguration.DEFAULT_KEYSTORE);
tlsConfiguration.initialise(true, TlsConfiguration.JSSE_NAMESPACE);
SSLSocket socket = (SSLSocket) tlsConfiguration.getSocketFactory().createSocket();
SSLServerSocket serverSocket = (SSLServerSocket) tlsConfiguration.getServerSocketFactory().createServerSocket();
assertArrayEquals(new String[] { SUPPORTED_CIPHER_SUITE }, socket.getEnabledCipherSuites());
assertArrayEquals(new String[] { SUPPORTED_CIPHER_SUITE }, serverSocket.getEnabledCipherSuites());
} finally {
configFile.delete();
}
}Example 65
| Project: nifi-master File: SocketUtils.java View source code |
public static ServerSocket createServerSocket(final int port, final ServerSocketConfiguration config) throws IOException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
if (config == null) {
throw new NullPointerException("Configuration may not be null.");
}
final SSLContext sslContext = config.createSSLContext();
final ServerSocket serverSocket;
if (sslContext == null) {
serverSocket = new ServerSocket(port);
} else {
serverSocket = sslContext.getServerSocketFactory().createServerSocket(port);
((SSLServerSocket) serverSocket).setNeedClientAuth(config.getNeedClientAuth());
}
if (config.getSocketTimeout() != null) {
serverSocket.setSoTimeout(config.getSocketTimeout());
}
if (config.getReuseAddress() != null) {
serverSocket.setReuseAddress(config.getReuseAddress());
}
if (config.getReceiveBufferSize() != null) {
serverSocket.setReceiveBufferSize(config.getReceiveBufferSize());
}
return serverSocket;
}Example 66
| Project: PeerDeviceNet_Src-master File: SecureSocketFactory.java View source code |
public SSLServerSocket newServerSocket() { SSLServerSocketFactory fact = (SSLServerSocketFactory) sslContext.getServerSocketFactory(); SSLServerSocket sock = null; try { sock = (SSLServerSocket) fact.createServerSocket(); } catch (IOException ioe) { Log.d(TAG, ioe.getMessage()); } return sock; }
Example 67
| Project: ploggy-master File: TransportSecurity.java View source code |
public static ServerSocket makeServerSocket(X509.KeyMaterial transportKeyMaterial, List<String> friendCertificates) throws Utils.ApplicationError {
try {
SSLContext sslContext = TransportSecurity.getSSLContext(transportKeyMaterial, friendCertificates);
SSLServerSocket sslServerSocket = (SSLServerSocket) (sslContext.getServerSocketFactory().createServerSocket());
sslServerSocket.setNeedClientAuth(true);
sslServerSocket.setEnabledCipherSuites(TLS_REQUIRED_CIPHER_SUITES);
sslServerSocket.setEnabledProtocols(TLS_REQUIRED_PROTOCOLS);
return sslServerSocket;
} catch (IllegalArgumentException e) {
throw new Utils.ApplicationError(LOG_TAG, e);
} catch (IOException e) {
throw new Utils.ApplicationError(LOG_TAG, e);
}
}Example 68
| Project: secureftp-master File: SSLUtil.java View source code |
public static SSLServerSocket createServerSocket(int port, int backlog, String host, SSLServerSocketFactory f) throws IOException, UnknownHostException { ServerSocket ss = null; if (f != null) { ss = f.createServerSocket(port, backlog, InetAddress.getByName(host)); } else { return null; } String oldCipherOrder[] = ((SSLServerSocket) ss).getSupportedCipherSuites(); //String oldCipherOrder[] = ((SSLServerSocket)ss).getEnabledCipherSuites(); ((SSLServerSocket) ss).setEnabledCipherSuites(getEnabledCipherSuites(oldCipherOrder)); return (SSLServerSocket) ss; }
Example 69
| Project: wildfly-master File: LegacySSLSocketFactory.java View source code |
public ServerSocket createSSLServerSocket(int port, int backlog, InetAddress inetAddress) throws IOException {
this.initSSLContext();
SSLServerSocketFactory serverSocketFactory = this.sslContext.getServerSocketFactory();
SSLServerSocket serverSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(port, backlog, inetAddress);
if (this.jsseSecurityDomain.getProtocols() != null) {
serverSocket.setEnabledProtocols(this.jsseSecurityDomain.getProtocols());
}
if (this.jsseSecurityDomain.getCipherSuites() != null) {
serverSocket.setEnabledCipherSuites(this.jsseSecurityDomain.getCipherSuites());
}
if (this.jsseSecurityDomain.isClientAuth() || this.require_mutual_auth) {
serverSocket.setNeedClientAuth(true);
} else {
serverSocket.setWantClientAuth(this.request_mutual_auth);
}
return serverSocket;
}Example 70
| Project: activemq-artemis-master File: JaasDualAuthenticationBrokerTest.java View source code |
@Override
protected void setUp() throws Exception {
receiveBroker = new StubBroker();
authBroker = new JaasDualAuthenticationBroker(receiveBroker, "activemq-domain", "activemq-ssl-domain");
connectionContext = new ConnectionContext();
SSLServerSocket sslServerSocket = new StubSSLServerSocket();
StubSSLSocketFactory socketFactory = new StubSSLSocketFactory(sslServerSocket);
try {
sslTransportServer = new SslTransportServer(null, new URI("ssl://localhost:61616?needClientAuth=true"), socketFactory);
} catch (Exception e) {
fail("Unable to create SslTransportServer.");
}
sslTransportServer.setNeedClientAuth(true);
sslTransportServer.bind();
try {
nonSslTransportServer = new TcpTransportServer(null, new URI("tcp://localhost:61613"), socketFactory);
} catch (Exception e) {
fail("Unable to create TcpTransportServer.");
}
connectionInfo = new ConnectionInfo();
createLoginConfig();
}Example 71
| Project: android-rcs-ims-stack-master File: TLSMessageProcessor.java View source code |
/**
* Start the processor.
*/
public void start() throws IOException {
Thread thread = new Thread(this);
thread.setName("TLSMessageProcessorThread");
// ISSUE 184
thread.setPriority(Thread.MAX_PRIORITY);
thread.setDaemon(true);
this.sock = sipStack.getNetworkLayer().createSSLServerSocket(this.getPort(), 0, this.getIpAddress());
((SSLServerSocket) this.sock).setNeedClientAuth(false);
((SSLServerSocket) this.sock).setUseClientMode(false);
((SSLServerSocket) this.sock).setWantClientAuth(true);
String[] enabledCiphers = ((SipStackImpl) sipStack).getEnabledCipherSuites();
((SSLServerSocket) this.sock).setEnabledCipherSuites(enabledCiphers);
((SSLServerSocket) this.sock).setWantClientAuth(true);
this.isRunning = true;
thread.start();
}Example 72
| Project: android-servlet-container-master File: HttpsListener.java View source code |
/**
* Gets a server socket - this gets as SSL socket instead of the standard
* socket returned in the base class.
*/
protected ServerSocket getServerSocket() throws IOException {
// Just to make sure it's set before we start
SSLContext context = getSSLContext(this.keystore, this.password);
SSLServerSocketFactory factory = context.getServerSocketFactory();
SSLServerSocket ss = (SSLServerSocket) (this.listenAddress == null ? factory.createServerSocket(this.listenPort, BACKLOG_COUNT) : factory.createServerSocket(this.listenPort, BACKLOG_COUNT, InetAddress.getByName(this.listenAddress)));
ss.setEnableSessionCreation(true);
ss.setWantClientAuth(true);
return ss;
}Example 73
| Project: bigpetstore-master File: Krb5AndCertsSslSocketConnector.java View source code |
/* (non-Javadoc)
* @see org.mortbay.jetty.security.SslSocketConnector#newServerSocket(java.lang.String, int, int)
*/
@Override
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
logIfDebug("Creating new KrbServerSocket for: " + host);
SSLServerSocket ss = null;
if (// Get the server socket from the SSL super impl
useCerts)
ss = (SSLServerSocket) super.newServerSocket(host, port, backlog);
else {
// Create a default server socket
try {
ss = (SSLServerSocket) (host == null ? createFactory().createServerSocket(port, backlog) : createFactory().createServerSocket(port, backlog, InetAddress.getByName(host)));
} catch (Exception e) {
LOG.warn("Could not create KRB5 Listener", e);
throw new IOException("Could not create KRB5 Listener: " + e.toString());
}
}
// Add Kerberos ciphers to this socket server if needed.
if (useKrb) {
ss.setNeedClientAuth(true);
String[] combined;
if (useCerts) {
// combine the cipher suites
String[] certs = ss.getEnabledCipherSuites();
combined = new String[certs.length + KRB5_CIPHER_SUITES.size()];
System.arraycopy(certs, 0, combined, 0, certs.length);
System.arraycopy(KRB5_CIPHER_SUITES.toArray(new String[0]), 0, combined, certs.length, KRB5_CIPHER_SUITES.size());
} else {
// Just enable Kerberos auth
combined = KRB5_CIPHER_SUITES.toArray(new String[0]);
}
ss.setEnabledCipherSuites(combined);
}
return ss;
}Example 74
| Project: camel-master File: SSLContextServerParameters.java View source code |
@Override public SSLServerSocket configure(SSLServerSocket socket) { LOG.trace("Configuring client-auth on SSLServerSocket [{}] to [{}].", socket, clientAuthValue); switch(clientAuthValue) { case NONE: socket.setWantClientAuth(false); socket.setNeedClientAuth(false); break; case WANT: socket.setWantClientAuth(true); break; case REQUIRE: socket.setNeedClientAuth(true); break; default: throw new RuntimeCamelException("Unknown ClientAuthentication value: " + clientAuthValue); } return socket; }
Example 75
| Project: CassandraQoS-master File: SSLFactory.java View source code |
public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port) throws IOException { SSLContext ctx = createSSLContext(options, true); SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(); serverSocket.setReuseAddress(true); String[] suits = filterCipherSuites(serverSocket.getSupportedCipherSuites(), options.cipher_suites); serverSocket.setEnabledCipherSuites(suits); serverSocket.setNeedClientAuth(options.require_client_auth); serverSocket.setEnabledProtocols(ACCEPTED_PROTOCOLS); serverSocket.bind(new InetSocketAddress(address, port), 500); return serverSocket; }
Example 76
| Project: cdh-mesos-master File: Krb5AndCertsSslSocketConnector.java View source code |
/* (non-Javadoc)
* @see org.mortbay.jetty.security.SslSocketConnector#newServerSocket(java.lang.String, int, int)
*/
@Override
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
logIfDebug("Creating new KrbServerSocket for: " + host);
SSLServerSocket ss = null;
if (// Get the server socket from the SSL super impl
useCerts)
ss = (SSLServerSocket) super.newServerSocket(host, port, backlog);
else {
// Create a default server socket
try {
ss = (SSLServerSocket) (host == null ? createFactory().createServerSocket(port, backlog) : createFactory().createServerSocket(port, backlog, InetAddress.getByName(host)));
} catch (Exception e) {
LOG.warn("Could not create KRB5 Listener", e);
throw new IOException("Could not create KRB5 Listener: " + e.toString());
}
}
// Add Kerberos ciphers to this socket server if needed.
if (useKrb) {
ss.setNeedClientAuth(true);
String[] combined;
if (useCerts) {
// combine the cipher suites
String[] certs = ss.getEnabledCipherSuites();
combined = new String[certs.length + KRB5_CIPHER_SUITES.size()];
System.arraycopy(certs, 0, combined, 0, certs.length);
System.arraycopy(KRB5_CIPHER_SUITES.toArray(new String[0]), 0, combined, certs.length, KRB5_CIPHER_SUITES.size());
} else {
// Just enable Kerberos auth
combined = KRB5_CIPHER_SUITES.toArray(new String[0]);
}
ss.setEnabledCipherSuites(combined);
}
return ss;
}Example 77
| Project: cdh3u3-with-mesos-master File: Krb5AndCertsSslSocketConnector.java View source code |
/* (non-Javadoc)
* @see org.mortbay.jetty.security.SslSocketConnector#newServerSocket(java.lang.String, int, int)
*/
@Override
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
logIfDebug("Creating new KrbServerSocket for: " + host);
SSLServerSocket ss = null;
if (// Get the server socket from the SSL super impl
useCerts)
ss = (SSLServerSocket) super.newServerSocket(host, port, backlog);
else {
// Create a default server socket
try {
ss = (SSLServerSocket) (host == null ? createFactory().createServerSocket(port, backlog) : createFactory().createServerSocket(port, backlog, InetAddress.getByName(host)));
} catch (Exception e) {
LOG.warn("Could not create KRB5 Listener", e);
throw new IOException("Could not create KRB5 Listener: " + e.toString());
}
}
// Add Kerberos ciphers to this socket server if needed.
if (useKrb) {
ss.setNeedClientAuth(true);
String[] combined;
if (useCerts) {
// combine the cipher suites
String[] certs = ss.getEnabledCipherSuites();
combined = new String[certs.length + KRB5_CIPHER_SUITES.size()];
System.arraycopy(certs, 0, combined, 0, certs.length);
System.arraycopy(KRB5_CIPHER_SUITES.toArray(new String[0]), 0, combined, certs.length, KRB5_CIPHER_SUITES.size());
} else {
// Just enable Kerberos auth
combined = KRB5_CIPHER_SUITES.toArray(new String[0]);
}
ss.setEnabledCipherSuites(combined);
}
return ss;
}Example 78
| Project: ecf-master File: SSLServerSOContainerGroup.java View source code |
public synchronized void putOnTheAir() throws IOException {
//$NON-NLS-1$ //$NON-NLS-2$
trace("SSLServerSOContainerGroup at port " + port + " on the air");
if (this.serverSocket == null) {
SSLServerSocketFactory socketFactory = ProviderPlugin.getDefault().getSSLServerSocketFactory();
if (socketFactory == null)
throw new //$NON-NLS-1$
IOException(//$NON-NLS-1$
"Cannot get SSLServerSocketFactory to create SSLServerSocket");
serverSocket = (SSLServerSocket) ((this.inetAddress == null) ? socketFactory.createServerSocket(this.port, this.backlog) : socketFactory.createServerSocket(this.port, this.backlog, this.inetAddress));
}
port = serverSocket.getLocalPort();
isOnTheAir = true;
listenerThread.start();
}Example 79
| Project: etch-master File: TlsListener.java View source code |
@Override
protected synchronized boolean openSocket(boolean reconnect) throws Exception {
boolean first = true;
while (isStarted()) {
if (reconnect || !first)
return false;
try {
InetAddress h = host != null ? InetAddress.getByName(host) : null;
try {
// serverSocket = new ServerSocket( port, backlog, h );
initializeSSLVariables();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(KEYSTORE), KEYSTOREPW);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, KEYPAIRPWD);
SSLContext sslc = SSLContext.getInstance("SSLv3");
sslc.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketFactory = sslc.getServerSocketFactory();
/* SSLServerSocketFactory sslServerSocketFactory =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); */
sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(port, backlog, h);
} catch (BindException e) {
throw new BindException("Address already in use: " + h + ":" + port);
} catch (IOException ex) {
IOException exc = new IOException(" Problem in setting up SSL Connection. In order to use SSL " + " please specify valid keystore location and password using VM arguments.");
exc.setStackTrace(ex.getStackTrace());
fireException("open", exc);
return false;
}
return true;
} catch (Exception e) {
if (first) {
first = false;
fireException("open", e);
}
}
}
return false;
}Example 80
| Project: ffmq-master File: TcpListener.java View source code |
private ServerSocket createServerSocket(int port, int tcpBackLog, InetAddress localAddr, boolean useSSL) throws JMSException {
try {
if (useSSL) {
SSLServerSocket socket = (SSLServerSocket) createSSLContext().getServerSocketFactory().createServerSocket(port, tcpBackLog, localAddr);
socket.setNeedClientAuth(false);
return socket;
} else
return new ServerSocket(port, tcpBackLog, localAddr);
} catch (Exception e) {
throw new FFMQException("Cannot create server socket", "NETWORK_ERROR", e);
}
}Example 81
| Project: flink-master File: SSLUtilsTest.java View source code |
/** * Tests if SSLUtils set the right ssl version and cipher suites for SSLServerSocket */ @Test public void testSetSSLVersionAndCipherSuitesForSSLServerSocket() throws Exception { Configuration serverConfig = new Configuration(); serverConfig.setBoolean(ConfigConstants.SECURITY_SSL_ENABLED, true); serverConfig.setString(ConfigConstants.SECURITY_SSL_KEYSTORE, "src/test/resources/local127.keystore"); serverConfig.setString(ConfigConstants.SECURITY_SSL_KEYSTORE_PASSWORD, "password"); serverConfig.setString(ConfigConstants.SECURITY_SSL_KEY_PASSWORD, "password"); serverConfig.setString(ConfigConstants.SECURITY_SSL_PROTOCOL, "TLSv1.1"); serverConfig.setString(ConfigConstants.SECURITY_SSL_ALGORITHMS, "TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA256"); SSLContext serverContext = SSLUtils.createSSLServerContext(serverConfig); ServerSocket socket = null; try { socket = serverContext.getServerSocketFactory().createServerSocket(0); String[] protocols = ((SSLServerSocket) socket).getEnabledProtocols(); String[] algorithms = ((SSLServerSocket) socket).getEnabledCipherSuites(); Assert.assertNotEquals(1, protocols.length); Assert.assertNotEquals(2, algorithms.length); SSLUtils.setSSLVerAndCipherSuites(socket, serverConfig); protocols = ((SSLServerSocket) socket).getEnabledProtocols(); algorithms = ((SSLServerSocket) socket).getEnabledCipherSuites(); Assert.assertEquals(1, protocols.length); Assert.assertEquals("TLSv1.1", protocols[0]); Assert.assertEquals(2, algorithms.length); Assert.assertTrue(algorithms[0].equals("TLS_RSA_WITH_AES_128_CBC_SHA") || algorithms[0].equals("TLS_RSA_WITH_AES_128_CBC_SHA256")); Assert.assertTrue(algorithms[1].equals("TLS_RSA_WITH_AES_128_CBC_SHA") || algorithms[1].equals("TLS_RSA_WITH_AES_128_CBC_SHA256")); } finally { if (socket != null) { socket.close(); } } }
Example 82
| Project: glassfish-main-master File: SecureRMIServerSocketFactory.java View source code |
@Override
public ServerSocket createServerSocket(int port) throws IOException {
//debug( "MyRMIServerSocketFactory.createServerSocket(): " + mAddress + " : " + port );
if (socketMap.containsKey(port)) {
return (ServerSocket) socketMap.get(port);
}
// plenty
final int backlog = 5;
// we use a custom class here. The reason is mentioned in the class.
final JMXSslConfigHolder sslConfigHolder;
try {
sslConfigHolder = new JMXSslConfigHolder(habitat, ssl);
} catch (SSLException ssle) {
throw new IllegalStateException(ssle);
}
final SSLContext context = sslConfigHolder.getSslContext();
SSLServerSocket sslSocket = (SSLServerSocket) context.getServerSocketFactory().createServerSocket(port, backlog, mAddress);
configureSSLSocket(sslSocket, sslConfigHolder);
Util.getLogger().info("SSLServerSocket " + sslSocket.getLocalSocketAddress() + "and " + sslSocket.toString() + " created");
//sslSocket.startHandshake();
//debug( "MyRMIServerSocketFactory.createServerSocket(): " + mAddress + " : " + port );
socketMap.put(port, sslSocket);
return sslSocket;
}Example 83
| Project: H2-Research-master File: TestNetUtils.java View source code |
/**
* TLS connections (without trusted certificates) should fail if the server
* does not allow anonymous TLS.
* The global property ENABLE_ANONYMOUS_TLS cannot be modified for the test;
* instead, the server socket is altered.
*/
private void testTlsSessionWithServerSideAnonymousDisabled() throws Exception {
boolean ssl = true;
Task task = null;
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = NetUtils.createServerSocket(PORT, ssl);
serverSocket.setSoTimeout(WAIT_LONGER_MILLIS);
// emulate the situation ENABLE_ANONYMOUS_TLS=false on server side
String[] defaultCipherSuites = SSLContext.getDefault().getServerSocketFactory().getDefaultCipherSuites();
((SSLServerSocket) serverSocket).setEnabledCipherSuites(defaultCipherSuites);
task = createServerSocketTask(serverSocket);
task.execute(TASK_PREFIX + "AnonDisabled");
Thread.sleep(WAIT_MILLIS);
socket = NetUtils.createLoopbackSocket(PORT, ssl);
assertTrue("loopback socket should be connected", socket.isConnected());
// Java 6 API does not have getHandshakeSession() which could
// reveal the actual cipher selected in the attempted handshake
SSLSession session = ((SSLSocket) socket).getSession();
assertFalse("TLS session should be invalid when the server" + "disables anonymous TLS", session.isValid());
// the SSL handshake should fail, because non-anon ciphers require
// a trusted certificate
assertEquals("SSL_NULL_WITH_NULL_NULL", session.getCipherSuite());
} finally {
closeSilently(socket);
closeSilently(serverSocket);
if (task != null) {
assertTrue(task.getException() != null);
assertEquals(javax.net.ssl.SSLHandshakeException.class.getName(), task.getException().getClass().getName());
assertContains(task.getException().getMessage(), "certificate_unknown");
task.join();
}
}
}Example 84
| Project: h2database-master File: TestNetUtils.java View source code |
/**
* TLS connections (without trusted certificates) should fail if the server
* does not allow anonymous TLS.
* The global property ENABLE_ANONYMOUS_TLS cannot be modified for the test;
* instead, the server socket is altered.
*/
private void testTlsSessionWithServerSideAnonymousDisabled() throws Exception {
boolean ssl = true;
Task task = null;
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = NetUtils.createServerSocket(PORT, ssl);
serverSocket.setSoTimeout(WAIT_LONGER_MILLIS);
// emulate the situation ENABLE_ANONYMOUS_TLS=false on server side
String[] defaultCipherSuites = SSLContext.getDefault().getServerSocketFactory().getDefaultCipherSuites();
((SSLServerSocket) serverSocket).setEnabledCipherSuites(defaultCipherSuites);
task = createServerSocketTask(serverSocket);
task.execute(TASK_PREFIX + "AnonDisabled");
Thread.sleep(WAIT_MILLIS);
socket = NetUtils.createLoopbackSocket(PORT, ssl);
assertTrue("loopback socket should be connected", socket.isConnected());
// Java 6 API does not have getHandshakeSession() which could
// reveal the actual cipher selected in the attempted handshake
SSLSession session = ((SSLSocket) socket).getSession();
assertFalse("TLS session should be invalid when the server" + "disables anonymous TLS", session.isValid());
// the SSL handshake should fail, because non-anon ciphers require
// a trusted certificate
assertEquals("SSL_NULL_WITH_NULL_NULL", session.getCipherSuite());
} finally {
closeSilently(socket);
closeSilently(serverSocket);
if (task != null) {
assertTrue(task.getException() != null);
assertEquals(javax.net.ssl.SSLHandshakeException.class.getName(), task.getException().getClass().getName());
assertContains(task.getException().getMessage(), "certificate_unknown");
task.join();
}
}
}Example 85
| Project: hadoop-1.0.3-gpu-master File: Krb5AndCertsSslSocketConnector.java View source code |
/* (non-Javadoc)
* @see org.mortbay.jetty.security.SslSocketConnector#newServerSocket(java.lang.String, int, int)
*/
@Override
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
logIfDebug("Creating new KrbServerSocket for: " + host);
SSLServerSocket ss = null;
if (// Get the server socket from the SSL super impl
useCerts)
ss = (SSLServerSocket) super.newServerSocket(host, port, backlog);
else {
// Create a default server socket
try {
ss = (SSLServerSocket) (host == null ? createFactory().createServerSocket(port, backlog) : createFactory().createServerSocket(port, backlog, InetAddress.getByName(host)));
} catch (Exception e) {
LOG.warn("Could not create KRB5 Listener", e);
throw new IOException("Could not create KRB5 Listener: " + e.toString());
}
}
// Add Kerberos ciphers to this socket server if needed.
if (useKrb) {
ss.setNeedClientAuth(true);
String[] combined;
if (useCerts) {
// combine the cipher suites
String[] certs = ss.getEnabledCipherSuites();
combined = new String[certs.length + KRB5_CIPHER_SUITES.size()];
System.arraycopy(certs, 0, combined, 0, certs.length);
System.arraycopy(KRB5_CIPHER_SUITES.toArray(new String[0]), 0, combined, certs.length, KRB5_CIPHER_SUITES.size());
} else {
// Just enable Kerberos auth
combined = KRB5_CIPHER_SUITES.toArray(new String[0]);
}
ss.setEnabledCipherSuites(combined);
}
return ss;
}Example 86
| Project: hadoop-src-research-master File: Krb5AndCertsSslSocketConnector.java View source code |
/* (non-Javadoc)
* @see org.mortbay.jetty.security.SslSocketConnector#newServerSocket(java.lang.String, int, int)
*/
@Override
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
logIfDebug("Creating new KrbServerSocket for: " + host);
SSLServerSocket ss = null;
if (// Get the server socket from the SSL super impl
useCerts)
ss = (SSLServerSocket) super.newServerSocket(host, port, backlog);
else {
// Create a default server socket
try {
ss = (SSLServerSocket) (host == null ? createFactory().createServerSocket(port, backlog) : createFactory().createServerSocket(port, backlog, InetAddress.getByName(host)));
} catch (Exception e) {
LOG.warn("Could not create KRB5 Listener", e);
throw new IOException("Could not create KRB5 Listener: " + e.toString());
}
}
// Add Kerberos ciphers to this socket server if needed.
if (useKrb) {
ss.setNeedClientAuth(true);
String[] combined;
if (useCerts) {
// combine the cipher suites
String[] certs = ss.getEnabledCipherSuites();
combined = new String[certs.length + KRB5_CIPHER_SUITES.size()];
System.arraycopy(certs, 0, combined, 0, certs.length);
System.arraycopy(KRB5_CIPHER_SUITES.toArray(new String[0]), 0, combined, certs.length, KRB5_CIPHER_SUITES.size());
} else {
// Just enable Kerberos auth
combined = KRB5_CIPHER_SUITES.toArray(new String[0]);
}
ss.setEnabledCipherSuites(combined);
}
return ss;
}Example 87
| Project: hdfs-cloudera-cdh3u3-production-master File: Krb5AndCertsSslSocketConnector.java View source code |
/* (non-Javadoc)
* @see org.mortbay.jetty.security.SslSocketConnector#newServerSocket(java.lang.String, int, int)
*/
@Override
protected ServerSocket newServerSocket(String host, int port, int backlog) throws IOException {
logIfDebug("Creating new KrbServerSocket for: " + host);
SSLServerSocket ss = null;
if (// Get the server socket from the SSL super impl
useCerts)
ss = (SSLServerSocket) super.newServerSocket(host, port, backlog);
else {
// Create a default server socket
try {
ss = (SSLServerSocket) (host == null ? createFactory().createServerSocket(port, backlog) : createFactory().createServerSocket(port, backlog, InetAddress.getByName(host)));
} catch (Exception e) {
LOG.warn("Could not create KRB5 Listener", e);
throw new IOException("Could not create KRB5 Listener: " + e.toString());
}
}
// Add Kerberos ciphers to this socket server if needed.
if (useKrb) {
ss.setNeedClientAuth(true);
String[] combined;
if (useCerts) {
// combine the cipher suites
String[] certs = ss.getEnabledCipherSuites();
combined = new String[certs.length + KRB5_CIPHER_SUITES.size()];
System.arraycopy(certs, 0, combined, 0, certs.length);
System.arraycopy(KRB5_CIPHER_SUITES.toArray(new String[0]), 0, combined, certs.length, KRB5_CIPHER_SUITES.size());
} else {
// Just enable Kerberos auth
combined = KRB5_CIPHER_SUITES.toArray(new String[0]);
}
ss.setEnabledCipherSuites(combined);
}
return ss;
}Example 88
| Project: hq-master File: SSLConnectionListener.java View source code |
public void setup(int timeout) throws AgentStartException {
AgentConfig cfg = this.getConfig();
AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
SSLProvider provider = new HQSSLProviderImpl(keystoreConfig, keystoreConfig.isAcceptUnverifiedCert());
SSLContext context = provider.getSSLContext();
SSLServerSocketFactory sFactory = context.getServerSocketFactory();
InetAddress addr;
try {
addr = cfg.getListenIpAsAddr();
} catch (UnknownHostException exc) {
throw new AgentStartException("Failed to setup listen socket on '" + cfg.getListenIp() + "': unknown host");
}
int port = cfg.getListenPort();
// the agent to start
while (true) {
try {
listenSock = (SSLServerSocket) sFactory.createServerSocket(port, 50, addr);
listenSock.setEnabledCipherSuites(getSupportedAndEnabledCiphers(cfg.getEnabledCipherList(), sFactory));
listenSock.setSoTimeout(timeout);
break;
} catch (IOException exc) {
if (listenSock != null) {
try {
listenSock.close();
} catch (IOException e1) {
log.debug(e1, e1);
}
}
log.warn("Failed to listen at " + cfg.getListenIp() + ":" + port + ": " + exc.getMessage() + ". Will retry until up.");
log.debug(exc, exc);
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
log.debug(e, e);
}
}
}
}Example 89
| Project: httpcomponents-core-master File: HttpServer.java View source code |
public void start() throws IOException {
if (this.status.compareAndSet(Status.READY, Status.ACTIVE)) {
this.serverSocket = this.serverSocketFactory.createServerSocket(this.port, this.socketConfig.getBacklogSize(), this.ifAddress);
this.serverSocket.setReuseAddress(this.socketConfig.isSoReuseAddress());
if (this.socketConfig.getRcvBufSize() > 0) {
this.serverSocket.setReceiveBufferSize(this.socketConfig.getRcvBufSize());
}
if (this.sslSetupHandler != null && this.serverSocket instanceof SSLServerSocket) {
this.sslSetupHandler.initialize((SSLServerSocket) this.serverSocket);
}
this.requestListener = new RequestListener(this.socketConfig, this.serverSocket, this.httpService, this.connectionFactory, this.exceptionListener, this.workerExecutorService);
this.listenerExecutorService.execute(this.requestListener);
}
}Example 90
| Project: i2p.i2p-master File: SSLClientListenerRunner.java View source code |
/**
* Get a SSLServerSocket.
*/
@Override
protected ServerSocket getServerSocket() throws IOException {
ServerSocket rv;
if (_bindAllInterfaces) {
if (_log.shouldLog(Log.INFO))
_log.info("Listening on port " + _port + " on all interfaces");
rv = _factory.createServerSocket(_port);
} else {
String listenInterface = _context.getProperty(ClientManagerFacadeImpl.PROP_CLIENT_HOST, ClientManagerFacadeImpl.DEFAULT_HOST);
if (_log.shouldLog(Log.INFO))
_log.info("Listening on port " + _port + " of the specific interface: " + listenInterface);
rv = _factory.createServerSocket(_port, 0, InetAddress.getByName(listenInterface));
}
I2PSSLSocketFactory.setProtocolsAndCiphers((SSLServerSocket) rv);
return rv;
}Example 91
| Project: IOCipherServer-master File: SSLAcceptor.java View source code |
/**
* Set the requested properties for this server socket.
*
* @param ssocket
* The server socket to be configured
*/
protected void initServerSocket(ServerSocket ssocket, boolean clientAuth) {
SSLServerSocket socket = (SSLServerSocket) ssocket;
// Enable all available cipher suites when the socket is connected
String cipherSuites[] = socket.getSupportedCipherSuites();
socket.setEnabledCipherSuites(cipherSuites);
// Set client authentication if necessary
socket.setNeedClientAuth(clientAuth);
}Example 92
| Project: JamVM-PH-master File: SslRMIServerSocketFactory.java View source code |
/** * Creates an SSLServerSocket on a given port * * @throws IOException if an error occurs on socket creation. */ public ServerSocket createServerSocket(int port) throws IOException { SSLServerSocket socket = (SSLServerSocket) socketFactory.createServerSocket(port); if (enabledCipherSuites != null) socket.setEnabledCipherSuites(enabledCipherSuites); if (enabledProtocols != null) socket.setEnabledProtocols(enabledProtocols); socket.setNeedClientAuth(needClientAuth); return socket; }
Example 93
| Project: java-apns-master File: ApnsServerStub.java View source code |
@SuppressWarnings("InfiniteLoopStatement")
public void run() {
Thread.currentThread().setName("GatewayThread");
try {
gatewaySocket = (SSLServerSocket) sslFactory.createServerSocket(gatewayPort);
gatewaySocket.setNeedClientAuth(true);
} catch (IOException e) {
messages.release();
throw new RuntimeException(e);
}
InputStream in = null;
effectiveGatewayPort = gatewaySocket.getLocalPort();
try {
// Listen for connections
startUp.release();
while (true) {
Socket socket = gatewaySocket.accept();
// Work around JVM deadlock ... https://community.oracle.com/message/10989561#10989561
socket.setSoLinger(true, 1);
// Create streams to securely send and receive data to the client
in = socket.getInputStream();
gatewayOutputStream = socket.getOutputStream();
gatewayOutLock.release();
// Read from in and write to out...
byte[] read = readFully(in);
waitBeforeSend();
received.write(read);
messages.release();
waitForError.acquire();
// Close the socket
in.close();
gatewayOutputStream.close();
}
} catch (Throwable e) {
try {
if (in != null) {
in.close();
}
} catch (IOException ioex) {
LOGGER.warn("Can not close socket properly", ioex);
}
try {
if (gatewayOutputStream != null) {
gatewayOutputStream.close();
}
} catch (IOException ioex) {
LOGGER.warn("Can not close gatewayOutputStream properly", ioex);
}
messages.release();
}
}Example 94
| Project: JBossAS51-master File: DomainServerSocketFactory.java View source code |
/**
* Returns a server socket which uses only the specified network interface on the local host, is bound to a the
* specified port, and uses the specified connection backlog. The socket is configured with the socket options (such
* as accept timeout) given to this factory.
*
* @param port the port to listen to
* @param backlog how many connections are queued
* @param ifAddress the network interface address to use
*
* @exception IOException for networking errors
*/
@Override
public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException {
initSSLContext();
SSLServerSocketFactory factory = sslCtx.getServerSocketFactory();
SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(port, backlog, ifAddress);
SSLSessionContext ctx = sslCtx.getServerSessionContext();
System.out.println(ctx);
if (log.isTraceEnabled()) {
String[] supportedProtocols = socket.getSupportedProtocols();
log.debug("Supported protocols: " + Arrays.asList(supportedProtocols));
String[] supportedCipherSuites = socket.getSupportedCipherSuites();
log.debug("Supported CipherSuites: " + Arrays.asList(supportedCipherSuites));
}
socket.setNeedClientAuth(needsClientAuth);
// JBAS-5815: only set the wantClientAuth property if needClientAuth hasn't been already set.
if (!needsClientAuth)
socket.setWantClientAuth(wantsClientAuth);
if (protocols != null)
socket.setEnabledProtocols(protocols);
if (cipherSuites != null)
socket.setEnabledCipherSuites(cipherSuites);
DomainServerSocket handler = new DomainServerSocket(socket);
ProxyFactory pf = new ProxyFactory();
pf.setHandler(handler);
pf.setSuperclass(SSLServerSocket.class);
Class[] sig = {};
Object[] args = {};
SSLServerSocket proxy = null;
try {
proxy = (SSLServerSocket) pf.create(sig, args);
} catch (Exception e) {
IOException ioe = new IOException("Failed to create SSLServerSocket proxy");
ioe.initCause(e);
throw ioe;
}
return proxy;
}Example 95
| Project: JBossAS_5_1_EDG-master File: DomainServerSocketFactory.java View source code |
/**
* Returns a server socket which uses only the specified network interface on the local host, is bound to a the
* specified port, and uses the specified connection backlog. The socket is configured with the socket options (such
* as accept timeout) given to this factory.
*
* @param port the port to listen to
* @param backlog how many connections are queued
* @param ifAddress the network interface address to use
*
* @exception IOException for networking errors
*/
@Override
public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException {
initSSLContext();
SSLServerSocketFactory factory = sslCtx.getServerSocketFactory();
SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(port, backlog, ifAddress);
SSLSessionContext ctx = sslCtx.getServerSessionContext();
System.out.println(ctx);
if (log.isTraceEnabled()) {
String[] supportedProtocols = socket.getSupportedProtocols();
log.debug("Supported protocols: " + Arrays.asList(supportedProtocols));
String[] supportedCipherSuites = socket.getSupportedCipherSuites();
log.debug("Supported CipherSuites: " + Arrays.asList(supportedCipherSuites));
}
socket.setNeedClientAuth(needsClientAuth);
// JBAS-5815: only set the wantClientAuth property if needClientAuth hasn't been already set.
if (!needsClientAuth)
socket.setWantClientAuth(wantsClientAuth);
if (protocols != null)
socket.setEnabledProtocols(protocols);
if (cipherSuites != null)
socket.setEnabledCipherSuites(cipherSuites);
DomainServerSocket handler = new DomainServerSocket(socket);
ProxyFactory pf = new ProxyFactory();
pf.setHandler(handler);
pf.setSuperclass(SSLServerSocket.class);
Class[] sig = {};
Object[] args = {};
SSLServerSocket proxy = null;
try {
proxy = (SSLServerSocket) pf.create(sig, args);
} catch (Exception e) {
IOException ioe = new IOException("Failed to create SSLServerSocket proxy");
ioe.initCause(e);
throw ioe;
}
return proxy;
}Example 96
| Project: JNRPE-LIB-master File: CBindingThread.java View source code |
private void init() throws IOException, KeyManagementException, KeyStoreException, CertificateException, UnrecoverableKeyException {
InetAddress addr = InetAddress.getByName(m_Binding.getIP());
ServerSocketFactory sf = null;
if (m_Binding.useSSL())
sf = getSSLSocketFactory(m_Binding.getKeyStoreFile(), m_Binding.getKeyStorePassword(), "JKS");
else
sf = ServerSocketFactory.getDefault();
m_serverSocket = sf.createServerSocket(m_Binding.getPort(), 0, addr);
//m_serverSocket.setSoTimeout(10000); //Ten seconds timeout added by oriol.lopez
if (m_serverSocket instanceof SSLServerSocket)
((SSLServerSocket) m_serverSocket).setEnabledCipherSuites(((SSLServerSocket) m_serverSocket).getSupportedCipherSuites());
// Init the thread factory
m_threadFactory = new CThreadFactory(m_Binding.getThreadFactoryConfig());
}Example 97
| Project: limewire5-ruby-master File: ServerSideConnectBackRedirectTest.java View source code |
public void testTCPTSLConnectBackRedirect() throws Exception {
drainAll();
// first attempt with be with TLS
TCP_ACCESS.close();
TCP_ACCESS = SSLServerSocketFactory.getDefault().createServerSocket(TCP_ACCESS_PORT);
SSLServerSocket sslss = (SSLServerSocket) TCP_ACCESS;
sslss.setEnabledCipherSuites(new String[] { "TLS_DH_anon_WITH_AES_128_CBC_SHA" });
TCPConnectBackRedirect tcp = new TCPConnectBackRedirect(InetAddress.getLocalHost(), TCP_ACCESS.getLocalPort());
LEAF[0].send(tcp);
LEAF[0].flush();
// we should NOT get a incoming connection
TCP_ACCESS.setSoTimeout(1000);
try {
TCP_ACCESS.accept();
fail("got IOX");
} catch (IOException good) {
}
tcp = new TCPConnectBackRedirect(InetAddress.getLocalHost(), TCP_ACCESS.getLocalPort());
ULTRAPEER[0].send(tcp);
ULTRAPEER[0].flush();
// we should get a incoming connection
try {
Socket x = TCP_ACCESS.accept();
// just like Acceptor reads words.
String word = IOUtils.readLargestWord(x.getInputStream(), 8);
assertEquals("CONNECT", word);
} catch (IOException bad) {
fail("got IOX", bad);
}
}Example 98
| Project: multibit-hd-master File: PaymentProtocolHttpsServer.java View source code |
/**
* @return True if the server started OK
*/
public boolean start() {
InputStream is = null;
try {
log.debug("Initialise the trust store containing the trusted certificates (including localhost:8443)");
URL trustStoreUrl = PaymentProtocolHttpsServer.class.getResource("/mbhd-cacerts-with-localhost");
System.setProperty("javax.net.ssl.trustStore", trustStoreUrl.getFile());
System.setProperty("javax.net.ssl.trustStorePassword", HttpsManager.PASSPHRASE);
SSLContext sslContext = SSLContext.getInstance("TLS");
log.debug("Initialise the key store containing the private server keys (CN=localhost is required)");
KeyStore ks = KeyStore.getInstance("JKS");
is = PaymentProtocolHttpsServer.class.getResourceAsStream("/localhost.jks");
ks.load(is, HttpsManager.PASSPHRASE.toCharArray());
log.debug("Initialise the key manager factory");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, HttpsManager.PASSPHRASE.toCharArray());
log.debug("Initialise the trust manager factory");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
// Setup the HTTPS context and parameters
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
// Create a ServerSocketFactory from the SSLContext
ServerSocketFactory ssf = sslContext.getServerSocketFactory();
// Create unauthenticated server socket on localhost:8443
serverSocket = (SSLServerSocket) ssf.createServerSocket(8443);
serverSocket.setNeedClientAuth(false);
serverSocket.setWantClientAuth(false);
String[] suites = serverSocket.getSupportedCipherSuites();
serverSocket.setEnabledCipherSuites(suites);
return true;
} catch (Exception e) {
log.error("Failed to create HTTPS server", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ioe) {
log.error("Failed to close key store", ioe);
}
}
}
// Must have failed to be here
return false;
}Example 99
| Project: ranger-master File: UnixAuthenticationService.java View source code |
public void startService() throws Throwable {
SSLContext context = SSLContext.getInstance(SSL_ALGORITHM);
KeyManager[] km = null;
if (keyStorePath != null && !keyStorePath.isEmpty()) {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = null;
in = getFileInputStream(keyStorePath);
try {
if (keyStorePathPassword == null) {
keyStorePathPassword = "";
}
ks.load(in, keyStorePathPassword.toCharArray());
} finally {
if (in != null) {
in.close();
}
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyStorePathPassword.toCharArray());
km = kmf.getKeyManagers();
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore trustStoreKeyStore = null;
if (trustStorePath != null && !trustStorePath.isEmpty()) {
trustStoreKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = null;
in = getFileInputStream(trustStorePath);
try {
if (trustStorePathPassword == null) {
trustStorePathPassword = "";
}
trustStoreKeyStore.load(in, trustStorePathPassword.toCharArray());
} finally {
if (in != null) {
in.close();
}
}
}
trustManagerFactory.init(trustStoreKeyStore);
TrustManager[] tm = trustManagerFactory.getTrustManagers();
SecureRandom random = new SecureRandom();
context.init(km, tm, random);
SSLServerSocketFactory sf = context.getServerSocketFactory();
ServerSocket socket = (SSLEnabled ? sf.createServerSocket(portNum) : new ServerSocket(portNum));
if (SSLEnabled) {
SSLServerSocket secureSocket = (SSLServerSocket) socket;
String[] protocols = secureSocket.getEnabledProtocols();
Set<String> allowedProtocols = new HashSet<String>();
for (String ep : protocols) {
if (!ep.toUpperCase().startsWith("SSLV3")) {
LOG.info("Enabling Protocol: [" + ep + "]");
allowedProtocols.add(ep);
} else {
LOG.info("Disabling Protocol: [" + ep + "]");
}
}
if (!allowedProtocols.isEmpty()) {
secureSocket.setEnabledProtocols(allowedProtocols.toArray(new String[0]));
}
}
Socket client = null;
try {
while ((client = socket.accept()) != null) {
Thread clientValidatorThread = new Thread(new PasswordValidator(client));
clientValidatorThread.start();
}
} catch (IOException e) {
socket.close();
throw (e);
}
}Example 100
| Project: stratio-cassandra-master File: SSLFactory.java View source code |
public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port) throws IOException { SSLContext ctx = createSSLContext(options, true); SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(); serverSocket.setReuseAddress(true); String[] suits = filterCipherSuites(serverSocket.getSupportedCipherSuites(), options.cipher_suites); serverSocket.setEnabledCipherSuites(suits); serverSocket.setNeedClientAuth(options.require_client_auth); serverSocket.setEnabledProtocols(ACCEPTED_PROTOCOLS); serverSocket.bind(new InetSocketAddress(address, port), 500); return serverSocket; }
Example 101
| Project: tnoodle-master File: HttpsListener.java View source code |
/**
* Gets a server socket - this gets as SSL socket instead of the standard
* socket returned in the base class.
*/
protected ServerSocket getServerSocket() throws IOException {
// Just to make sure it's set before we start
SSLContext context = getSSLContext(this.keystore, this.password);
SSLServerSocketFactory factory = context.getServerSocketFactory();
SSLServerSocket ss = (SSLServerSocket) (this.listenAddress == null ? factory.createServerSocket(this.listenPort, BACKLOG_COUNT) : factory.createServerSocket(this.listenPort, BACKLOG_COUNT, InetAddress.getByName(this.listenAddress)));
ss.setEnableSessionCreation(true);
ss.setWantClientAuth(true);
return ss;
}