Java Code Examples for javax.net.ssl.SSLParameters#setServerNames()

The following examples show how to use javax.net.ssl.SSLParameters#setServerNames() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSLEngineTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns client ssl engine.
 *
 * @param context - SSLContext to get SSLEngine from.
 * @param useSNI  - flag used to enable or disable using SNI extension.
 *                Needed for Kerberos.
 */
public static SSLEngine getClientSSLEngine(
        SSLContext context, boolean useSNI) {

    SSLEngine clientEngine = context.createSSLEngine(HOST, 80);
    clientEngine.setUseClientMode(true);
    if (useSNI) {
        SNIHostName serverName = new SNIHostName(SERVER_NAME);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        SSLParameters params = clientEngine.getSSLParameters();
        params.setServerNames(serverNames);
        clientEngine.setSSLParameters(params);
    }
    return clientEngine;
}
 
Example 2
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static SSLParameters copySSLParameters(SSLParameters p) {
    SSLParameters p1 = new SSLParameters();
    p1.setAlgorithmConstraints(p.getAlgorithmConstraints());
    p1.setCipherSuites(p.getCipherSuites());
    // JDK 8 EXCL START
    p1.setEnableRetransmissions(p.getEnableRetransmissions());
    p1.setMaximumPacketSize(p.getMaximumPacketSize());
    // JDK 8 EXCL END
    p1.setEndpointIdentificationAlgorithm(p.getEndpointIdentificationAlgorithm());
    p1.setNeedClientAuth(p.getNeedClientAuth());
    String[] protocols = p.getProtocols();
    if (protocols != null) {
        p1.setProtocols(protocols.clone());
    }
    p1.setSNIMatchers(p.getSNIMatchers());
    p1.setServerNames(p.getServerNames());
    p1.setUseCipherSuitesOrder(p.getUseCipherSuitesOrder());
    p1.setWantClientAuth(p.getWantClientAuth());
    return p1;
}
 
Example 3
Source File: UndertowXnioSsl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void handleEvent(final StreamConnection connection) {
    try {

        SSLEngine sslEngine = JsseSslUtils.createSSLEngine(sslContext, optionMap, destination);
        SSLParameters params = sslEngine.getSSLParameters();
        params.setServerNames(Collections.singletonList(new SNIHostName(destination.getHostString())));
        sslEngine.setSSLParameters(params);

        final SslConnection wrappedConnection = new UndertowSslConnection(connection, sslEngine, bufferPool);
        if (!futureResult.setResult(wrappedConnection)) {
            IoUtils.safeClose(connection);
        } else {
            ChannelListeners.invokeChannelListener(wrappedConnection, openListener);
        }
    } catch (Throwable e) {
        futureResult.setException(new IOException(e));
    }
}
 
Example 4
Source File: Https.java    From PacketProxy with Apache License 2.0 5 votes vote down vote up
public static SSLSocket createClientSSLSocket(InetSocketAddress addr, String SNIServerName, String alpn) throws Exception {
	/* SNI */
	SNIHostName serverName = new SNIHostName(SNIServerName);
	/* Fetch Client Certificate from ClientKeyManager */
	Server server = Servers.getInstance().queryByAddress(addr);
	clientKeyManagers = ClientKeyManager.getKeyManagers(server);

	SSLSocketFactory ssf = createSSLSocketFactory();
	SSLSocket sock = (SSLSocket) ssf.createSocket(addr.getAddress(), addr.getPort());
	SSLParameters sslp = sock.getSSLParameters();
	String[] clientAPs;
	if (alpn != null && alpn.length() > 0) {
		clientAPs = new String[]{ alpn };
	} else {
		clientAPs = new String[]{ "h2", "http/1.1", "http/1.0" };
	}
	sslp.setApplicationProtocols(clientAPs);

	sock.setSSLParameters(sslp);
	List<SNIServerName> serverNames = new ArrayList<>();
	serverNames.add(serverName);
	SSLParameters params = sock.getSSLParameters();
	params.setServerNames(serverNames);
	sock.setSSLParameters(params);
	sock.startHandshake();
	return sock;
}
 
