sentinel-driver 2.0.0

High-performance PostgreSQL wire protocol driver for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};

use crate::config::ChannelBinding;
use crate::connection::stream::PgConnection;
use crate::error::{Error, Result};
use crate::protocol::backend::BackendMessage;
use crate::protocol::frontend;

type HmacSha256 = Hmac<Sha256>;

/// Perform SCRAM-SHA-256 (or SCRAM-SHA-256-PLUS) authentication with the server.
///
/// This handles the full 3-message exchange:
/// 1. Client sends SASLInitialResponse with client-first-message
/// 2. Server replies with AuthenticationSaslContinue (server-first-message)
/// 3. Client sends SASLResponse with client-final-message
/// 4. Server replies with AuthenticationSaslFinal (server-final verification)
pub(crate) async fn authenticate(
    conn: &mut PgConnection,
    password: &str,
    mechanisms: &[String],
    channel_binding: ChannelBinding,
    server_cert_der: Option<&[u8]>,
) -> Result<()> {
    // Determine mechanism and GS2 header based on channel binding config
    let has_plus = mechanisms.iter().any(|m| m == "SCRAM-SHA-256-PLUS");
    let has_plain = mechanisms.iter().any(|m| m == "SCRAM-SHA-256");
    let is_tls = server_cert_der.is_some();

    let (mechanism, gs2_header) = select_mechanism(channel_binding, is_tls, has_plus, has_plain)?;

    // SASLprep the password (RFC 7613)
    let prepped_password = saslprep(password)?;

    // Generate client nonce
    let client_nonce = generate_nonce();

    // Client-first-message-bare: n=,r=<nonce>
    // We don't send a username in the SCRAM exchange; PG uses the startup user.
    let client_first_bare = format!("n=,r={client_nonce}");
    let client_first_message = format!("{gs2_header}{client_first_bare}");

    // Send SASLInitialResponse
    frontend::sasl_initial_response(conn.write_buf(), mechanism, client_first_message.as_bytes());
    conn.send().await?;

    // Receive server-first-message
    let server_first = match conn.recv().await? {
        BackendMessage::AuthenticationSaslContinue { data } => String::from_utf8(data)
            .map_err(|e| Error::Auth(format!("invalid server-first-message: {e}")))?,
        BackendMessage::ErrorResponse { fields } => {
            return Err(Error::server(
                fields.severity,
                fields.code,
                fields.message,
                fields.detail,
                fields.hint,
                fields.position,
            ));
        }
        other => {
            return Err(Error::protocol(format!(
                "expected SaslContinue, got {other:?}"
            )));
        }
    };

    // Parse server-first-message: r=<nonce>,s=<salt>,i=<iterations>
    let parsed = parse_server_first(&server_first)?;

    // Verify server nonce starts with our client nonce
    if !parsed.nonce.starts_with(&client_nonce) {
        return Err(Error::Auth(
            "server nonce doesn't match client nonce".into(),
        ));
    }

    let salt = BASE64
        .decode(&parsed.salt)
        .map_err(|e| Error::Auth(format!("invalid salt base64: {e}")))?;

    // Compute SCRAM proof
    let salted_password = hi(prepped_password.as_bytes(), &salt, parsed.iterations);
    let client_key = hmac_sha256(&salted_password, b"Client Key");
    let stored_key = sha256(&client_key);
    let server_key = hmac_sha256(&salted_password, b"Server Key");

    // Build channel binding data for c= parameter
    let cbind_input = build_channel_binding_data(gs2_header, server_cert_der);
    let channel_binding_b64 = BASE64.encode(&cbind_input);

    // client-final-message-without-proof
    let client_final_without_proof = format!("c={channel_binding_b64},r={}", parsed.nonce);

    // AuthMessage = client-first-bare + "," + server-first + "," + client-final-without-proof
    let auth_message = format!("{client_first_bare},{server_first},{client_final_without_proof}");

    let client_signature = hmac_sha256(&stored_key, auth_message.as_bytes());
    let client_proof: Vec<u8> = client_key
        .iter()
        .zip(client_signature.iter())
        .map(|(a, b)| a ^ b)
        .collect();

    let server_signature = hmac_sha256(&server_key, auth_message.as_bytes());

    // Send client-final-message
    let client_final = format!(
        "{client_final_without_proof},p={}",
        BASE64.encode(&client_proof)
    );

    frontend::sasl_response(conn.write_buf(), client_final.as_bytes());
    conn.send().await?;

    // Receive server-final-message
    match conn.recv().await? {
        BackendMessage::AuthenticationSaslFinal { data } => {
            let server_final = String::from_utf8(data)
                .map_err(|e| Error::Auth(format!("invalid server-final-message: {e}")))?;

            // Verify server signature
            let expected_verifier = format!("v={}", BASE64.encode(&server_signature));
            if server_final != expected_verifier {
                return Err(Error::Auth("server signature verification failed".into()));
            }
        }
        BackendMessage::ErrorResponse { fields } => {
            return Err(Error::server(
                fields.severity,
                fields.code,
                fields.message,
                fields.detail,
                fields.hint,
                fields.position,
            ));
        }
        other => {
            return Err(Error::protocol(format!(
                "expected SaslFinal, got {other:?}"
            )));
        }
    }

    // Wait for AuthenticationOk
    match conn.recv().await? {
        BackendMessage::AuthenticationOk => Ok(()),
        BackendMessage::ErrorResponse { fields } => Err(Error::server(
            fields.severity,
            fields.code,
            fields.message,
            fields.detail,
            fields.hint,
            fields.position,
        )),
        other => Err(Error::protocol(format!(
            "expected AuthenticationOk, got {other:?}"
        ))),
    }
}

