use std::fmt::Display; use std::time::Duration; use base64::prelude::*; use log::{debug, error, warn}; use mini_moka::sync::Cache; use once_cell::sync::Lazy; use crate::utils::postgres::{compute_client_proof, compute_server_signature}; #[derive(Debug, Default, Clone)] struct AuthenticationData { client_final_without_proof: String, client_first_bare: String, combined_nonce: String, iterations: u32, provided_password: String, provided_username: String, salt: String, server_first: String, } static NONCE_SALTS: Lazy> = Lazy::new(|| { Cache::builder() .time_to_live(Duration::from_secs(30 * 60)) .build() }); pub struct PostgresMsg<'pm> { /// Type of messsage between frontend & backend postgres. pub msg_type: PostgresMessageType, /// Original bytes array. pub bytes: &'pm [u8], /// Modified bytes vector. pub changed_bytes: Option>, } impl<'def> Default for PostgresMsg<'def> { fn default() -> Self { PostgresMsg { msg_type: PostgresMessageType::NotRecognized, bytes: &[], changed_bytes: None, } } } impl<'m> PostgresMsg<'m> { fn new(msg_type: PostgresMessageType, bytes: &'m [u8]) -> PostgresMsg<'m> { PostgresMsg { msg_type, bytes, ..Default::default() } } fn new_transformed( msg_type: PostgresMessageType, bytes: &'m [u8], changed_bytes: Vec, ) -> PostgresMsg<'m> { PostgresMsg { msg_type, bytes, changed_bytes: Some(changed_bytes), } } fn not_recognised<'nr>(bytes: &'nr [u8]) -> PostgresMsg<'nr> { PostgresMsg::new(PostgresMessageType::NotRecognized, bytes) } /// Parse key-value pairs from the startup message (order is not guaranteed) fn get_all_params(startup_elements: Vec<&str>) -> Vec<(&str, &str)> { let mut params: Vec<(&str, &str)> = Vec::new(); let mut i = 0; while i + 1 < startup_elements.len() { let key = startup_elements[i]; let value = startup_elements[i + 1]; if key.is_empty() { break; } params.push((key, value)); i += 2; } params } fn find_param(name: &str, params: &Vec<(&str, &str)>) -> String { params .iter() .find(|(k, _)| *k == name) .map(|(_, v)| v.to_string()) .unwrap_or_default() } /// First message from client to the server with user name / database. fn startup_message(bytes: &'m [u8]) -> Result { let length_of_message = as_u32_be(&bytes[0..4]) as usize; let startup_message = String::from_utf8(bytes[8..length_of_message].to_vec()).unwrap(); // TODO: handle let startup_elements: Vec<&str> = startup_message.split("\0").collect(); // Parse key-value pairs from the startup message (order is not guaranteed) let params: Vec<(&str, &str)> = Self::get_all_params(startup_elements); let user = "sammy".to_string(); let database = "sammydb".to_string(); let application_name = Self::find_param("application_name", ¶ms); let client_encoding = Self::find_param("client_encoding", ¶ms); // Rebuild the startup message, replacing user/database but keeping all other params let mut changed_bytes = String::new(); for (key, value) in ¶ms { let new_value: &str = match *key { "user" => &user, "database" => &database, _ => value, }; changed_bytes.push_str(key); changed_bytes.push('\0'); changed_bytes.push_str(new_value); changed_bytes.push('\0'); } changed_bytes.push('\0'); // double-null terminator let bytes_sent = changed_bytes.as_bytes().to_owned(); let new_length = (bytes_sent.len() + 8) as u32; // include the length of the length field and protocol version // TODO: get protocol version from db let protocol_version = 0x00030000u32.to_be_bytes(); // Protocol version 3.0 let modified_bytes = [ &new_length.to_be_bytes(), &protocol_version, &bytes_sent[..], ] .concat(); Ok(PostgresMsg::new_transformed( PostgresMessageType::StartupMessage { user, database, application_name, client_encoding, }, bytes, modified_bytes, )) } /// Takes a string like `r=123456` and returns just the value (a common pattern in postgres). fn extract_value(input: &str) -> String { input.splitn(2, "=").collect::>()[1].to_string() } fn find_auth_data_with_combined(combined_nonce: String) -> (String, AuthenticationData) { let salt_matches: Vec<(String, AuthenticationData)> = NONCE_SALTS .into_iter() .filter(|entry| combined_nonce.starts_with(entry.key())) .map(|entry| { let (key, value) = entry.pair(); (key.clone(), value.clone()) }) .collect(); if salt_matches.len() != 1 { panic!("Could not find matching nonce in cache!"); } let (client_nonce, auth_data) = salt_matches[0].clone(); if !auth_data.combined_nonce.is_empty() && auth_data.combined_nonce != combined_nonce { panic!("Combined nonce does not match"); } debug!("Found AuthenticationData: {:?}", auth_data); (client_nonce, auth_data) } /// Client final message, SASLResponse, the password proof gets changed here. /// Input looks like: /// c=biws,r=9iXBuitB4pPvx9/9N34EEBb/3C1/DJ33YLddJFxkI8MLrPW7,p=GIdr6Yoh1pqFjMEKV431AC+3d96HURztJ0L8802MIoM= /// c -> channel_binding /// r -> combined_nonce /// p -> client_proof fn client_final_message(input: String) -> String { let split: Vec<&str> = input.splitn(3, ",").collect(); let combined_nonce = Self::extract_value(split[1]); let (client_nonce, mut auth_data) = Self::find_auth_data_with_combined(combined_nonce.clone()); // TODO: get password to database dynamically from some sort of gateway app let password = "sammypassword"; let client_final_without_proof = format!("c=biws,r={}", combined_nonce); let client_first_bare = format!("n={},r={}", auth_data.provided_username, client_nonce); let server_first = format!( "r={},s={},i={}", combined_nonce, auth_data.salt, auth_data.iterations ); auth_data.client_final_without_proof = client_final_without_proof; auth_data.client_first_bare = client_first_bare; auth_data.server_first = server_first; NONCE_SALTS.insert(client_nonce, auth_data.clone()); debug!("FINAL AuthenticationData == {:?}", &auth_data); let client_proof = compute_client_proof( password, &BASE64_STANDARD.decode(auth_data.salt).unwrap(), auth_data.iterations, auth_data.client_first_bare.as_str(), auth_data.server_first.as_str(), auth_data.client_final_without_proof.as_str(), ); format!("c=biws,r={},p={}", combined_nonce, client_proof) } /// Server final message, AuthenticationSASLFinal. fn server_final_message() -> String { let all_nonces: Vec<(String, AuthenticationData)> = NONCE_SALTS .iter() .map(|e| { let (n, a) = e.pair(); (n.clone(), a.clone()) }) .collect(); if all_nonces.len() != 1 { NONCE_SALTS.invalidate_all(); panic!("more than once found (or less?!)") } let (client_nonce, auth_data) = all_nonces[0].clone(); // no longer needed NONCE_SALTS.invalidate(&client_nonce); // TODO: figure this out // TODO: get provided password dynamically from some sort of gateway app let provided_password = "password"; let server_proof = compute_server_signature( provided_password, &BASE64_STANDARD.decode(auth_data.salt).unwrap(), auth_data.iterations, auth_data.client_first_bare.as_str(), auth_data.server_first.as_str(), auth_data.client_final_without_proof.as_str(), ); format!("v={}", server_proof) } fn set_initial_auth_data(client_nonce: String, username: String) { NONCE_SALTS.insert( client_nonce, AuthenticationData { provided_username: username, provided_password: "somethingMadeUpToRemove".to_string(), ..Default::default() }, ); } // TODO: Only supports SAML currently /// When the first byte is 'p'. fn password_response_message(bytes: &'m [u8]) -> Result { let length_of_message = as_u32_be(&bytes[1..5]) as usize; let possible_msg_contents = String::from_utf8(bytes[5..length_of_message + 1].to_vec()).unwrap(); if possible_msg_contents.starts_with("SCRAM-SHA-256") { // client first message after SCRAM-SHA-256<-PLUS> with client_first_message debug!("SASLInitialResponse == {:?}", possible_msg_contents); if possible_msg_contents.contains("SCRAM-SHA-256-PLUS") { // pretty sure dam can never work with channel binding warn!("Server is requesting channel binding (SCRAM-SHA-256-PLUS)"); } else { debug!("Server is NOT requesting channel binding (SCRAM-SHA-256-PLUS)"); } let initial_parts = possible_msg_contents.splitn(4, ",").collect::>(); // the username part "n=" (before extraction here), can be empty string let username = Self::extract_value(initial_parts[2]); // the client nonce part "r=" before extraction let client_nonce_part = Self::extract_value(initial_parts[3]); Self::set_initial_auth_data(client_nonce_part, username); Ok(PostgresMsg::new( PostgresMessageType::SASLInitialResponse, bytes, )) } else { // final SASL message from client with client_final_message where // we replace the client proof of the postgres db password with // the new real one debug!("SASLResponse == {:?}", possible_msg_contents); let client_final_message = Self::client_final_message(possible_msg_contents); debug!("client_final_message == {}", client_final_message); let bytes_sent = client_final_message.as_bytes().to_owned(); let new_length = (bytes_sent.len() + 4) as u32; // length includes itself, not the type byte let mut modified_bytes = Vec::with_capacity(1 + 4 + bytes_sent.len()); modified_bytes.push(b'p'); modified_bytes.extend_from_slice(&new_length.to_be_bytes()); modified_bytes.extend_from_slice(&bytes_sent); Ok(PostgresMsg::new_transformed( PostgresMessageType::SASLResponse, bytes, modified_bytes, )) } } /// Parses the message from postgres with nonce, salt, and iterations needed /// to calculate client proof later on. Uses an in-memory TTL cache to store the salt /// for later on. fn parse_sasl_continue_msg(input: String) -> PostgresMessageType { let split: Vec<&str> = input.splitn(3, ",").collect(); let combined_nonce = Self::extract_value(split[0]); let salt = Self::extract_value(split[1]); let raw_iters_str = split[2].splitn(2, "=").collect::>()[1]; let iterations = match raw_iters_str.parse::() { Ok(n) => n, Err(e) => { error!("ParseIntError for {}: {}", raw_iters_str, e); panic!(); } }; let (client_nonce, mut auth_data) = Self::find_auth_data_with_combined(combined_nonce.clone()); auth_data.combined_nonce = combined_nonce; auth_data.salt = salt.clone(); auth_data.iterations = iterations; NONCE_SALTS.insert(client_nonce.clone(), auth_data); PostgresMessageType::AuthenticationSASLContinue { nonce: client_nonce, salt, iterations, } } /// When the first byte is 'R' it's related to authentication and handled here. fn authentication_message(bytes: &'m [u8]) -> Result { let b = as_u32_be(&bytes[1..5]) as usize; let c = as_u32_be(&bytes[5..9]); match c { 10 => { // first msg from backend confirming SCRAM-SHA-256 or SCRAM-SHA-256-PLUS Ok(PostgresMsg::new( PostgresMessageType::AuthenticationSASL, bytes, )) } 11 => { // backend 2nd message with server_first_message // contains nonce, salt, and iteration count let possible_msg_contents = String::from_utf8(bytes[9..].to_vec()).unwrap(); debug!("AuthenticationSASLContinue == {possible_msg_contents}"); Ok(PostgresMsg::new( Self::parse_sasl_continue_msg(possible_msg_contents), bytes, )) } 12 => { // backend 3rd message with server signature let msg_len = as_u32_be(&bytes[1..5]) as usize; // message length including itself let payload = &bytes[9..(1 + msg_len)]; let possible_msg_contents = String::from_utf8(payload.to_vec()).unwrap(); let end_of_stream = &bytes[9 + payload.len()..]; debug!("end_of_stream == {:?}", end_of_stream); print_postgres_messages(end_of_stream); debug!("AuthenticationSASLFinal == {possible_msg_contents}"); let server_final_message = Self::server_final_message(); let bytes_sent = server_final_message.as_bytes().to_owned(); let new_length = (bytes_sent.len() + 8) as u32; // length includes itself (4) + auth type (4), not the type byte let mut modified_bytes = Vec::with_capacity(1 + 4 + 4 + bytes_sent.len()); modified_bytes.push(b'R'); modified_bytes.extend_from_slice(&new_length.to_be_bytes()); modified_bytes.extend_from_slice(&12u32.to_be_bytes()); modified_bytes.extend_from_slice(&bytes_sent); modified_bytes.extend_from_slice(end_of_stream); Ok(PostgresMsg::new_transformed( PostgresMessageType::AuthenticationSASLFinal, bytes, modified_bytes, )) } _ => match b { 8 if c == 0 => Ok(PostgresMsg::new( PostgresMessageType::AuthenticationOk, bytes, )), 8 if c == 2 => Ok(PostgresMsg::new( PostgresMessageType::AuthenticationKerberosV5, bytes, )), 8 if c == 3 => Ok(PostgresMsg::new( PostgresMessageType::AuthenticationCleartextPassword, bytes, )), 12 if c == 5 => Ok(PostgresMsg::new( PostgresMessageType::AuthenticationMD5Password, bytes, )), _ => Ok(PostgresMsg::not_recognised(bytes)), }, } } } impl<'tf> TryFrom<&'tf [u8]> for PostgresMsg<'tf> { type Error = Self; fn try_from(bytes: &'tf [u8]) -> Result { if bytes.is_empty() { return Ok(PostgresMsg { msg_type: PostgresMessageType::Empty, bytes, ..Default::default() }); } // startup message if bytes.len() >= 8 && as_u32_be(&bytes[4..8]) == 196608 { return Self::startup_message(bytes); } match bytes[0] as char { 'p' => Self::password_response_message(bytes), 'R' => Self::authentication_message(bytes), _ => Ok(PostgresMsg::not_recognised(bytes)), } } } impl<'d> Display for PostgresMsg<'d> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Postgres Message Type is {:?}", self.msg_type) } } #[derive(Debug)] pub(crate) enum PostgresMessageType { AuthenticationOk, AuthenticationKerberosV5, AuthenticationCleartextPassword, AuthenticationMD5Password, // AuthenticationGSS, // AuthenticationGSSContinue, // AuthenticationSSPI, AuthenticationSASL, AuthenticationSASLContinue { nonce: String, salt: String, iterations: u32, }, AuthenticationSASLFinal, // Bind, // BindComplete, // CancelRequest, Empty, SASLInitialResponse, SASLResponse, StartupMessage { user: String, database: String, application_name: String, client_encoding: String, }, // SSLRequest, NotRecognized, } fn as_u32_be(array: &[u8]) -> u32 { ((array[0] as u32) << 24) + ((array[1] as u32) << 16) + ((array[2] as u32) << 8) + (array[3] as u32) } impl Display for PostgresMessageType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Postgres Message Type is {:?}", self) } } fn print_postgres_messages(bytes: &[u8]) { let mut i = 0; while i + 5 <= bytes.len() { let msg_type = bytes[i] as char; let len = ((bytes[i + 1] as u32) << 24) | ((bytes[i + 2] as u32) << 16) | ((bytes[i + 3] as u32) << 8) | (bytes[i + 4] as u32); println!("Type: {}, Length: {}", msg_type, len); if i + (len as usize) > bytes.len() { println!("(truncated or incomplete message)"); break; } let payload = &bytes[i + 5..i + len as usize]; if msg_type == 'S' { // Decode two null-terminated strings let mut parts = payload.split(|b| *b == 0); let param_name = parts .next() .and_then(|s| std::str::from_utf8(s).ok()) .unwrap_or(""); let param_value = parts .next() .and_then(|s| std::str::from_utf8(s).ok()) .unwrap_or(""); println!(" ParameterStatus: {} = {}", param_name, param_value); } else if msg_type == 'K' { // Decode BackendKeyData if payload.len() >= 8 { let pid = ((payload[0] as u32) << 24) | ((payload[1] as u32) << 16) | ((payload[2] as u32) << 8) | (payload[3] as u32); let secret_key = &payload[4..]; println!( " BackendKeyData: pid = {}, secret_key = {:?}", pid, secret_key ); } else { println!(" BackendKeyData: payload too short!"); } } // Optionally print payload as hex or string for other types // println!("Payload: {:?}", payload); i += 1 + len as usize; } if i < bytes.len() { println!("Remaining bytes: {:?}", &bytes[i..]); } } #[cfg(test)] mod tests { use super::*; #[test] fn parse_nonce_salt_iterations_correctly() { let input = "r=4f0wpBSrg2BVAYxW1A3gyfDNH8Iq+S6F8l6XoMvcFvyqClAE,s=aEAaprWGne9ObVLE9LBMUw==,i=4096" .to_string(); let output = PostgresMsg::parse_sasl_continue_msg(input); match output { PostgresMessageType::AuthenticationSASLContinue { nonce, salt, iterations, } => { assert_eq!( nonce, "4f0wpBSrg2BVAYxW1A3gyfDNH8Iq+S6F8l6XoMvcFvyqClAE".to_string() ); assert_eq!(iterations, 4096); } _ => unreachable!(), } } }