Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent accidentally calling SSLEngine.beginHandshake more than once #201

Merged
merged 1 commit into from
Apr 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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