/// Select SCRAM mechanism and GS2 header based on channel binding config.
fn select_mechanism(
    channel_binding: ChannelBinding,
    is_tls: bool,
    has_plus: bool,
    has_plain: bool,
) -> Result<(&'static str, &'static str)> {
    match channel_binding {
        ChannelBinding::Require => {
            if !is_tls {
                return Err(Error::Auth("channel binding requires TLS".into()));
            }
            if !has_plus {
                return Err(Error::Auth(
                    "server does not support SCRAM-SHA-256-PLUS".into(),
                ));
            }
            Ok(("SCRAM-SHA-256-PLUS", "p=tls-server-end-point,,"))
        }
        ChannelBinding::Prefer => {
            if is_tls && has_plus {
                Ok(("SCRAM-SHA-256-PLUS", "p=tls-server-end-point,,"))
            } else if has_plain {
                // y,, = client supports channel binding but server doesn't advertise it
                let gs2 = if is_tls { "y,," } else { "n,," };
                Ok(("SCRAM-SHA-256", gs2))
            } else {
                Err(Error::Auth(
                    "server offered no supported SASL mechanisms".into(),
                ))
            }
        }
        ChannelBinding::Disable => {
            if has_plain {
                Ok(("SCRAM-SHA-256", "n,,"))
            } else {
                Err(Error::Auth(
                    "server offered no supported SASL mechanisms".into(),
                ))
            }
        }
    }
}

/// Build the channel binding input bytes: gs2_header + cbind_data.
///
/// For `tls-server-end-point`, cbind_data is SHA-256 hash of the server's DER certificate.
/// For non-PLUS, cbind_data is empty (just the GS2 header).
fn build_channel_binding_data(gs2_header: &str, server_cert_der: Option<&[u8]>) -> Vec<u8> {
    let mut data = gs2_header.as_bytes().to_vec();
    if gs2_header.starts_with("p=tls-server-end-point") {
        if let Some(cert_der) = server_cert_der {
            let hash = sha256(cert_der);
            data.extend_from_slice(&hash);
        }
    }
    data
}

pub struct ServerFirst {
    pub nonce: String,
    pub salt: String,
    pub iterations: u32,
}

pub fn parse_server_first(msg: &str) -> Result<ServerFirst> {
    let mut nonce = None;
    let mut salt = None;
    let mut iterations = None;

    for part in msg.split(',') {
        if let Some(val) = part.strip_prefix("r=") {
            nonce = Some(val.to_string());
        } else if let Some(val) = part.strip_prefix("s=") {
            salt = Some(val.to_string());
        } else if let Some(val) = part.strip_prefix("i=") {
            iterations = Some(
                val.parse::<u32>()
                    .map_err(|_| Error::Auth(format!("invalid iteration count: {val}")))?,
            );
        }
    }

    Ok(ServerFirst {
        nonce: nonce.ok_or_else(|| Error::Auth("missing nonce in server-first".into()))?,
        salt: salt.ok_or_else(|| Error::Auth("missing salt in server-first".into()))?,
        iterations: iterations
            .ok_or_else(|| Error::Auth("missing iterations in server-first".into()))?,
    })
}

/// Hi(password, salt, iterations) — PBKDF2-HMAC-SHA256.
pub fn hi(password: &[u8], salt: &[u8], iterations: u32) -> Vec<u8> {
    // U1 = HMAC(password, salt + INT(1))
    let mut salt_with_one = salt.to_vec();
    salt_with_one.extend_from_slice(&1u32.to_be_bytes());

    let mut u_prev = hmac_sha256(password, &salt_with_one);
    let mut result = u_prev.clone();

    for _ in 1..iterations {
        let u_current = hmac_sha256(password, &u_prev);
        for (r, u) in result.iter_mut().zip(u_current.iter()) {
            *r ^= u;
        }
        u_prev = u_current;
    }

    result
}

pub fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
    #[allow(clippy::expect_used)]
    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
    mac.update(data);
    mac.finalize().into_bytes().to_vec()
}

fn sha256(data: &[u8]) -> Vec<u8> {
    let mut hasher = Sha256::new();
    hasher.update(data);
    hasher.finalize().to_vec()
}

