Merge commit from fork

* fix(admin): bound IAM import archive expansion

MAX_IAM_IMPORT_SIZE caps the compressed upload at 10 MB, but every member of the
archive was then read with read_to_end into an unbounded Vec. Deflate ratios well
above 100:1 are easy to construct, so a small authorized upload could expand
without limit across the seven members ImportIam reads.

Add a shared expansion budget (MAX_IAM_IMPORT_EXPANDED_SIZE, 10x the compressed
cap) drawn down by every member, and route all seven reads through one helper
that reads a byte past the remaining budget to detect overrun. Sharing the budget
bounds the archive as a whole rather than letting each member spend the full
limit independently.

Covers R03-CAN-024 through R03-CAN-030 plus R04-CAN-077 (backlog #1471) — one
fix rather than seven, since all seven call sites were byte-identical.

* fix(kms): confine local key paths and refuse silent key replacement

Local KMS key identifiers arrive from request input — the `name` tag on CreateKey,
the `keyId` body field or query parameter on DeleteKey — and were joined onto
`key_dir` with no validation. An identifier such as `../../tmp/evil` escaped the
configured directory, making key creation a constrained arbitrary-file write and
`DeleteKey` with `force_immediate` a cross-directory delete.

Validate in `master_key_path` and make it fallible, so every filesystem path in
this backend inherits the guard: decode_stored_key, load_master_key,
save_master_key, create_key and delete_key all derive their paths there. The rule
is containment rather than a character allowlist, so identifiers already in use
keep resolving; only separators, NUL, absolute paths and non-single-component
forms are refused. Note `.` and `..` are contained rather than refused — the
`.key` suffix turns them into the ordinary filenames `..key` and `...key`.

Separately, `LocalKmsBackend::create_key` had no existence check, while the
sibling `KmsClient::create_key` has always had one. Since `save_master_key`
renames over its destination, creating a key under an existing name silently
replaced its material and destroyed the ability to decrypt everything wrapped
under it — and the backend path is the one the admin API uses. It now returns
KeyAlreadyExists, matching StaticKmsBackend.

Covers R03-CAN-072, R03-CAN-073 and R07-CAN-103 (backlog #1475). R03-CAN-073
needed no separate change: delete_key routes both its load and its remove_file
through master_key_path.

* fix(swift): bound SLO manifest reads to the 2 MiB manifest limit

The three Swift SLO handlers that load a stored manifest (handle_slo_get,
handle_slo_get_manifest, handle_slo_delete) read the `<object>.slo-manifest`
object to EOF with AsyncReadExt::read_to_end. That key is predictable and
writable through the ordinary object PUT path, so a tenant can replace the
manifest with an arbitrarily large object and then make the server allocate
its full size on every SLO GET, multipart-manifest=get, or
multipart-manifest=delete request - a memory amplification bounded only by
the stored object size (CWE-400 / CWE-770). The 2 MiB manifest limit that
handle_slo_put enforces was not applied on the read side.

Introduce MAX_SLO_MANIFEST_SIZE (the existing 2 MiB PUT limit, now a named
constant) and a shared read_manifest_bytes helper that reads through a
`take(limit + 1)` and rejects anything larger, so an oversized manifest is
refused instead of being buffered first. All three call sites go through the
helper. handle_slo_put now checks the size before parsing the JSON.

Regression tests: test_read_manifest_bytes_rejects_oversized_manifest and
test_read_manifest_bytes_stops_reading_oversized_manifest (which asserts the
reader is not consumed past the limit), plus a boundary test that a manifest
at exactly 2 MiB is still accepted.

* fix(protocols): authorize every object in FTPS/WebDAV recursive deletes

The FTPS and WebDAV gateways authorized only the container before a
recursive delete and then destroyed everything inside it without a
further check:

- FTPS RMD (and DELE on a bucket path ending in '/') cleared
  s3:DeleteBucket, then delete_bucket_recursively listed the bucket and
  deleted every object.
- WebDAV DELETE on a bucket did the same via its own
  delete_bucket_recursively.
- WebDAV DELETE on a directory cleared s3:DeleteObject for the directory
  marker key ("dir/") only, then listed that prefix and deleted every
  child under it.

A principal holding s3:DeleteBucket (or s3:DeleteObject on a single
marker key) could therefore erase objects it had no s3:DeleteObject
permission for, and the operation reported success.

Deletion stays recursive - that is the expected behaviour for these
protocols - but each object now clears s3:DeleteObject on its own key
before it is removed, and the enumeration clears s3:ListBucket. A denial
aborts the whole operation with access denied rather than being skipped,
so the caller can never be told the delete succeeded while objects were
left behind or removed without authorization.

The test double gained shared-state cloning, delete_object/delete_bucket
call logs, and list/delete queue helpers so the regression tests can
observe that nothing is deleted once a deny lands.

* fix(server,ecstore): bound TLS handshakes and remote volume RPC waits

Three call sites let an unauthenticated client or a misbehaving peer hold
server resources with no deadline.

TLS listener (R03-CAN-035): process_connection awaited
`acceptor.accept(socket)` with no bound. A client that opens a TCP
connection and never finishes the handshake parks a Tokio task and a socket
forever, and the connection cap (RUSTFS_API_MAX_CONNECTIONS) is unlimited by
default, so nothing else sheds it. The handshake now runs under
accept_tls_with_deadline(), reusing the existing HTTP/1 header-read budget —
the established slow-client bound for the pre-request phase — and the
expiry is recorded through the same log/metric path as a handshake error,
under a new TIMEOUT failure kind.

Remote disk RPCs (R03-CAN-049, R03-CAN-050): list_volumes and delete_volume
passed Duration::ZERO, which execute_with_timeout treats as "no deadline",
so a peer that accepts the request and never answers stalls the coordinator
(and, for delete_volume, the bucket-deletion workflow). Both now pass
get_max_timeout_duration(), matching every sibling method in the file.

Regression tests: a silent TLS peer must be shed by the handshake deadline;
list_volumes/delete_volume against a peer that completes the TCP connect and
then goes silent must fail with DiskError::Timeout instead of hanging.

* fix(security): stop leaking signed headers and bound OIDC/KMS credentials

Three independent hygiene fixes found by the security review.

R03-CAN-018 (crates/signer): try_get_canonical_headers and get_signed_headers
logged the complete header map at DEBUG before signing. Runtime callers pass
session credentials and SSE-C key material through these headers, so anyone
able to raise the log level (or read DEBUG logs) recovered
X-Amz-Security-Token and SSE-C keys verbatim. The statements were debugging
leftovers with no operational value and are deleted rather than redacted.

R03-CAN-014 (crates/iam): the OIDC HTTP adapter buffered provider responses
with an unbounded Response::bytes(), so a configured, compromised or
attacker-pointed IdP endpoint could stream an arbitrarily large or endless
body into memory (the ValidateOidcConfig admin handler lets a ServerInfo
caller choose the endpoint). Responses are now read incrementally and fail
closed past MAX_OIDC_RESPONSE_SIZE, and the already SSRF-hardened client
builder gains request and connect timeouts so a stalled provider cannot pin
the calling task indefinitely.

R07-CAN-105 (helm): the Vault KMS token was serialized into the chart
ConfigMap, exposing it to every subject allowed to get ConfigMaps in the
namespace. It now renders into a dedicated Secret that the Deployment and
StatefulSet consume via envFrom; the Secret is separate from the main
credentials Secret so it also works when secret.existingSecret is set.

Regression tests:
- rustfs-signer: signing_never_logs_signed_header_material
- rustfs-iam: oidc_response_body_past_the_limit_is_rejected,
  oidc_response_body_at_the_limit_is_accepted
- scripts/test_helm_templates.sh: KMS token must never render in plaintext

* fix(webdav): enforce body limit, request timeout and connection cap

The configured WebDAV maximum body size was enforced from Content-Length, so a
chunked request declared no length and bypassed it entirely. The configured
request timeout was never applied to the connection at all, and the accept loop
spawned a task per connection with no bound, so an unauthenticated client could
hold resources indefinitely and in unbounded number.

Enforce the limit on bytes actually read rather than the declared length, apply
the configured timeout to the request, and bound accepted connections with a new
RUSTFS_WEBDAV_MAX_CONNECTIONS (default 1024) surfaced in the config report.

Covers R03-CAN-051, R03-CAN-052, R03-CAN-067, R04-CAN-089, R05-CAN-094 and
R05-CAN-097 (backlog #1471, #1474).

* fix(security): stop STS credentials from crossing the parent trust boundary

Two related credential-boundary holes let a short-lived STS credential act
with the full, unrestricted authority of the long-term user it was minted
from.

AddUser (R03-CAN-021, CWE-269/863): should_check_deny_only relaxes the admin
policy check to deny-only when a Console/STS session targets the IAM user it
represents. Nothing then stopped that session from calling AddUser with its
own parent's access key, so the handler wrote an attacker-chosen secret key
and status over the parent's stored Credentials via create_user ->
save_user_identity. A session that expires in minutes became permanent
control of the account. AddUser now rejects any temp or service-account
requester whose resolved parent equals the target access key, resolving the
parent the same way should_check_deny_only does (parent_user field, else the
JWT `parent` claim, since some stores persist the parent only in the token).

FTPS/SFTP/WebDAV password auth (R04-CAN-086, CWE-287/862): these protocols
looked the access key up with check_key, which falls back to the STS account
cache, and then compared only the stored secret. An STS access key plus
secret therefore authenticated with no session token presented and no
session-policy claims applied - the holder got the parent's full permissions.
Password authentication now rejects temporary credentials before the secret
comparison. The discriminator is is_temp() && !is_service_account(), the same
one IamCache::update_user_with_claims uses to route an identity into the STS
cache, so service accounts - which resolve policy from stored IAM state
rather than a client-presented token - keep working over these protocols.

Regression tests cover both predicates and pin the guards to their call
sites so neither can be dropped without a test failure.
This commit is contained in:
Zhengchao An
2026-07-27 00:22:50 +08:00
committed by GitHub
parent 887868e7cd
commit b2a376c2d2
32 changed files with 1924 additions and 187 deletions
+159 -12
View File
@@ -32,12 +32,41 @@ use rand::RngExt;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::PathBuf;
use std::path::{Component, Path, PathBuf};
use std::time::Duration;
use tokio::fs;
use tokio::sync::RwLock;
use tracing::{debug, warn};
/// Reject key identifiers that would not name a single file directly inside the key
/// directory.
///
/// The rule is containment, not a character allowlist: anything that stays inside
/// `key_dir` is accepted, so identifiers already in use by existing deployments keep
/// resolving. Only separators, traversal and the degenerate cases are refused, which is
/// what stops `key_dir.join(...)` from escaping.
fn validate_key_id(key_id: &str) -> Result<()> {
if key_id.is_empty() {
return Err(KmsError::invalid_key("key identifier must not be empty"));
}
if key_id.contains('/') || key_id.contains('\\') || key_id.contains('\0') {
return Err(KmsError::invalid_key(format!(
"key identifier must not contain path separators or NUL: {key_id:?}"
)));
}
// Catches `.`, `..`, absolute paths, and platform-specific forms such as Windows
// drive prefixes, all of which would move the join outside key_dir.
let file_name = format!("{key_id}.key");
let mut components = Path::new(&file_name).components();
match (components.next(), components.next()) {
(Some(Component::Normal(_)), None) => Ok(()),
_ => Err(KmsError::invalid_key(format!(
"key identifier must name a single file inside the key directory: {key_id:?}"
))),
}
}
const LOCAL_KMS_MASTER_KEY_SALT_FILE: &str = ".master-key.salt";
const LOCAL_KMS_MASTER_KEY_SALT_LEN: usize = 16;
const LOCAL_KMS_MASTER_KEY_LEN: usize = 32;
@@ -187,14 +216,26 @@ impl LocalKmsClient {
Ok(())
}
/// Get the file path for a master key
fn master_key_path(&self, key_id: &str) -> PathBuf {
self.config.key_dir.join(format!("{key_id}.key"))
/// Get the file path for a master key.
///
/// Key identifiers reach this from request input (the `name` tag on CreateKey, the
/// `keyId` body field or query parameter on DeleteKey), so they are joined onto
/// `key_dir` only after being confirmed to name a single file inside it. Without that
/// check an identifier such as `../../tmp/evil` escapes the configured key directory,
/// turning key creation into a constrained arbitrary-file write and key deletion into
/// a cross-directory delete.
///
/// Every filesystem path in this backend is derived here, so validating at this one
/// point covers `decode_stored_key`, `load_master_key`, `save_master_key`, `create_key`
/// and `delete_key`.
fn master_key_path(&self, key_id: &str) -> Result<PathBuf> {
validate_key_id(key_id)?;
Ok(self.config.key_dir.join(format!("{key_id}.key")))
}
/// Decode and decrypt a stored key file, returning both the metadata and decrypted key material
async fn decode_stored_key(&self, key_id: &str) -> Result<(StoredMasterKey, Vec<u8>)> {
let key_path = self.master_key_path(key_id);
let key_path = self.master_key_path(key_id)?;
if !fs::try_exists(&key_path).await? {
return Err(KmsError::key_not_found(key_id));
}
@@ -284,7 +325,7 @@ impl LocalKmsClient {
/// Save a master key to disk
async fn save_master_key(&self, master_key: &MasterKeyInfo, key_material: &[u8]) -> Result<()> {
let key_path = self.master_key_path(&master_key.key_id);
let key_path = self.master_key_path(&master_key.key_id)?;
// Encrypt key material if master cipher is available
let (encrypted_key_material, nonce, at_rest_protection) = if let Some(ref cipher) = self.master_cipher {
@@ -453,7 +494,7 @@ impl KmsClient for LocalKmsClient {
debug!("Creating master key: {}", key_id);
// Check if key already exists
if self.master_key_path(key_id).exists() {
if self.master_key_path(key_id)?.exists() {
return Err(KmsError::key_already_exists(key_id));
}
@@ -704,6 +745,15 @@ impl KmsBackend for LocalKmsBackend {
async fn create_key(&self, request: CreateKeyRequest) -> Result<CreateKeyResponse> {
let key_id = request.key_name.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
// `save_master_key` writes through a temp file and renames over the destination, so
// creating a key under an existing name would replace its material and silently
// destroy the ability to decrypt everything wrapped under it. The sibling
// `KmsClient::create_key` has always refused this; the backend path did not, and
// this is the path the admin API uses.
if self.client.master_key_path(&key_id)?.exists() {
return Err(KmsError::key_already_exists(&key_id));
}
// Create master key with description directly
let _master_key = {
let algorithm = "AES_256";
@@ -833,7 +883,7 @@ impl KmsBackend for LocalKmsBackend {
let (deletion_date_str, deletion_date_dt) = if request.force_immediate.unwrap_or(false) {
// For immediate deletion, actually delete the key from filesystem
let key_path = self.client.master_key_path(key_id);
let key_path = self.client.master_key_path(key_id)?;
tokio::fs::remove_file(&key_path)
.await
.map_err(|e| KmsError::internal_error(format!("Failed to delete key file: {e}")))?;
@@ -1132,7 +1182,7 @@ mod tests {
assert_eq!(salt.len(), LOCAL_KMS_MASTER_KEY_SALT_LEN);
let stored: StoredMasterKey = serde_json::from_slice(
&fs::read(client.master_key_path("encrypted-key"))
&fs::read(client.master_key_path("encrypted-key").expect("valid key id"))
.await
.expect("stored key should exist"),
)
@@ -1150,7 +1200,7 @@ mod tests {
.expect("Failed to create plaintext-dev-only key");
let stored: StoredMasterKey = serde_json::from_slice(
&fs::read(client.master_key_path("plaintext-key"))
&fs::read(client.master_key_path("plaintext-key").expect("valid key id"))
.await
.expect("stored key should exist"),
)
@@ -1208,7 +1258,7 @@ mod tests {
"nonce": Vec::<u8>::new()
});
let key_path = client.master_key_path("legacy-key");
let key_path = client.master_key_path("legacy-key").expect("valid key id");
fs::write(&key_path, serde_json::to_vec_pretty(&stored_key).expect("serialize test key"))
.await
.expect("write legacy key");
@@ -1226,7 +1276,7 @@ mod tests {
.await
.expect("Failed to create encrypted key");
let key_path = client.master_key_path("legacy-encrypted-key");
let key_path = client.master_key_path("legacy-encrypted-key").expect("valid key id");
let mut stored_json: serde_json::Value =
serde_json::from_slice(&fs::read(&key_path).await.expect("stored key should exist"))
.expect("stored key should deserialize");
@@ -1322,4 +1372,101 @@ mod tests {
.expect_err("wrong beta.5 master key must not decrypt the fixture");
assert!(matches!(error, KmsError::CryptographicError { .. }));
}
/// R03-CAN-072 / R03-CAN-073: key identifiers arrive from request input, so every path
/// derived from one must stay inside the configured key directory. Traversal here would
/// turn CreateKey into a constrained arbitrary-file write and DeleteKey into a
/// cross-directory delete.
#[tokio::test]
async fn master_key_path_confines_key_ids_to_the_key_directory() {
let (client, temp_dir) = create_test_client().await;
// The invariant is containment, so assert that directly: whatever the input, the
// result is either refused or a path whose parent is exactly the key directory.
// Note `.` and `..` are contained rather than refused — the `.key` suffix turns
// them into the ordinary filenames `..key` and `...key`.
for candidate in [
"../escape",
"../../etc/rustfs",
"sub/dir",
"..",
".",
"",
"/absolute",
"back\\slash",
"nul\0byte",
"....//....//escape",
] {
match client.master_key_path(candidate) {
Err(KmsError::InvalidKey { .. }) => {}
Err(other) => panic!("unexpected error kind for {candidate:?}: {other:?}"),
Ok(path) => assert_eq!(
path.parent(),
Some(temp_dir.path()),
"{candidate:?} was accepted but escapes the key directory: {path:?}"
),
}
}
// The traversal forms specifically must be refused, not merely contained.
for escaping in ["../escape", "sub/dir", "/absolute", "back\\slash", "nul\0byte", ""] {
let err = client.master_key_path(escaping).expect_err("traversal must be refused");
assert!(
matches!(err, KmsError::InvalidKey { .. }),
"expected InvalidKey for {escaping:?}, got {err:?}"
);
}
// Ordinary identifiers, including the UUID form used when no name is supplied,
// must still resolve — and must land directly in the key directory.
for ok in ["test-key", "a.b_c-1", "3f2504e0-4f89-11d3-9a0c-0305e82c3301"] {
let path = client.master_key_path(ok).expect("valid key id must be accepted");
assert_eq!(
path.parent(),
Some(temp_dir.path()),
"{ok:?} must resolve directly inside the key directory"
);
}
}
/// R07-CAN-103: `save_master_key` writes a temp file and renames over the destination,
/// so creating a key under an existing name would replace its material and silently
/// destroy the ability to decrypt anything wrapped under it.
#[tokio::test]
async fn backend_create_key_refuses_to_replace_existing_key_material() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let client = LocalKmsClient::new(LocalConfig {
key_dir: temp_dir.path().to_path_buf(),
master_key: Some("test-master-key".to_string()),
file_permissions: Some(0o600),
})
.await
.expect("Failed to create client");
let backend = LocalKmsBackend { client };
let request = || CreateKeyRequest {
key_name: Some("duplicate-key".to_string()),
..Default::default()
};
backend.create_key(request()).await.expect("first create must succeed");
let original = backend
.client
.get_key_material("duplicate-key")
.await
.expect("key material must be readable after creation");
let err = backend
.create_key(request())
.await
.expect_err("creating a key under an existing name must be refused");
assert!(matches!(err, KmsError::KeyAlreadyExists { .. }), "expected KeyAlreadyExists, got {err:?}");
let after = backend
.client
.get_key_material("duplicate-key")
.await
.expect("original key material must survive the refused create");
assert_eq!(original, after, "existing key material must not be replaced");
}
}