下面列出了怎么用javax.net.ssl.SNIHostName的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns true if name matches against template.<p>
*
* The matching is performed as per RFC 2818 rules for TLS and
* RFC 2830 rules for LDAP.<p>
*
* The <code>name</code> parameter should represent a DNS name. The
* <code>template</code> parameter may contain the wildcard character '*'.
*/
private boolean isMatched(String name, String template) {
// check the validity of the domain name template.
try {
// Replacing wildcard character '*' with 'z' so as to check
// the domain name template validity.
//
// Using the checking implemented in SNIHostName
SNIHostName sni = new SNIHostName(template.replace('*', 'z'));
} catch (IllegalArgumentException iae) {
// It would be nice to add debug log if not matching.
return false;
}
if (checkType == TYPE_TLS) {
return matchAllWildcards(name, template);
} else if (checkType == TYPE_LDAP) {
return matchLeftmostWildcard(name, template);
} else {
return false;
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
static List<String> getSniHostNames(SSLParameters sslParameters) {
List<SNIServerName> names = sslParameters.getServerNames();
if (names == null || names.isEmpty()) {
return Collections.emptyList();
}
List<String> strings = new ArrayList<String>(names.size());
for (SNIServerName serverName : names) {
if (serverName instanceof SNIHostName) {
strings.add(((SNIHostName) serverName).getAsciiName());
} else {
throw new IllegalArgumentException("Only " + SNIHostName.class.getName()
+ " instances are supported, but found: " + serverName);
}
}
return strings;
}
@SuppressWarnings("unchecked")
static boolean checkSniHostnameMatch(Collection<?> matchers, String hostname) {
if (matchers != null && !matchers.isEmpty()) {
SNIHostName name = new SNIHostName(hostname);
Iterator<SNIMatcher> matcherIt = (Iterator<SNIMatcher>) matchers.iterator();
while (matcherIt.hasNext()) {
SNIMatcher matcher = matcherIt.next();
// type 0 is for hostname
if (matcher.getType() == 0 && matcher.matches(name)) {
return true;
}
}
return false;
}
return true;
}
/**
* Returns true if name matches against template.<p>
*
* The matching is performed as per RFC 2818 rules for TLS and
* RFC 2830 rules for LDAP.<p>
*
* The <code>name</code> parameter should represent a DNS name. The
* <code>template</code> parameter may contain the wildcard character '*'.
*/
private boolean isMatched(String name, String template) {
// check the validity of the domain name template.
try {
// Replacing wildcard character '*' with 'z' so as to check
// the domain name template validity.
//
// Using the checking implemented in SNIHostName
SNIHostName sni = new SNIHostName(template.replace('*', 'z'));
} catch (IllegalArgumentException iae) {
// It would be nice to add debug log if not matching.
return false;
}
if (checkType == TYPE_TLS) {
return matchAllWildcards(name, template);
} else if (checkType == TYPE_LDAP) {
return matchLeftmostWildcard(name, template);
} else {
return false;
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
/**
* Returns true if name matches against template.<p>
*
* The matching is performed as per RFC 2818 rules for TLS and
* RFC 2830 rules for LDAP.<p>
*
* The <code>name</code> parameter should represent a DNS name. The
* <code>template</code> parameter may contain the wildcard character '*'.
*/
private boolean isMatched(String name, String template) {
// check the validity of the domain name template.
try {
// Replacing wildcard character '*' with 'z' so as to check
// the domain name template validity.
//
// Using the checking implemented in SNIHostName
SNIHostName sni = new SNIHostName(template.replace('*', 'z'));
} catch (IllegalArgumentException iae) {
// It would be nice to add debug log if not matching.
return false;
}
if (checkType == TYPE_TLS) {
return matchAllWildcards(name, template);
} else if (checkType == TYPE_LDAP) {
return matchLeftmostWildcard(name, template);
} else {
return false;
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
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));
}
}
/**
* Returns true if name matches against template.<p>
*
* The matching is performed as per RFC 2818 rules for TLS and
* RFC 2830 rules for LDAP.<p>
*
* The <code>name</code> parameter should represent a DNS name.
* The <code>template</code> parameter
* may contain the wildcard character *
*/
private boolean isMatched(String name, String template) {
// check the validity of the domain name template.
try {
// Replacing wildcard character '*' with 'x' so as to check
// the domain name template validity.
//
// Using the checking implemented in SNIHostName
SNIHostName sni = new SNIHostName(template.replace('*', 'x'));
} catch (IllegalArgumentException iae) {
// It would be nice to add debug log if not matching.
return false;
}
if (checkType == TYPE_TLS) {
return matchAllWildcards(name, template);
} else if (checkType == TYPE_LDAP) {
return matchLeftmostWildcard(name, template);
} else {
return false;
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
/**
* 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;
}
/**
* Returns server 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 getServerSSLEngine(
SSLContext context, boolean useSNI) {
SSLEngine serverEngine = context.createSSLEngine();
serverEngine.setUseClientMode(false);
if (useSNI) {
SNIMatcher matcher = SNIHostName.createSNIMatcher(SNI_PATTERN);
List<SNIMatcher> matchers = new ArrayList<>();
matchers.add(matcher);
SSLParameters params = serverEngine.getSSLParameters();
params.setSNIMatchers(matchers);
serverEngine.setSSLParameters(params);
}
return serverEngine;
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
/**
* Returns true if name matches against template.<p>
*
* The matching is performed as per RFC 2818 rules for TLS and
* RFC 2830 rules for LDAP.<p>
*
* The <code>name</code> parameter should represent a DNS name. The
* <code>template</code> parameter may contain the wildcard character '*'.
*/
private boolean isMatched(String name, String template) {
// check the validity of the domain name template.
try {
// Replacing wildcard character '*' with 'z' so as to check
// the domain name template validity.
//
// Using the checking implemented in SNIHostName
SNIHostName sni = new SNIHostName(template.replace('*', 'z'));
} catch (IllegalArgumentException iae) {
// It would be nice to add debug log if not matching.
return false;
}
if (checkType == TYPE_TLS) {
return matchAllWildcards(name, template);
} else if (checkType == TYPE_LDAP) {
return matchLeftmostWildcard(name, template);
} else {
return false;
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
private Optional<SNIServerName> getServerNameIndication() throws IOException, EofException {
inEncrypted.prepare();
try {
int recordHeaderSize = readRecordHeaderSize();
while (inEncrypted.buffer.position() < recordHeaderSize) {
if (!inEncrypted.buffer.hasRemaining()) {
inEncrypted.enlarge();
}
TlsChannelImpl.readFromChannel(underlying, inEncrypted.buffer); // IO block
}
inEncrypted.buffer.flip();
Map<Integer, SNIServerName> serverNames = TlsExplorer.explore(inEncrypted.buffer);
inEncrypted.buffer.compact();
SNIServerName hostName = serverNames.get(StandardConstants.SNI_HOST_NAME);
if (hostName instanceof SNIHostName) {
SNIHostName sniHostName = (SNIHostName) hostName;
return Optional.of(sniHostName);
} else {
return Optional.empty();
}
} finally {
inEncrypted.release();
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
public static void main(String[] args) throws Exception {
String[] illegalNames = {
"example\u3002\u3002com",
"example..com",
"com\u3002",
"com.",
"."
};
for (String name : illegalNames) {
try {
SNIHostName hostname = new SNIHostName(name);
throw new Exception(
"Expected to get IllegalArgumentException for " + name);
} catch (IllegalArgumentException iae) {
// That's the right behavior.
}
}
}
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;
}
/**
* Puts {@code hostname} into the {@code serverNames} list.
* <P>
* If the {@code serverNames} does not look like a legal FQDN, it will
* not be put into the returned list.
* <P>
* Note that the returned list does not allow duplicated name type.
*
* @return a list of {@link SNIServerName}
*/
static List<SNIServerName> addToSNIServerNameList(
List<SNIServerName> serverNames, String hostname) {
SNIHostName sniHostName = rawToSNIHostName(hostname);
if (sniHostName == null) {
return serverNames;
}
int size = serverNames.size();
List<SNIServerName> sniList = (size != 0) ?
new ArrayList<SNIServerName>(serverNames) :
new ArrayList<SNIServerName>(1);
boolean reset = false;
for (int i = 0; i < size; i++) {
SNIServerName serverName = sniList.get(i);
if (serverName.getType() == StandardConstants.SNI_HOST_NAME) {
sniList.set(i, sniHostName);
if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
SSLLogger.fine(
"the previous server name in SNI (" + serverName +
") was replaced with (" + sniHostName + ")");
}
reset = true;
break;
}
}
if (!reset) {
sniList.add(sniHostName);
}
return Collections.<SNIServerName>unmodifiableList(sniList);
}
/**
* Returns true if name matches against template.<p>
*
* The matching is performed as per RFC 2818 rules for TLS and
* RFC 2830 rules for LDAP.<p>
*
* The <code>name</code> parameter should represent a DNS name. The
* <code>template</code> parameter may contain the wildcard character '*'.
*/
private boolean isMatched(String name, String template,
boolean chainsToPublicCA) {
// Normalize to Unicode, because PSL is in Unicode.
try {
name = IDN.toUnicode(IDN.toASCII(name));
template = IDN.toUnicode(IDN.toASCII(template));
} catch (RuntimeException re) {
if (SSLLogger.isOn) {
SSLLogger.fine("Failed to normalize to Unicode: " + re);
}
return false;
}
if (hasIllegalWildcard(template, chainsToPublicCA)) {
return false;
}
// check the validity of the domain name template.
try {
// Replacing wildcard character '*' with 'z' so as to check
// the domain name template validity.
//
// Using the checking implemented in SNIHostName
new SNIHostName(template.replace('*', 'z'));
} catch (IllegalArgumentException iae) {
// It would be nice to add debug log if not matching.
return false;
}
if (checkType == TYPE_TLS) {
return matchAllWildcards(name, template);
} else if (checkType == TYPE_LDAP) {
return matchLeftmostWildcard(name, template);
} else {
return false;
}
}
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);
}
static SSLEchoServer init(String cipherSuiteFilter,
String sniPattern) throws NoSuchAlgorithmException, IOException {
SSLContext context = SSLContext.getDefault();
SSLServerSocketFactory ssf =
(SSLServerSocketFactory) context.getServerSocketFactory();
SSLServerSocket ssocket =
(SSLServerSocket) ssf.createServerSocket(0);
// specify enabled cipher suites
if (cipherSuiteFilter != null) {
String[] ciphersuites = UnboundSSLUtils.filterStringArray(
ssf.getSupportedCipherSuites(), cipherSuiteFilter);
System.out.println("Server: enabled cipher suites: "
+ Arrays.toString(ciphersuites));
ssocket.setEnabledCipherSuites(ciphersuites);
}
// specify SNI matcher pattern
if (sniPattern != null) {
System.out.println("Server: set SNI matcher: " + sniPattern);
SNIMatcher matcher = SNIHostName.createSNIMatcher(sniPattern);
List<SNIMatcher> matchers = new ArrayList<>();
matchers.add(matcher);
SSLParameters params = ssocket.getSSLParameters();
params.setSNIMatchers(matchers);
ssocket.setSSLParameters(params);
}
return new SSLEchoServer(ssocket);
}
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);
}