下面列出了javax.net.ssl.SSLEngine#getSession ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
* and {@link EchoMethodHandler}.
* @param useSSL {@code true} to add an {@link SslHandler} to the pipeline.
* @return an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
* and {@link EchoMethodHandler}, and an {@link SslHandler} if needed.
*/
private EmbeddedChannel createChannel(boolean useSSL) {
EmbeddedChannel channel = new EmbeddedChannel();
if (useSSL) {
SSLEngine sslEngine = SSL_CONTEXT.newEngine(channel.alloc());
// HttpRequests pass through the SslHandler without a handshake (it only operates on ByteBuffers) so we have
// to mock certain methods of SSLEngine and SSLSession to ensure that we can test certificate logging.
SSLEngine mockSSLEngine =
new MockSSLEngine(sslEngine, new MockSSLSession(sslEngine.getSession(), new Certificate[]{PEER_CERT}));
channel.pipeline().addLast(new SslHandler(mockSSLEngine));
}
channel.pipeline()
.addLast(new PublicAccessLogHandler(publicAccessLogger, new NettyMetrics(new MetricRegistry())))
.addLast(new EchoMethodHandler());
return channel;
}
/**
* Construct a new channel.
*
* @param channel the unsecure socket channel.
* @param engine the SSL engine.
*/
public SSLSocketChannel(SocketChannel channel, SSLEngine engine)
{
super(channel.provider());
socketChannel = channel;
sslEngine = engine;
sslSession = engine.getSession();
minCacheSize = sslSession.getApplicationBufferSize();
inputCache = new ByteBuffer[]{ ByteBuffer.allocate(minCacheSize) };
minBufferSize = sslSession.getPacketBufferSize();
inputBuffer = new ByteBuffer[]{ ByteBuffer.allocate(minBufferSize) };
outputBuffer = new ByteBuffer[]{ ByteBuffer.allocate(minBufferSize) };
emptyBuffer = ByteBuffer.allocate(0);
// Set initial values.
inputCache[0].limit(0);
outputBuffer[0].limit(0);
}
/**
* {@inheritDoc}
* @param clientCertProvider Ignored for this implementation
*/
@Override
public SSLSupport getSslSupport(String clientCertProvider) {
if (getSocket() instanceof SecureNio2Channel) {
SecureNio2Channel ch = (SecureNio2Channel) getSocket();
SSLEngine sslEngine = ch.getSslEngine();
if (sslEngine != null) {
SSLSession session = sslEngine.getSession();
return ((Nio2Endpoint) getEndpoint()).getSslImplementation().getSSLSupport(session);
}
}
return null;
}
/**
* {@inheritDoc}
* @param clientCertProvider Ignored for this implementation
*/
@Override
public SSLSupport getSslSupport(String clientCertProvider) {
if (getSocket() instanceof SecureNioChannel) {
SecureNioChannel ch = (SecureNioChannel) getSocket();
SSLEngine sslEngine = ch.getSslEngine();
if (sslEngine != null) {
SSLSession session = sslEngine.getSession();
return ((NioEndpoint) getEndpoint()).getSslImplementation().getSSLSupport(session);
}
}
return null;
}
public static void main (String[] args) throws Exception {
SSLContext context = SSLContext.getDefault();
// set the property before initialization SSLEngine.
System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");
SSLEngine cliEngine = context.createSSLEngine();
cliEngine.setUseClientMode(true);
SSLEngine srvEngine = context.createSSLEngine();
srvEngine.setUseClientMode(false);
SSLSession cliSession = cliEngine.getSession();
SSLSession srvSession = srvEngine.getSession();
// check packet buffer sizes.
if (cliSession.getPacketBufferSize() < 33049 ||
srvSession.getPacketBufferSize() < 33049) {
throw new Exception("Don't accept large SSL/TLS fragments");
}
// check application data buffer sizes.
if (cliSession.getApplicationBufferSize() < 32768 ||
srvSession.getApplicationBufferSize() < 32768) {
throw new Exception(
"Don't accept large SSL/TLS application data ");
}
}
public static void main (String[] args) throws Exception {
SSLContext context = SSLContext.getDefault();
// set the property before initialization SSLEngine.
System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");
SSLEngine cliEngine = context.createSSLEngine();
cliEngine.setUseClientMode(true);
SSLEngine srvEngine = context.createSSLEngine();
srvEngine.setUseClientMode(false);
SSLSession cliSession = cliEngine.getSession();
SSLSession srvSession = srvEngine.getSession();
// check packet buffer sizes.
if (cliSession.getPacketBufferSize() < 33049 ||
srvSession.getPacketBufferSize() < 33049) {
throw new Exception("Don't accept large SSL/TLS fragments");
}
// check application data buffer sizes.
if (cliSession.getApplicationBufferSize() < 32768 ||
srvSession.getApplicationBufferSize() < 32768) {
throw new Exception(
"Don't accept large SSL/TLS application data ");
}
}
public static void main (String[] args) throws Exception {
SSLContext context = SSLContext.getDefault();
// set the property before initialization SSLEngine.
System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");
SSLEngine cliEngine = context.createSSLEngine();
cliEngine.setUseClientMode(true);
SSLEngine srvEngine = context.createSSLEngine();
srvEngine.setUseClientMode(false);
SSLSession cliSession = cliEngine.getSession();
SSLSession srvSession = srvEngine.getSession();
// check packet buffer sizes.
if (cliSession.getPacketBufferSize() < 33049 ||
srvSession.getPacketBufferSize() < 33049) {
throw new Exception("Don't accept large SSL/TLS fragments");
}
// check application data buffer sizes.
if (cliSession.getApplicationBufferSize() < 32768 ||
srvSession.getApplicationBufferSize() < 32768) {
throw new Exception(
"Don't accept large SSL/TLS application data ");
}
}
public SSLFacade(SSLContext context, boolean client,
boolean clientAuthRequired, ITaskHandler taskHandler) {
//Currently there is no support for SSL session reuse,
// so no need to take a peerHost or port from the host application
final String who = client ? "client" : "server";
SSLEngine engine = makeSSLEngine(context, client, clientAuthRequired);
engine.setEnabledProtocols(new String[]{context.getProtocol()});
//engine.setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"});
Buffers buffers = new Buffers(engine.getSession());
_worker = new Worker(who, engine, buffers);
_handshaker = new Handshaker(client, _worker, taskHandler);
_clientMode = client;
}
public FlowContext(ClientToProxyConnection clientConnection) {
super();
this.clientAddress = clientConnection.getClientAddress();
SSLEngine sslEngine = clientConnection.getSslEngine();
this.clientSslSession = sslEngine != null ? sslEngine.getSession()
: null;
}
public static void main (String[] args) throws Exception {
SSLContext context = SSLContext.getDefault();
// set the property before initialization SSLEngine.
System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");
SSLEngine cliEngine = context.createSSLEngine();
cliEngine.setUseClientMode(true);
SSLEngine srvEngine = context.createSSLEngine();
srvEngine.setUseClientMode(false);
SSLSession cliSession = cliEngine.getSession();
SSLSession srvSession = srvEngine.getSession();
// check packet buffer sizes.
if (cliSession.getPacketBufferSize() < 33049 ||
srvSession.getPacketBufferSize() < 33049) {
throw new Exception("Don't accept large SSL/TLS fragments");
}
// check application data buffer sizes.
if (cliSession.getApplicationBufferSize() < 32768 ||
srvSession.getApplicationBufferSize() < 32768) {
throw new Exception(
"Don't accept large SSL/TLS application data ");
}
}
public static void main (String[] args) throws Exception {
SSLContext context = SSLContext.getDefault();
// set the property before initialization SSLEngine.
System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");
SSLEngine cliEngine = context.createSSLEngine();
cliEngine.setUseClientMode(true);
SSLEngine srvEngine = context.createSSLEngine();
srvEngine.setUseClientMode(false);
SSLSession cliSession = cliEngine.getSession();
SSLSession srvSession = srvEngine.getSession();
// check packet buffer sizes.
if (cliSession.getPacketBufferSize() < 33049 ||
srvSession.getPacketBufferSize() < 33049) {
throw new Exception("Don't accept large SSL/TLS fragments");
}
// check application data buffer sizes.
if (cliSession.getApplicationBufferSize() < 32768 ||
srvSession.getApplicationBufferSize() < 32768) {
throw new Exception(
"Don't accept large SSL/TLS application data ");
}
}
@Override
protected void doStart() throws Exception
{
super.doStart();
final SSLEngine engine = _sslContextFactory.newSSLEngine();
engine.setUseClientMode(false);
final SSLSession session = engine.getSession();
if (session.getPacketBufferSize() > this.getInputBufferSize())
{
this.setInputBufferSize(session.getPacketBufferSize());
}
engine.closeInbound();
engine.closeOutbound();
}
HandshakeModel createSSLEngine(AsynchronousSocketChannel socketChannel, BufferPage bufferPage) {
try {
HandshakeModel handshakeModel = new HandshakeModel();
SSLEngine sslEngine = sslContext.createSSLEngine();
SSLSession session = sslEngine.getSession();
sslEngine.setUseClientMode(isClient);
if (clientAuth != null) {
switch (clientAuth) {
case OPTIONAL:
sslEngine.setWantClientAuth(true);
break;
case REQUIRE:
sslEngine.setNeedClientAuth(true);
break;
case NONE:
break;
default:
throw new Error("Unknown auth " + clientAuth);
}
}
handshakeModel.setSslEngine(sslEngine);
handshakeModel.setAppWriteBuffer(bufferPage.allocate(session.getApplicationBufferSize()));
handshakeModel.setNetWriteBuffer(bufferPage.allocate(session.getPacketBufferSize()));
handshakeModel.getNetWriteBuffer().buffer().flip();
handshakeModel.setAppReadBuffer(bufferPage.allocate(session.getApplicationBufferSize()));
handshakeModel.setNetReadBuffer(bufferPage.allocate(session.getPacketBufferSize()));
sslEngine.beginHandshake();
handshakeModel.setSocketChannel(socketChannel);
return handshakeModel;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main (String[] args) throws Exception {
SSLContext context = SSLContext.getDefault();
// set the property before initialization SSLEngine.
System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");
SSLEngine cliEngine = context.createSSLEngine();
cliEngine.setUseClientMode(true);
SSLEngine srvEngine = context.createSSLEngine();
srvEngine.setUseClientMode(false);
SSLSession cliSession = cliEngine.getSession();
SSLSession srvSession = srvEngine.getSession();
// check packet buffer sizes.
if (cliSession.getPacketBufferSize() < 33049 ||
srvSession.getPacketBufferSize() < 33049) {
throw new Exception("Don't accept large SSL/TLS fragments");
}
// check application data buffer sizes.
if (cliSession.getApplicationBufferSize() < 32768 ||
srvSession.getApplicationBufferSize() < 32768) {
throw new Exception(
"Don't accept large SSL/TLS application data ");
}
}
public TlsCryptoSocket(SocketChannel channel, SSLEngine sslEngine) {
this.channel = channel;
this.sslEngine = sslEngine;
SSLSession nullSession = sslEngine.getSession();
this.wrapBuffer = new Buffer(Math.max(0x10000, nullSession.getPacketBufferSize() * 2));
this.unwrapBuffer = new Buffer(Math.max(0x10000, nullSession.getPacketBufferSize() * 2));
// Note: Dummy buffer as unwrap requires a full size application buffer even though no application data is unwrapped
this.handshakeDummyBuffer = ByteBuffer.allocate(nullSession.getApplicationBufferSize());
this.handshakeState = HandshakeState.NOT_STARTED;
log.fine(() -> "Initialized with " + sslEngine.toString());
}
public static SSLInfo getSSLInfo(final Settings settings, final Path configPath, final RestRequest request, PrincipalExtractor principalExtractor) throws SSLPeerUnverifiedException {
if(request == null || !(request instanceof Netty4HttpRequest)) {
return null;
}
final Netty4HttpRequest nettyHttpRequest = (Netty4HttpRequest) request;
final SslHandler sslhandler = (SslHandler) nettyHttpRequest.getChannel().pipeline().get("ssl_http");
if(sslhandler == null) {
return null;
}
final SSLEngine engine = sslhandler.engine();
final SSLSession session = engine.getSession();
X509Certificate[] x509Certs = null;
final String protocol = session.getProtocol();
final String cipher = session.getCipherSuite();
String principal = null;
boolean validationFailure = false;
if (engine.getNeedClientAuth() || engine.getWantClientAuth()) {
try {
final Certificate[] certs = session.getPeerCertificates();
if (certs != null && certs.length > 0 && certs[0] instanceof X509Certificate) {
x509Certs = Arrays.copyOf(certs, certs.length, X509Certificate[].class);
final X509Certificate[] x509CertsF = x509Certs;
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SpecialPermission());
}
validationFailure = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return !validate(x509CertsF, settings, configPath);
}
});
if(validationFailure) {
throw new SSLPeerUnverifiedException("Unable to validate certificate (CRL)");
}
principal = principalExtractor == null?null: principalExtractor.extractPrincipal(x509Certs[0], Type.HTTP);
} else if (engine.getNeedClientAuth()) {
final ElasticsearchException ex = new ElasticsearchException("No client certificates found but such are needed (Security 9).");
throw ex;
}
} catch (final SSLPeerUnverifiedException e) {
if (engine.getNeedClientAuth() || validationFailure) {
throw e;
}
}
}
Certificate[] localCerts = session.getLocalCertificates();
return new SSLInfo(x509Certs, principal, protocol, cipher, localCerts==null?null:Arrays.copyOf(localCerts, localCerts.length, X509Certificate[].class));
}
public static void run() throws Exception {
SSLEngine[][] enginesToTest = getSSLEnginesToTest();
for (SSLEngine[] engineToTest : enginesToTest) {
SSLEngine clientSSLEngine = engineToTest[0];
SSLEngine serverSSLEngine = engineToTest[1];
// SSLEngine code based on RedhandshakeFinished.java
boolean dataDone = false;
ByteBuffer clientOut = null;
ByteBuffer clientIn = null;
ByteBuffer serverOut = null;
ByteBuffer serverIn = null;
ByteBuffer cTOs;
ByteBuffer sTOc;
SSLSession session = clientSSLEngine.getSession();
int appBufferMax = session.getApplicationBufferSize();
int netBufferMax = session.getPacketBufferSize();
clientIn = ByteBuffer.allocate(appBufferMax + 50);
serverIn = ByteBuffer.allocate(appBufferMax + 50);
cTOs = ByteBuffer.allocateDirect(netBufferMax);
sTOc = ByteBuffer.allocateDirect(netBufferMax);
clientOut = ByteBuffer.wrap(
"Hi Server, I'm Client".getBytes());
serverOut = ByteBuffer.wrap(
"Hello Client, I'm Server".getBytes());
SSLEngineResult clientResult;
SSLEngineResult serverResult;
while (!dataDone) {
clientResult = clientSSLEngine.wrap(clientOut, cTOs);
runDelegatedTasks(clientResult, clientSSLEngine);
serverResult = serverSSLEngine.wrap(serverOut, sTOc);
runDelegatedTasks(serverResult, serverSSLEngine);
cTOs.flip();
sTOc.flip();
if (enableDebug) {
System.out.println("Client -> Network");
printTlsNetworkPacket("", cTOs);
System.out.println("");
System.out.println("Server -> Network");
printTlsNetworkPacket("", sTOc);
System.out.println("");
}
clientResult = clientSSLEngine.unwrap(sTOc, clientIn);
runDelegatedTasks(clientResult, clientSSLEngine);
serverResult = serverSSLEngine.unwrap(cTOs, serverIn);
runDelegatedTasks(serverResult, serverSSLEngine);
cTOs.compact();
sTOc.compact();
if (!dataDone &&
(clientOut.limit() == serverIn.position()) &&
(serverOut.limit() == clientIn.position())) {
checkTransfer(serverOut, clientIn);
checkTransfer(clientOut, serverIn);
dataDone = true;
}
}
}
}
private TlsEstablishedResult(SSLEngine sslEngine) {
super("TLS established: " + sslEngine.getSession());
}
public SSLSession getSSLSession() {
SSLEngine e = this.connection.getSSLEngine();
return e == null ? null : e.getSession();
}
public static void run() throws Exception {
SSLEngine[][] enginesToTest = getSSLEnginesToTest();
for (SSLEngine[] engineToTest : enginesToTest) {
SSLEngine clientSSLEngine = engineToTest[0];
SSLEngine serverSSLEngine = engineToTest[1];
// SSLEngine code based on RedhandshakeFinished.java
boolean dataDone = false;
ByteBuffer clientOut = null;
ByteBuffer clientIn = null;
ByteBuffer serverOut = null;
ByteBuffer serverIn = null;
ByteBuffer cTOs;
ByteBuffer sTOc;
SSLSession session = clientSSLEngine.getSession();
int appBufferMax = session.getApplicationBufferSize();
int netBufferMax = session.getPacketBufferSize();
clientIn = ByteBuffer.allocate(appBufferMax + 50);
serverIn = ByteBuffer.allocate(appBufferMax + 50);
cTOs = ByteBuffer.allocateDirect(netBufferMax);
sTOc = ByteBuffer.allocateDirect(netBufferMax);
clientOut = ByteBuffer.wrap(
"Hi Server, I'm Client".getBytes());
serverOut = ByteBuffer.wrap(
"Hello Client, I'm Server".getBytes());
SSLEngineResult clientResult;
SSLEngineResult serverResult;
while (!dataDone) {
clientResult = clientSSLEngine.wrap(clientOut, cTOs);
runDelegatedTasks(clientResult, clientSSLEngine);
serverResult = serverSSLEngine.wrap(serverOut, sTOc);
runDelegatedTasks(serverResult, serverSSLEngine);
cTOs.flip();
sTOc.flip();
if (enableDebug) {
System.out.println("Client -> Network");
printTlsNetworkPacket("", cTOs);
System.out.println("");
System.out.println("Server -> Network");
printTlsNetworkPacket("", sTOc);
System.out.println("");
}
clientResult = clientSSLEngine.unwrap(sTOc, clientIn);
runDelegatedTasks(clientResult, clientSSLEngine);
serverResult = serverSSLEngine.unwrap(cTOs, serverIn);
runDelegatedTasks(serverResult, serverSSLEngine);
cTOs.compact();
sTOc.compact();
if (!dataDone &&
(clientOut.limit() == serverIn.position()) &&
(serverOut.limit() == clientIn.position())) {
checkTransfer(serverOut, clientIn);
checkTransfer(clientOut, serverIn);
dataDone = true;
}
}
}
}