/// SASLprep (RFC 7613) password normalization.
///
/// This is what sqlx gets wrong — they skip this step, leading to
/// authentication failures with non-ASCII passwords.
pub fn saslprep(input: &str) -> Result<String> {
    stringprep::saslprep(input)
        .map(std::borrow::Cow::into_owned)
        .map_err(|e| Error::Auth(format!("SASLprep failed: {e}")))
}

/// Generate a random nonce for SCRAM.
pub fn generate_nonce() -> String {
    use rand::Rng;
    let mut rng = rand::thread_rng();
    let bytes: Vec<u8> = (0..24).map(|_| rng.gen()).collect();
    BASE64.encode(&bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_select_mechanism_require_with_tls_and_plus() {
        let (mech, gs2) = select_mechanism(ChannelBinding::Require, true, true, true).unwrap();
        assert_eq!(mech, "SCRAM-SHA-256-PLUS");
        assert_eq!(gs2, "p=tls-server-end-point,,");
    }

    #[test]
    fn test_select_mechanism_require_without_tls() {
        let err = select_mechanism(ChannelBinding::Require, false, false, true).unwrap_err();
        assert!(err.to_string().contains("channel binding requires TLS"));
    }

    #[test]
    fn test_select_mechanism_require_no_plus() {
        let err = select_mechanism(ChannelBinding::Require, true, false, true).unwrap_err();
        assert!(err
            .to_string()
            .contains("does not support SCRAM-SHA-256-PLUS"));
    }

    #[test]
    fn test_select_mechanism_prefer_with_tls_and_plus() {
        let (mech, gs2) = select_mechanism(ChannelBinding::Prefer, true, true, true).unwrap();
        assert_eq!(mech, "SCRAM-SHA-256-PLUS");
        assert_eq!(gs2, "p=tls-server-end-point,,");
    }

    #[test]
    fn test_select_mechanism_prefer_tls_no_plus() {
        let (mech, gs2) = select_mechanism(ChannelBinding::Prefer, true, false, true).unwrap();
        assert_eq!(mech, "SCRAM-SHA-256");
        assert_eq!(gs2, "y,,");
    }

    #[test]
    fn test_select_mechanism_prefer_no_tls() {
        let (mech, gs2) = select_mechanism(ChannelBinding::Prefer, false, false, true).unwrap();
        assert_eq!(mech, "SCRAM-SHA-256");
        assert_eq!(gs2, "n,,");
    }

    #[test]
    fn test_select_mechanism_disable() {
        let (mech, gs2) = select_mechanism(ChannelBinding::Disable, true, true, true).unwrap();
        assert_eq!(mech, "SCRAM-SHA-256");
        assert_eq!(gs2, "n,,");
    }

    #[test]
    fn test_build_channel_binding_no_plus() {
        let data = build_channel_binding_data("n,,", None);
        assert_eq!(data, b"n,,");
        assert_eq!(BASE64.encode(&data), "biws");
    }

    #[test]
    fn test_build_channel_binding_with_plus() {
        let fake_cert = b"fake-server-certificate-der";
        let data = build_channel_binding_data("p=tls-server-end-point,,", Some(fake_cert));
        // Should be: gs2_header bytes + sha256(cert)
        let expected_hash = sha256(fake_cert);
        let mut expected = b"p=tls-server-end-point,,".to_vec();
        expected.extend_from_slice(&expected_hash);
        assert_eq!(data, expected);
    }

    #[test]
    fn test_gs2_header_y_flag() {
        // y,, means client supports CB but server didn't advertise PLUS
        let (mech, gs2) = select_mechanism(ChannelBinding::Prefer, true, false, true).unwrap();
        assert_eq!(mech, "SCRAM-SHA-256");
        assert_eq!(gs2, "y,,");
        let data = build_channel_binding_data(gs2, Some(b"cert"));
        // y,, should NOT include channel binding data
        assert_eq!(data, b"y,,");
    }

    #[test]
    fn test_select_mechanism_prefer_no_mechanisms() {
        let err = select_mechanism(ChannelBinding::Prefer, false, false, false).unwrap_err();
        assert!(err.to_string().contains("no supported SASL mechanisms"));
    }

    #[test]
    fn test_select_mechanism_prefer_tls_no_mechanisms() {
        let err = select_mechanism(ChannelBinding::Prefer, true, false, false).unwrap_err();
        assert!(err.to_string().contains("no supported SASL mechanisms"));
    }

    #[test]
    fn test_select_mechanism_disable_no_plain() {
        let err = select_mechanism(ChannelBinding::Disable, true, true, false).unwrap_err();
        assert!(err.to_string().contains("no supported SASL mechanisms"));
    }

    #[test]
    fn test_select_mechanism_prefer_no_tls_plus_only() {
        // Server only offers PLUS but client has no TLS — should fail
        let err = select_mechanism(ChannelBinding::Prefer, false, true, false).unwrap_err();
        assert!(err.to_string().contains("no supported SASL mechanisms"));
    }
}