Skip to content

Commit

Permalink
Prevent accidentally calling SSLEngine.beginHandshake more than once
Browse files Browse the repository at this point in the history
  • Loading branch information
marianobarrios committed Apr 7, 2024
1 parent 51b4c52 commit 0ecf209
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/main/java/tlschannel/impl/TlsChannelImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ public TlsChannelImpl(
private final Lock readLock = new ReentrantLock();
private final Lock writeLock = new ReentrantLock();

private volatile boolean negotiated = false;
private boolean handshakeStarted = false;

private volatile boolean handshakeCompleted = false;

/**
* Whether a IOException was received from the underlying channel or from the {@link SSLEngine}.
Expand Down Expand Up @@ -489,31 +491,41 @@ public void handshake() throws IOException {
}

private void doHandshake(boolean force) throws IOException, EofException {
if (!force && negotiated) {
if (!force && handshakeCompleted) {
return;
}
initLock.lock();
try {
if (invalid || shutdownSent) {
throw new ClosedChannelException();
}
if (force || !negotiated) {
logger.log(Level.FINEST, "Calling SSLEngine.beginHandshake()");
engine.beginHandshake();
if (force || !handshakeCompleted) {

if (!handshakeStarted) {
logger.log(Level.FINEST, "Calling SSLEngine.beginHandshake()");
engine.beginHandshake();

// Some engines that do not support renegotiations may be sensitive to calling
// SSLEngine.beginHandshake() more than once. This guard prevents that.
// See: https://github.com/marianobarrios/tls-channel/issues/197
handshakeStarted = true;
}

writeAndHandshake();

if (engine.getSession().getProtocol().startsWith("DTLS")) {
throw new IllegalArgumentException("DTLS not supported");
}

handshakeCompleted = true;

// call client code
try {
initSessionCallback.accept(engine.getSession());
} catch (Exception e) {
logger.log(Level.FINEST, "client code threw exception in session initialization callback", e);
throw new TlsChannelCallbackException("session initialization callback failed", e);
}
negotiated = true;
}
} finally {
initLock.unlock();
Expand Down

0 comments on commit 0ecf209

Please sign in to comment.