use of javax.net.ssl.SSLSession in project jetty.project by eclipse.
the class SecureRequestCustomizer method customize.
/**
* <p>
* Customizes the request attributes to be set for SSL requests.
* </p>
* <p>
* The requirements of the Servlet specs are:
* </p>
* <ul>
* <li>an attribute named "javax.servlet.request.ssl_session_id" of type String (since Servlet Spec 3.0).</li>
* <li>an attribute named "javax.servlet.request.cipher_suite" of type String.</li>
* <li>an attribute named "javax.servlet.request.key_size" of type Integer.</li>
* <li>an attribute named "javax.servlet.request.X509Certificate" of type java.security.cert.X509Certificate[]. This
* is an array of objects of type X509Certificate, the order of this array is defined as being in ascending order of
* trust. The first certificate in the chain is the one set by the client, the next is the one used to authenticate
* the first, and so on.</li>
* </ul>
*
* @param sslEngine
* the sslEngine to be customized.
* @param request
* HttpRequest to be customized.
*/
protected void customize(SSLEngine sslEngine, Request request) {
SSLSession sslSession = sslEngine.getSession();
if (_sniHostCheck) {
String name = request.getServerName();
X509 x509 = (X509) sslSession.getValue(SniX509ExtendedKeyManager.SNI_X509);
if (x509 != null && !x509.matches(name)) {
LOG.warn("Host {} does not match SNI {}", name, x509);
throw new BadMessageException(400, "Host does not match SNI");
}
if (LOG.isDebugEnabled())
LOG.debug("Host {} matched SNI {}", name, x509);
}
try {
String cipherSuite = sslSession.getCipherSuite();
Integer keySize;
X509Certificate[] certs;
String idStr;
CachedInfo cachedInfo = (CachedInfo) sslSession.getValue(CACHED_INFO_ATTR);
if (cachedInfo != null) {
keySize = cachedInfo.getKeySize();
certs = cachedInfo.getCerts();
idStr = cachedInfo.getIdStr();
} else {
keySize = SslContextFactory.deduceKeyLength(cipherSuite);
certs = SslContextFactory.getCertChain(sslSession);
byte[] bytes = sslSession.getId();
idStr = TypeUtil.toHexString(bytes);
cachedInfo = new CachedInfo(keySize, certs, idStr);
sslSession.putValue(CACHED_INFO_ATTR, cachedInfo);
}
if (certs != null)
request.setAttribute("javax.servlet.request.X509Certificate", certs);
request.setAttribute("javax.servlet.request.cipher_suite", cipherSuite);
request.setAttribute("javax.servlet.request.key_size", keySize);
request.setAttribute("javax.servlet.request.ssl_session_id", idStr);
String sessionAttribute = getSslSessionAttribute();
if (sessionAttribute != null && !sessionAttribute.isEmpty())
request.setAttribute(sessionAttribute, sslSession);
} catch (Exception e) {
LOG.warn(Log.EXCEPTION, e);
}
}
use of javax.net.ssl.SSLSession in project jersey by jersey.
the class SslFilterTest method testCustomHostameVerificationFail.
@Test
public void testCustomHostameVerificationFail() throws Throwable {
CountDownLatch latch = new CountDownLatch(1);
SslEchoServer server = new SslEchoServer();
try {
server.start();
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return false;
}
};
openClientSocket("localhost", ByteBuffer.allocate(0), latch, verifier);
fail();
} catch (SSLException e) {
// expected
} finally {
server.stop();
}
}
use of javax.net.ssl.SSLSession in project hadoop by apache.
the class TestSSLFactory method testServerWeakCiphers.
@Test
public void testServerWeakCiphers() throws Exception {
// a simple test case to verify that SSL server rejects weak cipher suites,
// inspired by https://docs.oracle.com/javase/8/docs/technotes/guides/
// security/jsse/samples/sslengine/SSLEngineSimpleDemo.java
// set up a client and a server SSLEngine object, and let them exchange
// data over ByteBuffer instead of network socket.
GenericTestUtils.setLogLevel(SSLFactory.LOG, Level.DEBUG);
final Configuration conf = createConfiguration(true, true);
SSLFactory serverSSLFactory = new SSLFactory(SSLFactory.Mode.SERVER, conf);
SSLFactory clientSSLFactory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
serverSSLFactory.init();
clientSSLFactory.init();
SSLEngine serverSSLEngine = serverSSLFactory.createSSLEngine();
SSLEngine clientSSLEngine = clientSSLFactory.createSSLEngine();
// client selects cipher suites excluded by server
clientSSLEngine.setEnabledCipherSuites(excludeCiphers.split(","));
// use the same buffer size for server and client.
SSLSession session = clientSSLEngine.getSession();
int appBufferMax = session.getApplicationBufferSize();
int netBufferMax = session.getPacketBufferSize();
ByteBuffer clientOut = ByteBuffer.wrap("client".getBytes());
ByteBuffer clientIn = ByteBuffer.allocate(appBufferMax);
ByteBuffer serverOut = ByteBuffer.wrap("server".getBytes());
ByteBuffer serverIn = ByteBuffer.allocate(appBufferMax);
// send data from client to server
ByteBuffer cTOs = ByteBuffer.allocateDirect(netBufferMax);
// send data from server to client
ByteBuffer sTOc = ByteBuffer.allocateDirect(netBufferMax);
boolean dataDone = false;
try {
/**
* Server and client engines call wrap()/unwrap() to perform handshaking,
* until both engines are closed.
*/
while (!isEngineClosed(clientSSLEngine) || !isEngineClosed(serverSSLEngine)) {
LOG.info("client wrap " + wrap(clientSSLEngine, clientOut, cTOs));
LOG.info("server wrap " + wrap(serverSSLEngine, serverOut, sTOc));
cTOs.flip();
sTOc.flip();
LOG.info("client unwrap " + unwrap(clientSSLEngine, sTOc, clientIn));
LOG.info("server unwrap " + unwrap(serverSSLEngine, cTOs, serverIn));
cTOs.compact();
sTOc.compact();
if (!dataDone && (clientOut.limit() == serverIn.position()) && (serverOut.limit() == clientIn.position())) {
checkTransfer(serverOut, clientIn);
checkTransfer(clientOut, serverIn);
LOG.info("closing client");
clientSSLEngine.closeOutbound();
dataDone = true;
}
}
Assert.fail("The exception was not thrown");
} catch (SSLHandshakeException e) {
GenericTestUtils.assertExceptionContains("no cipher suites in common", e);
}
}
use of javax.net.ssl.SSLSession in project android_frameworks_base by ParanoidAndroid.
the class CertificateChainValidator method doHandshakeAndValidateServerCertificates.
/**
* Performs the handshake and server certificates validation
* Notice a new chain will be rebuilt by tracing the issuer and subject
* before calling checkServerTrusted().
* And if the last traced certificate is self issued and it is expired, it
* will be dropped.
* @param sslSocket The secure connection socket
* @param domain The website domain
* @return An SSL error object if there is an error and null otherwise
*/
public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket, String domain) throws IOException {
// get a valid SSLSession, close the socket if we fail
SSLSession sslSession = sslSocket.getSession();
if (!sslSession.isValid()) {
closeSocketThrowException(sslSocket, "failed to perform SSL handshake");
}
// retrieve the chain of the server peer certificates
Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates();
if (peerCertificates == null || peerCertificates.length == 0) {
closeSocketThrowException(sslSocket, "failed to retrieve peer certificates");
} else {
// update the SSL certificate associated with the connection
if (connection != null) {
if (peerCertificates[0] != null) {
connection.setCertificate(new SslCertificate((X509Certificate) peerCertificates[0]));
}
}
}
return verifyServerDomainAndCertificates((X509Certificate[]) peerCertificates, domain, "RSA");
}
use of javax.net.ssl.SSLSession in project android_frameworks_base by ParanoidAndroid.
the class SSLCertificateSocketFactory method verifyHostname.
/**
* Verify the hostname of the certificate used by the other end of a
* connected socket. You MUST call this if you did not supply a hostname
* to {@link #createSocket()}. It is harmless to call this method
* redundantly if the hostname has already been verified.
*
* <p>Wildcard certificates are allowed to verify any matching hostname,
* so "foo.bar.example.com" is verified if the peer has a certificate
* for "*.example.com".
*
* @param socket An SSL socket which has been connected to a server
* @param hostname The expected hostname of the remote server
* @throws IOException if something goes wrong handshaking with the server
* @throws SSLPeerUnverifiedException if the server cannot prove its identity
*
* @hide
*/
public static void verifyHostname(Socket socket, String hostname) throws IOException {
if (!(socket instanceof SSLSocket)) {
throw new IllegalArgumentException("Attempt to verify non-SSL socket");
}
if (!isSslCheckRelaxed()) {
// The code at the start of OpenSSLSocketImpl.startHandshake()
// ensures that the call is idempotent, so we can safely call it.
SSLSocket ssl = (SSLSocket) socket;
ssl.startHandshake();
SSLSession session = ssl.getSession();
if (session == null) {
throw new SSLException("Cannot verify SSL socket without session");
}
if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname);
}
}
}
Aggregations