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

Update syn requirement from 1.0 to 2.0 #12

Open
wants to merge 6 commits into
base: neon
Choose a base branch
from
Open
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ name: CI
on:
pull_request:
branches:
- neon
- master
push:
branches:
- neon
- master

env:
Expand Down
2 changes: 2 additions & 0 deletions docker/sql_setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ port = 5433
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
wal_level = logical
EOCONF

cat > "$PGDATA/pg_hba.conf" <<-EOCONF
Expand All @@ -82,6 +83,7 @@ host all ssl_user ::0/0 reject

# IPv4 local connections:
host all postgres 0.0.0.0/0 trust
host replication postgres 0.0.0.0/0 trust
# IPv6 local connections:
host all postgres ::0/0 trust
# Unix socket connections:
Expand Down
2 changes: 1 addition & 1 deletion postgres-derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ proc-macro = true
test = false

[dependencies]
syn = "1.0"
syn = "2.0"
proc-macro2 = "1.0"
quote = "1.0"
1 change: 1 addition & 0 deletions postgres-protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ byteorder = "1.0"
bytes = "1.0"
fallible-iterator = "0.2"
hmac = "0.12"
lazy_static = "1.4"
md-5 = "0.10"
memchr = "2.0"
rand = "0.8"
Expand Down
112 changes: 75 additions & 37 deletions postgres-protocol/src/authentication/sasl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,32 @@ impl ChannelBinding {
}
}

/// A pair of keys for the SCRAM-SHA-256 mechanism.
/// See <https://datatracker.ietf.org/doc/html/rfc5802#section-3> for details.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScramKeys<const N: usize> {
/// Used by server to authenticate client.
pub client_key: [u8; N],
/// Used by client to verify server's signature.
pub server_key: [u8; N],
}

/// Password or keys which were derived from it.
enum Credentials<const N: usize> {
/// A regular password as a vector of bytes.
Password(Vec<u8>),
/// A precomputed pair of keys.
Keys(Box<ScramKeys<N>>),
}

enum State {
Update {
nonce: String,
password: Vec<u8>,
password: Credentials<32>,
channel_binding: ChannelBinding,
},
Finish {
salted_password: [u8; 32],
server_key: [u8; 32],
auth_message: String,
},
Done,
Expand All @@ -129,30 +147,43 @@ pub struct ScramSha256 {
state: State,
}

fn nonce() -> String {
// rand 0.5's ThreadRng is cryptographically secure
let mut rng = rand::thread_rng();
(0..NONCE_LENGTH)
.map(|_| {
let mut v = rng.gen_range(0x21u8..0x7e);
if v == 0x2c {
v = 0x7e
}
v as char
})
.collect()
}

impl ScramSha256 {
/// Constructs a new instance which will use the provided password for authentication.
pub fn new(password: &[u8], channel_binding: ChannelBinding) -> ScramSha256 {
// rand 0.5's ThreadRng is cryptographically secure
let mut rng = rand::thread_rng();
let nonce = (0..NONCE_LENGTH)
.map(|_| {
let mut v = rng.gen_range(0x21u8..0x7e);
if v == 0x2c {
v = 0x7e
}
v as char
})
.collect::<String>();
let password = Credentials::Password(normalize(password));
ScramSha256::new_inner(password, channel_binding, nonce())
}

ScramSha256::new_inner(password, channel_binding, nonce)
/// Constructs a new instance which will use the provided key pair for authentication.
pub fn new_with_keys(keys: ScramKeys<32>, channel_binding: ChannelBinding) -> ScramSha256 {
let password = Credentials::Keys(keys.into());
ScramSha256::new_inner(password, channel_binding, nonce())
}

fn new_inner(password: &[u8], channel_binding: ChannelBinding, nonce: String) -> ScramSha256 {
fn new_inner(
password: Credentials<32>,
channel_binding: ChannelBinding,
nonce: String,
) -> ScramSha256 {
ScramSha256 {
message: format!("{}n=,r={}", channel_binding.gs2_header(), nonce),
state: State::Update {
nonce,
password: normalize(password),
password,
channel_binding,
},
}
Expand Down Expand Up @@ -189,20 +220,32 @@ impl ScramSha256 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid nonce"));
}

let salt = match base64::decode(parsed.salt) {
Ok(salt) => salt,
Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidInput, e)),
};
let (client_key, server_key) = match password {
Credentials::Password(password) => {
let salt = match base64::decode(parsed.salt) {
Ok(salt) => salt,
Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidInput, e)),
};

let salted_password = hi(&password, &salt, parsed.iteration_count);
let salted_password = hi(&password, &salt, parsed.iteration_count);

let mut hmac = Hmac::<Sha256>::new_from_slice(&salted_password)
.expect("HMAC is able to accept all key sizes");
hmac.update(b"Client Key");
let client_key = hmac.finalize().into_bytes();
let make_key = |name| {
let mut hmac = Hmac::<Sha256>::new_from_slice(&salted_password)
.expect("HMAC is able to accept all key sizes");
hmac.update(name);

let mut key = [0u8; 32];
key.copy_from_slice(hmac.finalize().into_bytes().as_slice());
key
};

(make_key(b"Client Key"), make_key(b"Server Key"))
}
Credentials::Keys(keys) => (keys.client_key, keys.server_key),
};