Example 5
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_SSLSocket_SNIHostName() throws Exception {
    TestSSLContext c = TestSSLContext.create();

    final SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();
    SSLParameters clientParams = client.getSSLParameters();
    clientParams.setServerNames(Collections.singletonList(
            (SNIServerName) new SNIHostName("www.example.com")));
    client.setSSLParameters(clientParams);

    SSLParameters serverParams = c.serverSocket.getSSLParameters();
    serverParams.setSNIMatchers(Collections.singletonList(
            SNIHostName.createSNIMatcher("www\\.example\\.com")));
    c.serverSocket.setSSLParameters(serverParams);

    client.connect(new InetSocketAddress(c.host, c.port));
    final SSLSocket server = (SSLSocket) c.serverSocket.accept();

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override public Void call() throws Exception {
            client.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    server.startHandshake();

    SSLSession serverSession = server.getSession();
    assertTrue(serverSession instanceof ExtendedSSLSession);
    ExtendedSSLSession extendedServerSession = (ExtendedSSLSession) serverSession;
    List<SNIServerName> requestedNames = extendedServerSession.getRequestedServerNames();
    assertNotNull(requestedNames);
    assertEquals(1, requestedNames.size());
    SNIServerName serverName = requestedNames.get(0);
    assertEquals(StandardConstants.SNI_HOST_NAME, serverName.getType());
    assertTrue(serverName instanceof SNIHostName);
    SNIHostName serverHostName = (SNIHostName) serverName;
    assertEquals("www.example.com", serverHostName.getAsciiName());
}
 
Example 6
Source File: UnboundSSLUtils.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example 7
Source File: UnboundSSLUtils.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example 8
Source File: UnboundSSLUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example 9
Source File: SSLConfiguration.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
SSLParameters getSSLParameters() {
    SSLParameters params = new SSLParameters();

    params.setAlgorithmConstraints(this.algorithmConstraints);
    params.setProtocols(ProtocolVersion.toStringArray(enabledProtocols));
    params.setCipherSuites(CipherSuite.namesOf(enabledCipherSuites));
    switch (this.clientAuthType) {
        case CLIENT_AUTH_REQUIRED:
            params.setNeedClientAuth(true);
            break;
        case CLIENT_AUTH_REQUESTED:
            params.setWantClientAuth(true);
            break;
        default:
            params.setWantClientAuth(false);
    }
    params.setEndpointIdentificationAlgorithm(this.identificationProtocol);

    if (serverNames.isEmpty() && !noSniExtension) {
        // 'null' indicates none has been set
        params.setServerNames(null);
    } else {
        params.setServerNames(this.serverNames);
    }

    if (sniMatchers.isEmpty() && !noSniMatcher) {
        // 'null' indicates none has been set
        params.setSNIMatchers(null);
    } else {
        params.setSNIMatchers(this.sniMatchers);
    }

    params.setApplicationProtocols(this.applicationProtocols);
    params.setUseCipherSuitesOrder(this.preferLocalCipherSuites);
    params.setEnableRetransmissions(this.enableRetransmissions);
    params.setMaximumPacketSize(this.maximumPacketSize);

    return params;
}
 
Example 10
Source File: UnboundSSLUtils.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example 11
Source File: UnboundSSLUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example 12
Source File: SslUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link SslHandler} which will supports SNI if the {@link InetSocketAddress} was created from
 * a hostname.
 *
 * @param context the {@link SslContext} which will be used to create the {@link SslHandler}
 * @param allocator the {@link ByteBufAllocator} which will be used to allocate direct memory if required for
 * {@link SSLEngine}
 * @param hostnameVerificationAlgorithm see {@link SSLParameters#setEndpointIdentificationAlgorithm(String)}.
 * If this is {@code null} or empty then you will be vulnerable to a MITM attack.
 * @param hostnameVerificationHost the non-authoritative name of the host.
 * @param hostnameVerificationPort the non-authoritative port.
 * @return a {@link SslHandler}
 */
static SslHandler newHandler(SslContext context, ByteBufAllocator allocator,
                             @Nullable String hostnameVerificationAlgorithm,
                             @Nullable String hostnameVerificationHost,
                             int hostnameVerificationPort) {
    if (hostnameVerificationHost == null) {
        return newHandler(context, allocator);
    }

    SslHandler handler = context.newHandler(allocator, hostnameVerificationHost, hostnameVerificationPort);
    SSLEngine engine = handler.engine();
    try {
        SSLParameters parameters = engine.getSSLParameters();
        parameters.setEndpointIdentificationAlgorithm(hostnameVerificationAlgorithm);
        if (!NetUtil.isValidIpV4Address(hostnameVerificationHost) &&
                !NetUtil.isValidIpV6Address(hostnameVerificationHost)) {
            // SNI doesn't permit IP addresses!
            // https://tools.ietf.org/html/rfc6066#section-3
            // Literal IPv4 and IPv6 addresses are not permitted in "HostName".
            parameters.setServerNames(Collections.singletonList(new SNIHostName(hostnameVerificationHost)));
        }
        engine.setSSLParameters(parameters);
    } catch (Throwable cause) {
        ReferenceCountUtil.release(engine);
        throw cause;
    }
    return handler;
}
 
Example 13
Source File: UnboundSSLUtils.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example 14
Source File: Java8SslUtils.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
static void setSniHostNames(SSLParameters sslParameters, List<String> names) {
    List<SNIServerName> sniServerNames = new ArrayList<SNIServerName>(names.size());
    for (String name: names) {
        sniServerNames.add(new SNIHostName(name));
    }
    sslParameters.setServerNames(sniServerNames);
}
 
Example 15
Source File: UnboundSSLUtils.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example 16
Source File: NonBlockingConnectionTLSDelegate.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
public boolean processData() throws IOException
{
    if(!_hostChecked)
    {
        try (QpidByteBuffer buffer = _netInputBuffer.duplicate())
        {
            buffer.flip();
            if (SSLUtil.isSufficientToDetermineClientSNIHost(buffer))
            {
                String hostName = SSLUtil.getServerNameFromTLSClientHello(buffer);
                if (hostName != null)
                {
                    _parent.setSelectedHost(hostName);
                    SSLParameters sslParameters = _sslEngine.getSSLParameters();
                    sslParameters.setServerNames(Collections.singletonList(new SNIHostName(hostName)));
                    _sslEngine.setSSLParameters(sslParameters);
                }
                _hostChecked = true;
            }
            else
            {
                return false;
            }
        }
    }
    _netInputBuffer.flip();
    boolean readData = false;
    boolean tasksRun;
    int oldNetBufferPos;
    do
    {
        int oldAppBufPos = _applicationBuffer.position();
        oldNetBufferPos = _netInputBuffer.position();

        _status = QpidByteBuffer.decryptSSL(_sslEngine, _netInputBuffer, _applicationBuffer);
        if (_status.getStatus() == SSLEngineResult.Status.CLOSED)
        {
            int remaining = _netInputBuffer.remaining();
            _netInputBuffer.position(_netInputBuffer.limit());
            // We'd usually expect no more bytes to be sent following a close_notify
            LOGGER.debug("SSLEngine closed, discarded {} byte(s)", remaining);
        }

        tasksRun = runSSLEngineTasks(_status);
        _applicationBuffer.flip();
        if(_applicationBuffer.position() > oldAppBufPos)
        {
            readData = true;
        }

        _parent.processAmqpData(_applicationBuffer);

        restoreApplicationBufferForWrite();

    }
    while((_netInputBuffer.hasRemaining() && (_netInputBuffer.position()>oldNetBufferPos)) || tasksRun);

    if(_netInputBuffer.hasRemaining())
    {
        _netInputBuffer.compact();
    }
    else
    {
        _netInputBuffer.clear();
    }
    return readData;
}
 
Example 17
Source File: MqttClientFactory.java    From enmasse with Apache License 2.0 4 votes vote down vote up
private Socket setHostnameParameter(final Socket newSocket) {
    SSLParameters sslParameters = new SSLParameters();
    sslParameters.setServerNames(this.sniHostNames);
    ((SSLSocket) newSocket).setSSLParameters(sslParameters);
    return newSocket;
}
 
Example 18
Source File: SSLSocketHelper.java    From Pix-Art-Messenger with GNU General Public License v3.0 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.N)
private static void setHostnameNougat(final SSLSocket socket, final String hostname) {
    final SSLParameters parameters = new SSLParameters();
    parameters.setServerNames(Collections.singletonList(new SNIHostName(hostname)));
    socket.setSSLParameters(parameters);
}
 
