-
Notifications
You must be signed in to change notification settings - Fork 819
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
Update SCRAM dependency to 3.0 and support channel binding #3188
Open
jorsol
wants to merge
1
commit into
pgjdbc:master
Choose a base branch
from
jorsol:scram-3.0
base: master
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
172 changes: 172 additions & 0 deletions
172
pgjdbc/src/main/java/org/postgresql/core/v3/ScramAuthenticator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
/* | ||
* Copyright (c) 2017, PostgreSQL Global Development Group | ||
* See the LICENSE file in the project root for more information. | ||
*/ | ||
|
||
package org.postgresql.core.v3; | ||
|
||
import org.postgresql.core.PGStream; | ||
import org.postgresql.util.GT; | ||
import org.postgresql.util.PSQLException; | ||
import org.postgresql.util.PSQLState; | ||
|
||
import com.ongres.scram.client.ScramClient; | ||
import com.ongres.scram.common.ClientFinalMessage; | ||
import com.ongres.scram.common.ClientFirstMessage; | ||
import com.ongres.scram.common.StringPreparation; | ||
import com.ongres.scram.common.exception.ScramException; | ||
import com.ongres.scram.common.util.TlsServerEndpoint; | ||
|
||
import java.io.IOException; | ||
import java.net.Socket; | ||
import java.nio.charset.StandardCharsets; | ||
import java.security.cert.Certificate; | ||
import java.security.cert.CertificateEncodingException; | ||
import java.security.cert.X509Certificate; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.logging.Level; | ||
import java.util.logging.Logger; | ||
|
||
import javax.net.ssl.SSLException; | ||
import javax.net.ssl.SSLSession; | ||
import javax.net.ssl.SSLSocket; | ||
|
||
final class ScramAuthenticator { | ||
private static final Logger LOGGER = Logger.getLogger(ScramAuthenticator.class.getName()); | ||
|
||
private final PGStream pgStream; | ||
private final ScramClient scramClient; | ||
|
||
ScramAuthenticator(char[] password, PGStream pgStream) throws PSQLException { | ||
this.pgStream = pgStream; | ||
this.scramClient = initializeScramClient(password, pgStream); | ||
} | ||
|
||
private static ScramClient initializeScramClient(char[] password, PGStream stream) throws PSQLException { | ||
try { | ||
final List<String> advertisedMechanisms = advertisedMechanisms(stream); | ||
final byte[] cbindData = extractChannelBindingData(stream); | ||
|
||
ScramClient client = ScramClient.builder() | ||
.advertisedMechanisms(advertisedMechanisms) | ||
.username("*") // username is ignored by server, startup message is used instead | ||
.password(password) | ||
.channelBinding(TlsServerEndpoint.TLS_SERVER_END_POINT, cbindData) | ||
.stringPreparation(StringPreparation.POSTGRESQL_PREPARATION) | ||
.build(); | ||
|
||
if (LOGGER.isLoggable(Level.FINEST)) { | ||
LOGGER.log(Level.FINEST, " Using SCRAM mechanism: {0}", | ||
client.getScramMechanism().getName()); | ||
} | ||
return client; | ||
} catch (IllegalArgumentException | IOException e) { | ||
throw new PSQLException( | ||
GT.tr("Invalid SCRAM client initialization", e), | ||
PSQLState.CONNECTION_REJECTED); | ||
} | ||
} | ||
|
||
private static List<String> advertisedMechanisms(PGStream stream) throws PSQLException, IOException { | ||
List<String> mechanisms = new ArrayList<>(); | ||
do { | ||
mechanisms.add(stream.receiveString()); | ||
} while (stream.peekChar() != 0); | ||
int c = stream.receiveChar(); | ||
assert c == 0; | ||
if (mechanisms.isEmpty()) { | ||
throw new PSQLException( | ||
GT.tr("Received AuthenticationSASL message with 0 mechanisms!"), | ||
PSQLState.CONNECTION_REJECTED); | ||
} | ||
LOGGER.log(Level.FINEST, " <=BE AuthenticationSASL( {0} )", mechanisms); | ||
return mechanisms; | ||
} | ||
|
||
private static byte[] extractChannelBindingData(PGStream stream) { | ||
Socket socket = stream.getSocket(); | ||
if (socket instanceof SSLSocket) { | ||
SSLSession session = ((SSLSocket) socket).getSession(); | ||
try { | ||
Certificate[] certificates = session.getPeerCertificates(); | ||
if (certificates != null && certificates.length > 0) { | ||
Certificate peerCert = certificates[0]; // First certificate is the peer's certificate | ||
if (peerCert instanceof X509Certificate) { | ||
X509Certificate cert = (X509Certificate) peerCert; | ||
return TlsServerEndpoint.getChannelBindingData(cert); | ||
} | ||
} | ||
} catch (CertificateEncodingException | SSLException e) { | ||
if (LOGGER.isLoggable(Level.FINEST)) { | ||
LOGGER.log(Level.FINEST, "Error extracting channel binding data", e); | ||
} | ||
} | ||
} | ||
return new byte[0]; | ||
} | ||
|
||
void handleAuthenticationSASL() throws IOException { | ||
ClientFirstMessage clientFirstMessage = scramClient.clientFirstMessage(); | ||
LOGGER.log(Level.FINEST, " FE=> SASLInitialResponse( {0} )", clientFirstMessage); | ||
String scramMechanismName = scramClient.getScramMechanism().getName(); | ||
final byte[] scramMechanismNameBytes = scramMechanismName.getBytes(StandardCharsets.UTF_8); | ||
final byte[] clientFirstMessageBytes = | ||
clientFirstMessage.toString().getBytes(StandardCharsets.UTF_8); | ||
sendAuthenticationMessage( | ||
(scramMechanismNameBytes.length + 1) + 4 + clientFirstMessageBytes.length, | ||
pgStream -> { | ||
pgStream.send(scramMechanismNameBytes); | ||
pgStream.sendChar(0); // List terminated in '\0' | ||
pgStream.sendInteger4(clientFirstMessageBytes.length); | ||
pgStream.send(clientFirstMessageBytes); | ||
}); | ||
} | ||
|
||
void handleAuthenticationSASLContinue(int length) throws IOException, PSQLException { | ||
String receivedServerFirstMessage = pgStream.receiveString(length); | ||
LOGGER.log(Level.FINEST, " <=BE AuthenticationSASLContinue( {0} )", receivedServerFirstMessage); | ||
try { | ||
scramClient.serverFirstMessage(receivedServerFirstMessage); | ||
} catch (ScramException | IllegalStateException | IllegalArgumentException e) { | ||
throw new PSQLException( | ||
GT.tr("SCRAM authentication failed: {0}", e.getMessage()), | ||
PSQLState.CONNECTION_REJECTED, | ||
e); | ||
} | ||
|
||
ClientFinalMessage clientFinalMessage = scramClient.clientFinalMessage(); | ||
LOGGER.log(Level.FINEST, " FE=> SASLResponse( {0} )", clientFinalMessage); | ||
final byte[] clientFinalMessageBytes = | ||
clientFinalMessage.toString().getBytes(StandardCharsets.UTF_8); | ||
sendAuthenticationMessage( | ||
clientFinalMessageBytes.length, | ||
pgStream -> pgStream.send(clientFinalMessageBytes) | ||
); | ||
} | ||
|
||
void handleAuthenticationSASLFinal(int length) throws IOException, PSQLException { | ||
String serverFinalMessage = pgStream.receiveString(length); | ||
LOGGER.log(Level.FINEST, " <=BE AuthenticationSASLFinal( {0} )", serverFinalMessage); | ||
try { | ||
scramClient.serverFinalMessage(serverFinalMessage); | ||
} catch (ScramException | IllegalStateException | IllegalArgumentException e) { | ||
throw new PSQLException( | ||
GT.tr("SCRAM authentication failed: {0}", e.getMessage()), | ||
PSQLState.CONNECTION_REJECTED, | ||
e); | ||
} | ||
} | ||
|
||
private interface BodySender { | ||
void sendBody(PGStream pgStream) throws IOException; | ||
} | ||
|
||
private void sendAuthenticationMessage(int bodyLength, BodySender bodySender) | ||
throws IOException { | ||
pgStream.sendChar('p'); | ||
pgStream.sendInteger4(Integer.BYTES + bodyLength); | ||
bodySender.sendBody(pgStream); | ||
pgStream.flush(); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If
scram-*
bundles the license file, we could probably remove customizations here, and remove/licenses/*
files.WDYT?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, it bundle the license now, not sure what exact does Gradle here, so if it's not needed to do anything else here, it could be probably removed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The configuration here sets to use license files from https://github.com/pgjdbc/pgjdbc/tree/master/licenses/scram for the scram library. Ideally, libraries should bundle their licenses (and the licenses of the shaded libraries as well), so in the ideal world, overrides should not be needed. However, previous scram versions missed the license files so we had to keep them in pgjdbc source tree
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ouch!, I just checked that the stringprep dependency does not have bundled the LICENSE file, was completely an oversight, so we might need to keep the overrides a bit longer.
I will need to add a test to ensure this never happens in the future.