let mut hash = Sha256::default();
hash.update(client_key.as_slice());
hash.update(client_key);
let stored_key = hash.finalize_fixed();

let mut cbind_input = vec![];
Expand All @@ -225,10 +268,10 @@ impl ScramSha256 {
*proof ^= signature;
}

write!(&mut self.message, ",p={}", base64::encode(&*client_proof)).unwrap();
write!(&mut self.message, ",p={}", base64::encode(client_proof)).unwrap();

self.state = State::Finish {
salted_password,
server_key,
auth_message,
};
Ok(())
Expand All @@ -239,11 +282,11 @@ impl ScramSha256 {
/// This should be called when the backend sends an `AuthenticationSASLFinal` message.
/// Authentication has only succeeded if this method returns `Ok(())`.
pub fn finish(&mut self, message: &[u8]) -> io::Result<()> {
let (salted_password, auth_message) = match mem::replace(&mut self.state, State::Done) {
let (server_key, auth_message) = match mem::replace(&mut self.state, State::Done) {
State::Finish {
salted_password,
server_key,
auth_message,
} => (salted_password, auth_message),
} => (server_key, auth_message),
_ => return Err(io::Error::new(io::ErrorKind::Other, "invalid SCRAM state")),
};

Expand All @@ -267,11 +310,6 @@ impl ScramSha256 {
Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidInput, e)),
};

let mut hmac = Hmac::<Sha256>::new_from_slice(&salted_password)
.expect("HMAC is able to accept all key sizes");
hmac.update(b"Server Key");
let server_key = hmac.finalize().into_bytes();

let mut hmac = Hmac::<Sha256>::new_from_slice(&server_key)
.expect("HMAC is able to accept all key sizes");
hmac.update(auth_message.as_bytes());
Expand Down Expand Up @@ -458,7 +496,7 @@ mod test {
let server_final = "v=U+ppxD5XUKtradnv8e2MkeupiA8FU87Sg8CXzXHDAzw=";

let mut scram = ScramSha256::new_inner(
password.as_bytes(),
Credentials::Password(normalize(password.as_bytes())),
ChannelBinding::unsupported(),
nonce.to_string(),
);
Expand Down
7 changes: 7 additions & 0 deletions postgres-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@

use byteorder::{BigEndian, ByteOrder};
use bytes::{BufMut, BytesMut};
use lazy_static::lazy_static;
use std::io;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

pub mod authentication;
pub mod escape;
Expand All @@ -28,6 +30,11 @@ pub type Oid = u32;
/// A Postgres Log Sequence Number (LSN).
pub type Lsn = u64;

lazy_static! {
/// Postgres epoch is 2000-01-01T00:00:00Z
pub static ref PG_EPOCH: SystemTime = UNIX_EPOCH + Duration::from_secs(946_684_800);
}

/// An enum indicating if a value is `NULL` or not.
pub enum IsNull {
/// The value is `NULL`.
Expand Down
Loading