-
Notifications
You must be signed in to change notification settings - Fork 39
SASL / SCRAM-SHA-256 Authentication #6
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
d2d38aa
Abstract Authenticators (MD5)
Gustl22 b62d2a8
Sasl/Scram Authenticator
Gustl22 f0ebbda
Relative links for imports
Gustl22 48aeeee
Move applyStringToBuffer to UTF8BackedString.applyToBuffer
Gustl22 dba3cd2
Use sasl scram lib
Gustl22 5248abe
Move authenticators
Gustl22 754f1a4
Reenable SSL test
Gustl22 2d22dad
👌 Change sasl_scram package source.
Gustl22 0a8379a
Merge branch 'master' into authenticators
Gustl22 ba68358
👌 Update CHANGELOG.md, Update sasl_scram dependency
Gustl22 5a23b85
👌 Review improvements (#6)
Gustl22 7e0a608
👌 improve log message (#6)
Gustl22 ea87688
👌 Remove redundant credentials in authenticator
Gustl22 3a85e06
👌 Remove authenticationScheme from PostgreSQLConnection
Gustl22 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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,98 @@ | ||
/// Source: https://github.com/mongo-dart/mongo_dart/blob/c761839efbf47ec556f853dec85debb4cb9370f7/lib/src/auth/auth.dart | ||
|
||
// (The MIT License) | ||
// | ||
// Copyright (c) 2012 Vadim Tsushko (vadimtsushko@gmail.com) | ||
// | ||
// Permission is hereby granted, free of charge, to any person obtaining | ||
// a copy of this software and associated documentation files (the | ||
// 'Software'), to deal in the Software without restriction, including | ||
// without limitation the rights to use, copy, modify, merge, publish, | ||
// distribute, sublicense, and/or sell copies of the Software, and to | ||
// permit persons to whom the Software is furnished to do so, subject to | ||
// the following conditions: | ||
// | ||
// The above copyright notice and this permission notice shall be | ||
// included in all copies or substantial portions of the Software. | ||
// | ||
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, | ||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, | ||
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | ||
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
|
||
import 'dart:math'; | ||
|
||
import 'package:postgres/src/auth/sasl/scram_sha256_authenticator.dart'; | ||
Gustl22 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
import '../../postgres.dart'; | ||
import '../server_messages.dart'; | ||
import 'md5/md5_authenticator.dart'; | ||
|
||
enum AuthenticationScheme { MD5, SCRAM_SHA_256 } | ||
|
||
abstract class Authenticator { | ||
static String? name; | ||
late final PostgreSQLConnection connection; | ||
|
||
Authenticator(this.connection); | ||
|
||
void init(); | ||
|
||
void onMessage(AuthenticationMessage message); | ||
} | ||
|
||
Authenticator createAuthenticator(PostgreSQLConnection connection, UsernamePasswordCredential credentials) { | ||
switch (connection.authenticationScheme) { | ||
case AuthenticationScheme.MD5: | ||
return MD5Authenticator(connection, credentials); | ||
case AuthenticationScheme.SCRAM_SHA_256: | ||
return ScramSha256Authenticator(connection, credentials); | ||
default: | ||
throw PostgreSQLException("Authenticator wasn't specified"); | ||
} | ||
} | ||
|
||
class UsernamePasswordCredential { | ||
String? username; | ||
String? password; // TODO: Encrypt this to secureString | ||
} | ||
|
||
abstract class RandomStringGenerator { | ||
static const String allowedCharacters = '!"#\'\$%&()*+-./0123456789:;<=>?@' | ||
'ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'; | ||
String generate(int length); | ||
} | ||
|
||
class CryptoStrengthStringGenerator extends RandomStringGenerator { | ||
@override | ||
String generate(int length) { | ||
final random = Random.secure(); | ||
final allowedCodeUnits = RandomStringGenerator.allowedCharacters.codeUnits; | ||
|
||
final max = allowedCodeUnits.length - 1; | ||
Gustl22 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
final randomString = <int>[]; | ||
|
||
for (var i = 0; i < length; ++i) { | ||
randomString.add(allowedCodeUnits.elementAt(random.nextInt(max))); | ||
} | ||
|
||
return String.fromCharCodes(randomString); | ||
} | ||
} | ||
|
||
Map<String, String> parsePayload(String payload) { | ||
final dict = <String, String>{}; | ||
final parts = payload.split(','); | ||
|
||
for (var i = 0; i < parts.length; i++) { | ||
final key = parts[i][0]; | ||
final value = parts[i].substring(2); | ||
dict[key] = value; | ||
} | ||
|
||
return dict; | ||
} |
This file contains hidden or 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,49 @@ | ||
import 'package:buffer/buffer.dart'; | ||
import 'package:crypto/crypto.dart'; | ||
import 'package:postgres/src/server_messages.dart'; | ||
Gustl22 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
import '../../../postgres.dart'; | ||
import '../../client_messages.dart'; | ||
import '../../utf8_backed_string.dart'; | ||
import '../auth.dart'; | ||
|
||
class MD5Authenticator extends Authenticator { | ||
static final String name = 'MD5'; | ||
late List<int> _salt; | ||
|
||
final UsernamePasswordCredential credentials; | ||
|
||
MD5Authenticator(PostgreSQLConnection connection, this.credentials): super(connection); | ||
|
||
@override | ||
void init() {} | ||
|
||
@override | ||
void onMessage(AuthenticationMessage message) { | ||
final reader = ByteDataReader()..add(message.bytes); | ||
_salt = reader.read(4, copy: true); | ||
|
||
final authMessage = AuthMD5Message(connection.username!, connection.password!, _salt); | ||
|
||
connection.socket!.add(authMessage.asBytes()); | ||
} | ||
} | ||
|
||
class AuthMD5Message extends ClientMessage { | ||
UTF8BackedString? _hashedAuthString; | ||
|
||
AuthMD5Message(String username, String password, List<int> saltBytes) { | ||
final passwordHash = md5.convert('$password$username'.codeUnits).toString(); | ||
final saltString = String.fromCharCodes(saltBytes); | ||
final md5Hash = md5.convert('$passwordHash$saltString'.codeUnits).toString(); | ||
_hashedAuthString = UTF8BackedString('md5$md5Hash'); | ||
} | ||
|
||
@override | ||
void applyToBuffer(ByteDataWriter buffer) { | ||
buffer.writeUint8(ClientMessage.PasswordIdentifier); | ||
final length = 5 + _hashedAuthString!.utf8Length; | ||
buffer.writeUint32(length); | ||
applyStringToBuffer(_hashedAuthString!, buffer); | ||
} | ||
} |
This file contains hidden or 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,134 @@ | ||
/// Source: https://github.com/mongo-dart/mongo_dart/blob/c761839efbf47ec556f853dec85debb4cb9370f7/lib/src/auth/sasl_authenticator.dart | ||
|
||
// (The MIT License) | ||
// | ||
// Copyright (c) 2012 Vadim Tsushko (vadimtsushko@gmail.com) | ||
// | ||
// Permission is hereby granted, free of charge, to any person obtaining | ||
// a copy of this software and associated documentation files (the | ||
// 'Software'), to deal in the Software without restriction, including | ||
// without limitation the rights to use, copy, modify, merge, publish, | ||
// distribute, sublicense, and/or sell copies of the Software, and to | ||
// permit persons to whom the Software is furnished to do so, subject to | ||
// the following conditions: | ||
// | ||
// The above copyright notice and this permission notice shall be | ||
// included in all copies or substantial portions of the Software. | ||
// | ||
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, | ||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, | ||
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | ||
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
|
||
import 'dart:typed_data'; | ||
|
||
import 'package:buffer/buffer.dart'; | ||
import 'package:postgres/src/utf8_backed_string.dart'; | ||
Gustl22 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
import '../../../postgres.dart'; | ||
import '../../client_messages.dart'; | ||
import '../../server_messages.dart'; | ||
import '../auth.dart'; | ||
|
||
abstract class SaslMechanism { | ||
String get name; | ||
|
||
SaslStep initialize(PostgreSQLConnection connection); | ||
} | ||
|
||
abstract class SaslStep { | ||
Uint8List bytesToSendToServer; | ||
bool isComplete = false; | ||
|
||
SaslStep(this.bytesToSendToServer, {this.isComplete = false}); | ||
|
||
SaslStep transition(SaslConversation conversation, List<int> bytesReceivedFromServer); | ||
} | ||
|
||
class SaslConversation { | ||
PostgreSQLConnection connection; | ||
|
||
SaslConversation(this.connection); | ||
} | ||
|
||
/// Structure for SASL Authenticator | ||
abstract class SaslAuthenticator extends Authenticator { | ||
static const int DefaultNonceLength = 24; | ||
|
||
SaslMechanism mechanism; | ||
late SaslStep currentStep; | ||
late SaslConversation conversation; | ||
|
||
SaslAuthenticator(PostgreSQLConnection connection, this.mechanism) : super(connection); | ||
|
||
@override | ||
void init() { | ||
conversation = SaslConversation(connection); | ||
} | ||
|
||
@override | ||
void onMessage(AuthenticationMessage message) { | ||
ClientMessage msg; | ||
switch (message.type) { | ||
case AuthenticationMessage.KindSASL: | ||
currentStep = mechanism.initialize(connection); | ||
msg = SaslClientFirstMessage(currentStep, mechanism); | ||
break; | ||
case AuthenticationMessage.KindSASLContinue: | ||
currentStep = currentStep.transition(conversation, message.bytes); | ||
msg = SaslClientLastMessage(currentStep); | ||
break; | ||
case AuthenticationMessage.KindSASLFinal: | ||
currentStep = currentStep.transition(conversation, message.bytes); | ||
return; | ||
default: | ||
throw PostgreSQLException('Unsupported authentication type ${message.type}, closing connection.'); | ||
} | ||
connection.socket!.add(msg.asBytes()); | ||
} | ||
} | ||
|
||
class SaslClientFirstMessage extends ClientMessage { | ||
SaslStep saslStep; | ||
SaslMechanism mechanism; | ||
|
||
SaslClientFirstMessage(this.saslStep, this.mechanism); | ||
|
||
@override | ||
void applyToBuffer(ByteDataWriter buffer) { | ||
buffer.writeUint8(ClientMessage.PasswordIdentifier); | ||
|
||
final utf8CachedMechanismName = UTF8BackedString(mechanism.name); | ||
|
||
final msgLength = saslStep.bytesToSendToServer.length; | ||
// No Identifier bit + 4 byte counts (for whole length) + mechanism bytes + zero byte + 4 byte counts (for msg length) + msg bytes | ||
final length = 4 + utf8CachedMechanismName.utf8Length + 1 + 4 + msgLength; | ||
|
||
buffer.writeUint32(length); | ||
applyStringToBuffer(utf8CachedMechanismName, buffer); | ||
|
||
// do not add the msg byte count for whatever reason | ||
buffer.writeUint32(msgLength); | ||
buffer.write(saslStep.bytesToSendToServer); | ||
} | ||
} | ||
|
||
class SaslClientLastMessage extends ClientMessage { | ||
SaslStep saslStep; | ||
|
||
SaslClientLastMessage(this.saslStep); | ||
|
||
@override | ||
void applyToBuffer(ByteDataWriter buffer) { | ||
buffer.writeUint8(ClientMessage.PasswordIdentifier); | ||
|
||
// No Identifier bit + 4 byte counts (for msg length) + msg bytes | ||
final length = 4 + saslStep.bytesToSendToServer.length; | ||
|
||
buffer.writeUint32(length); | ||
buffer.write(saslStep.bytesToSendToServer); | ||
} | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.