diff --git a/CHANGELOG.md b/CHANGELOG.md index 01f45057a..a445ef38a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,14 +6,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] -### Security +## [2.2.7] - 2026-12-04 -- **Statements and portals after a failed batch**: Proxy now refuses a Bind, Describe or Execute that names a prepared statement or portal a failed batch would have changed, until PostgreSQL confirms a later change to it. - Proxy applied a Parse, Bind or Close when it read it, but PostgreSQL skips the rest of a batch after an error and keeps the statement or portal such a message would have replaced. - So after a batch failed before its `Close` or re-`Parse` of a statement, values bound to that statement could be sent to PostgreSQL without being encrypted, and rows could be returned without being decrypted, for every later use of that statement name. - Proxy also refuses such a message when it is sent before PostgreSQL has answered the batch that made the change. - The refusal uses PostgreSQL's `26000` error for a statement and `34000` for a portal, and the connection stays open; drivers that cache statements prepare them again on `26000`. - See [Unconfirmed prepared statement](docs/errors.md#mapping-unconfirmed-prepared-statement) and [Unconfirmed portal](docs/errors.md#mapping-unconfirmed-portal). +### Changed + +- **Database errors are no longer logged at `error` level**: When PostgreSQL returns an error, Proxy now logs only its SQLSTATE code, as `Database returned an error` at `debug` level on the `PROTOCOL` target. + Previously Proxy logged every database error at `error` level with all of its fields, followed by an `info` message. + Those fields can contain values from the statement, such as the input in an `invalid input syntax` error or the key in a unique violation, so they reached the logs at the default log level. + The client still receives the full error. + The `PROTOCOL` target at `debug` level also logs the raw protocol messages, which include statement values such as bound parameters, so use it only in local development. ### Fixed @@ -24,8 +25,26 @@ Previously it went down only when a connection ended with an error, so the value ### Security +- **Encryption Migrator escapes the values it writes**: The `migrate` command, which encrypts the existing rows of a table, now escapes each source value, the target column name and the table name in the `UPDATE` statements it sends. + Previously a source value was inserted into the statement unescaped, so a value containing a single quote, such as `O'Brien`, made the whole batch fail. + A value written to look like SQL, such as `x'; DELETE FROM users; --`, ran as SQL with the migrating database user's privileges. + Upgrade before running `migrate` on a column whose values come from users or other untrusted sources. + +- **Statements and portals after a failed batch**: Proxy now refuses a Bind, Describe or Execute that names a prepared statement or portal a failed batch would have changed, until PostgreSQL confirms a later change to it. + Proxy applied a Parse, Bind or Close when it read it, but PostgreSQL skips the rest of a batch after an error and keeps the statement or portal such a message would have replaced. + So after a batch failed before its `Close` or re-`Parse` of a statement, values bound to that statement could be sent to PostgreSQL without being encrypted, and rows could be returned without being decrypted, for every later use of that statement name. + Proxy also refuses such a message when it is sent before PostgreSQL has answered the batch that made the change. + The refusal uses PostgreSQL's `26000` error for a statement and `34000` for a portal, and the connection stays open; drivers that cache statements prepare them again on `26000`. + See [Unconfirmed prepared statement](docs/errors.md#mapping-unconfirmed-prepared-statement) and [Unconfirmed portal](docs/errors.md#mapping-unconfirmed-portal). + - **Dependency updates**: Updated `quinn-proto` to 0.11.19, `quinn-udp` to 0.5.16, `rkyv` to 0.7.46 and `url` to 2.5.9 (with `idna` 1.1.0, `percent-encoding` 2.3.2 and `form_urlencoded` 1.2.3), to pick up the fixes for published security advisories in those crates. No configuration change is required. +- **Advisories that do not affect Proxy**: Some dependency scanners report two advisories against Proxy 2.2.7 that do not affect it. + - `jsonwebtoken` 9.3.1 ([GHSA-h395-gr6q-cpjc](https://github.com/advisories/GHSA-h395-gr6q-cpjc), CVE-2026-25537): a claim with the wrong type can skip the `exp` and `nbf` checks. + Proxy uses `jsonwebtoken` only to read claims from access tokens it has already obtained, with signature and expiry checks turned off, and never uses it to decide access. + The fix is in `jsonwebtoken` 10.3, which requires a major upgrade of the CipherStash client library. + - `rkyv` 0.7 (RUSTSEC-2026-0235): `rkyv` is listed in `Cargo.lock` but is not compiled into Proxy. + ## [2.2.6] - 2026-11-19 ### Changed diff --git a/Cargo.lock b/Cargo.lock index f7d020011..7e85974c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -845,7 +845,7 @@ dependencies = [ [[package]] name = "cipherstash-proxy" -version = "2.2.6" +version = "2.2.7" dependencies = [ "arc-swap", "async-trait", @@ -1612,7 +1612,7 @@ dependencies = [ [[package]] name = "eql-mapper-macros" -version = "2.2.6" +version = "2.2.7" dependencies = [ "pretty_assertions", "proc-macro2", @@ -4478,7 +4478,7 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "showcase" -version = "2.2.6" +version = "2.2.7" dependencies = [ "rand 0.9.3", "rustls", diff --git a/Cargo.toml b/Cargo.toml index 13f886994..6a03ac840 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["packages/*"] exclude = ["vendor/stack-auth"] [workspace.package] -version = "2.2.6" +version = "2.2.7" edition = "2021" [profile.dev] diff --git a/packages/cipherstash-proxy/src/cli/migrate/mod.rs b/packages/cipherstash-proxy/src/cli/migrate/mod.rs index f82b50e21..78ed5febe 100644 --- a/packages/cipherstash-proxy/src/cli/migrate/mod.rs +++ b/packages/cipherstash-proxy/src/cli/migrate/mod.rs @@ -164,33 +164,12 @@ impl Migrate { row.get(source_col.as_str()).unwrap_or("").to_owned() }) .collect::>(); - // Set the col to update to the encrypted column - // And set the plaintext value to the p value - let update_str = self - .columns - .iter() - .zip(column_vals.iter()) - .map(|((_source_col, target_col), val)| { - format!("\"{target_col}\"='{val}'") - }) - .collect::>() - .join(", "); - - let where_str = self - .primary_key - .iter() - .zip(primary_key_vals.iter()) - .map(|(col, val)| { - let col = escape_identifier(col); - let val = escape_literal(val); - format!("{col}={val}") - }) - .collect::>() - .join(" AND "); - - let sql = format!( - "UPDATE {} SET {update_str} WHERE {where_str};\n", - self.table + let sql = build_update_statement( + &self.table, + &self.columns, + &column_vals, + &self.primary_key, + &primary_key_vals, ); updated_count += 1; @@ -238,6 +217,43 @@ impl Migrate { } } +/// +/// Build the UPDATE statement for one row. +/// Sets each target column to the row's source column value, matched by primary key. +/// +fn build_update_statement( + table: &str, + columns: &[(String, String)], + column_vals: &[String], + primary_key: &[String], + primary_key_vals: &[String], +) -> String { + let update_str = columns + .iter() + .zip(column_vals.iter()) + .map(|((_source_col, target_col), val)| { + let col = escape_identifier(target_col); + let val = escape_literal(val); + format!("{col}={val}") + }) + .collect::>() + .join(", "); + + let where_str = primary_key + .iter() + .zip(primary_key_vals.iter()) + .map(|(col, val)| { + let col = escape_identifier(col); + let val = escape_literal(val); + format!("{col}={val}") + }) + .collect::>() + .join(" AND "); + + let table = escape_identifier(table); + format!("UPDATE {table} SET {update_str} WHERE {where_str};\n") +} + /// Parse a single key-value pair - copied from clap example https://github.com/clap-rs/clap/blob/master/examples/typed-derive.rs#L25 fn parse_key_val(s: &str) -> Result<(T, U), Box> where @@ -290,3 +306,82 @@ pub async fn connect_with_no_tls(connection_string: &str) -> Result Vec<(String, String)> { + vec![("name".to_string(), "encrypted_name".to_string())] + } + + fn primary_key() -> Vec { + vec!["id".to_string()] + } + + #[test] + fn update_statement_escapes_quote_in_source_value() { + let sql = build_update_statement( + "users", + &columns(), + &["O'Brien".to_string()], + &primary_key(), + &["1".to_string()], + ); + + assert_eq!( + sql, + "UPDATE \"users\" SET \"encrypted_name\"='O''Brien' WHERE \"id\"='1';\n" + ); + } + + #[test] + fn update_statement_keeps_injected_sql_inside_the_literal() { + let sql = build_update_statement( + "users", + &columns(), + &["x'; DELETE FROM users; --".to_string()], + &primary_key(), + &["1".to_string()], + ); + + assert_eq!( + sql, + "UPDATE \"users\" SET \"encrypted_name\"='x''; DELETE FROM users; --' WHERE \"id\"='1';\n" + ); + } + + #[test] + fn update_statement_quotes_table_and_target_column() { + let columns = vec![("name".to_string(), "encrypted \"name\"".to_string())]; + + let sql = build_update_statement( + "user accounts", + &columns, + &["Alice".to_string()], + &primary_key(), + &["1".to_string()], + ); + + assert_eq!( + sql, + "UPDATE \"user accounts\" SET \"encrypted \"\"name\"\"\"='Alice' WHERE \"id\"='1';\n" + ); + } + + #[test] + fn update_statement_escapes_backslash_and_compound_primary_key() { + let sql = build_update_statement( + "users", + &columns(), + &["a\\b".to_string()], + &["id".to_string(), "user_id".to_string()], + &["1".to_string(), "O'x\\".to_string()], + ); + + assert_eq!( + sql, + "UPDATE \"users\" SET \"encrypted_name\"= E'a\\\\b' WHERE \"id\"='1' AND \"user_id\"= E'O''x\\\\';\n" + ); + } +} diff --git a/packages/cipherstash-proxy/src/postgresql/backend.rs b/packages/cipherstash-proxy/src/postgresql/backend.rs index 6207d7a0b..4d4f5c296 100644 --- a/packages/cipherstash-proxy/src/postgresql/backend.rs +++ b/packages/cipherstash-proxy/src/postgresql/backend.rs @@ -2,7 +2,7 @@ use super::context::Context; use super::data::to_sql; use super::error_handler::PostgreSqlErrorHandler; use super::message_buffer::MessageBuffer; -use super::messages::error_response::ErrorResponse; +use super::messages::error_response::{ErrorResponse, ErrorResponseCode}; use super::messages::row_description::RowDescription; use super::messages::BackendCode; use super::Column; @@ -25,7 +25,7 @@ use cipherstash_client::eql::EqlCiphertext; use metrics::{counter, histogram}; use std::time::Instant; use tokio::io::AsyncRead; -use tracing::{debug, error, info, warn}; +use tracing::{debug, error, warn}; /// The PostgreSQL proxy backend that handles server-to-client message processing. /// @@ -363,9 +363,10 @@ where /// /// # Logging and Monitoring /// - /// All errors are logged at ERROR level for debugging and recorded in - /// monitoring systems. This helps track both application-level issues - /// and proxy-specific problems. + /// A database error forwarded to the client is normal proxy operation, and + /// the client surfaces it, so only its SQLSTATE code is logged, at DEBUG + /// level. The message and other fields can contain values from the + /// statement, so they are never logged. /// /// # Returns /// @@ -373,8 +374,20 @@ where /// to forward to the client unchanged. fn error_response_handler(&mut self, bytes: &BytesMut) -> Result, Error> { let error_response = ErrorResponse::try_from(bytes)?; - error!(msg = "PostgreSQL Error", error = ?error_response); - info!(msg = "PostgreSQL Errors originate in the database"); + let field = |code: ErrorResponseCode| { + error_response + .fields + .iter() + .find(|field| field.code == code) + .map(|field| field.value.as_str()) + .unwrap_or_default() + }; + debug!( + target: PROTOCOL, + client_id = self.context.client_id, + msg = "Database returned an error", + code = field(ErrorResponseCode::Code), + ); Ok(Some(bytes.to_owned())) } @@ -1055,6 +1068,46 @@ mod tests { assert_eq!(backend.context.session_metrics_queue_len(), 0); } + /// The `Message` field of an ErrorResponse can carry a value from the statement, + /// such as the input in an `invalid input syntax` error. + /// The database error log must not write it, even at `debug` level. + #[test] + fn error_response_log_omits_values_from_the_message() { + use crate::test_helpers::MockMakeWriter; + + let make_writer = MockMakeWriter::default(); + let subscriber = tracing_subscriber::fmt() + .with_max_level(tracing::Level::DEBUG) + .with_ansi(false) + .with_writer(make_writer.clone()) + .finish(); + let _default = tracing::subscriber::set_default(subscriber); + + let (client_sender, _client_receiver) = mpsc::unbounded_channel(); + let reader = Cursor::new(Vec::new()); + let mut backend = Backend::new(client_sender, reader, passthrough_context()); + + let bytes = backend_message( + b'E', + b"SERROR\0C22P02\0Minvalid input syntax for type integer: \"123-45-678X\"\0\0", + ); + backend.error_response_handler(&bytes).unwrap(); + + let log_contents = make_writer.get_string(); + assert!( + log_contents.contains("Database returned an error"), + "database error was not logged: {log_contents}" + ); + assert!( + log_contents.contains("22P02"), + "SQLSTATE was not logged: {log_contents}" + ); + assert!( + !log_contents.contains("123-45-678X"), + "statement value was logged: {log_contents}" + ); + } + #[test] fn deallocation_command_tags() { assert!(super::is_deallocation(&command_complete("DEALLOCATE")));