Example 19
Source File: IpStation.java    From swim with Apache License 2.0 4 votes vote down vote up
@Override
default IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
  try {
    final Station station = station();
    final SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);
    ipSettings.configure(channel.socket());

    final TlsSettings tlsSettings = ipSettings.tlsSettings();
    final SSLEngine sslEngine = tlsSettings.sslContext().createSSLEngine();
    sslEngine.setUseClientMode(true);
    final SNIHostName serverName = new SNIHostName(remoteAddress.getHostName());
    final List<SNIServerName> serverNames = new ArrayList<>(1);
    serverNames.add(serverName);
    final SSLParameters sslParameters = sslEngine.getSSLParameters();
    sslParameters.setServerNames(serverNames);
    sslEngine.setSSLParameters(sslParameters);
    switch (tlsSettings.clientAuth()) {
      case NEED:
        sslEngine.setNeedClientAuth(true);
        break;
      case WANT:
        sslEngine.setWantClientAuth(true);
        break;
      case NONE:
        sslEngine.setWantClientAuth(false);
        break;
      default:
    }
    final Collection<String> cipherSuites = tlsSettings.cipherSuites();
    if (cipherSuites != null) {
      sslEngine.setEnabledCipherSuites(cipherSuites.toArray(new String[cipherSuites.size()]));
    }
    final Collection<String> protocols = tlsSettings.protocols();
    if (protocols != null) {
      sslEngine.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
    }

    final boolean connected = channel.connect(remoteAddress);
    final InetSocketAddress localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress();
    final TlsSocket context = new TlsSocket(localAddress, remoteAddress, channel, sslEngine, ipSettings, true);
    context.become(socket);
    if (connected) {
      station.transport(context, FlowControl.WAIT);
      context.didConnect();
    } else {
      context.willConnect();
      station.transport(context, FlowControl.CONNECT);
    }
    return context;
  } catch (IOException | UnresolvedAddressException error) {
    throw new StationException(remoteAddress.toString(), error);
  }
}
 
Example 20
Source File: SSLSocketHelper.java    From Conversations with GNU General Public License v3.0 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.N)
private static void setHostnameNougat(final SSLSocket socket, final String hostname) {
    final SSLParameters parameters = new SSLParameters();
    parameters.setServerNames(Collections.singletonList(new SNIHostName(hostname)));
    socket.setSSLParameters(parameters);
}