Skip to content

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 14 commits into from
Aug 11, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[![CI](https://github.com/isoos/postgresql-dart/actions/workflows/dart.yml/badge.svg)](https://github.com/isoos/postgresql-dart/actions/workflows/dart.yml)

A library for connecting to and querying PostgreSQL databases.
A library for connecting to and querying PostgreSQL databases (see [Postgres Protocol](https://www.postgresql.org/docs/13/protocol-overview.html)).

This driver uses the more efficient and secure extended query format of the PostgreSQL protocol.

Expand Down
98 changes: 98 additions & 0 deletions lib/src/auth/auth.dart
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';

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;

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;
}
49 changes: 49 additions & 0 deletions lib/src/auth/md5/md5_authenticator.dart
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';

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);
}
}
134 changes: 134 additions & 0 deletions lib/src/auth/sasl/sasl_authenticator.dart
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';

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);
}
}
Loading