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 base64 requirement from 0.20 to 0.22 #28

Open
wants to merge 24 commits into
base: neon
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9542b25
Enable CI for `neon` branch
funbringer Apr 15, 2022
2005bf7
Support for physical and logical replication
funbringer Dec 14, 2020
2b4beff
Extend replication protocol with ZenithStatusUpdate message
lubennikovaav Dec 20, 2021
a27a406
Allow passing precomputed SCRAM keys via Config
funbringer Apr 19, 2022
43e6db2
Make tokio-postgres connection parameters public
funbringer Dec 15, 2022
0bc41d8
Expose conection.stream
kelvich Apr 27, 2023
2e9b5f1
Add text protocol based query method (#14)
kelvich May 23, 2023
f6ec31d
Allow passing null params in query_raw_txt()
kelvich Jun 8, 2023
1aaedab
Return more RowDescription fields
kelvich Jun 12, 2023
9011f71
add query_raw_txt for transaction (#20)
skyzh Jul 24, 2023
b25e7f3
Connection changes (#21)
conradludgate Aug 11, 2023
a2d0652
simple query ready for query (#22)
conradludgate Aug 24, 2023
a028f0c
fix panic in try_get
conradludgate Oct 19, 2023
efefdee
lints
conradludgate Oct 19, 2023
c0b5882
deprecated
conradludgate Oct 19, 2023
7434d93
deprecated
conradludgate Oct 19, 2023
1235ee7
make raw_txt not prepare statements
conradludgate Oct 31, 2023
dce71d2
fmt
conradludgate Oct 31, 2023
a39aaf6
offer get_type api
conradludgate Oct 31, 2023
b502452
add columns to rowstream
conradludgate Oct 31, 2023
ce7260d
get type generic client
conradludgate Oct 31, 2023
ef8559b
make CopyBothDuplex struct `pub` (#25)
problame Nov 3, 2023
988d0dd
Getter for process id (#26)
khanova Nov 16, 2023
934cbdd
Update base64 requirement from 0.20 to 0.22
dependabot[bot] Mar 4, 2024
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
12 changes: 7 additions & 5 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 All @@ -17,15 +19,15 @@ jobs:
name: rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- uses: sfackler/actions/rustup@master
- uses: sfackler/actions/rustfmt@master

clippy:
name: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- uses: sfackler/actions/rustup@master
- run: echo "::set-output name=version::$(rustc --version)"
id: rust-version
Expand All @@ -45,17 +47,17 @@ jobs:
with:
path: target
key: clippy-target-${{ runner.os }}-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }}y
- run: cargo clippy --all --all-targets
- run: cargo clippy --workspace --all-targets

test:
name: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- run: docker compose up -d
- uses: sfackler/actions/rustup@master
with:
version: 1.62.0
version: 1.67.0
- run: echo "::set-output name=version::$(rustc --version)"
id: rust-version
- uses: actions/cache@v1
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
4 changes: 2 additions & 2 deletions postgres-derive-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ where
T: PartialEq + FromSqlOwned + ToSql + Sync,
S: fmt::Display,
{
for &(ref val, ref repr) in checks.iter() {
for (val, repr) in checks.iter() {
let stmt = conn
.prepare(&format!("SELECT {}::{}", *repr, sql_type))
.unwrap();
Expand All @@ -38,7 +38,7 @@ pub fn test_type_asymmetric<T, F, S, C>(
S: fmt::Display,
C: Fn(&T, &F) -> bool,
{
for &(ref val, ref repr) in checks.iter() {
for (val, repr) in checks.iter() {
let stmt = conn
.prepare(&format!("SELECT {}::{}", *repr, sql_type))
.unwrap();
Expand Down
3 changes: 2 additions & 1 deletion postgres-protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ repository = "https://github.com/sfackler/rust-postgres"
readme = "../README.md"

[dependencies]
base64 = "0.20"
base64 = "0.22"
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
114 changes: 76 additions & 38 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 @@ -351,7 +389,7 @@ impl<'a> Parser<'a> {
}

fn posit_number(&mut self) -> io::Result<u32> {
let n = self.take_while(|c| matches!(c, '0'..='9'))?;
let n = self.take_while(|c| c.is_ascii_digit())?;
n.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
}
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
Loading