Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
70 changes: 68 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

110 changes: 107 additions & 3 deletions cli/src/command/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use pna::{
};
use std::{
borrow::Cow,
collections::HashMap,
fmt, fs,
io::{self, prelude::*},
path::{Path, PathBuf},
Expand Down Expand Up @@ -1894,7 +1895,10 @@ pub(crate) fn apply_chroot(chroot: bool) -> anyhow::Result<()> {
/// if a password is provided; without a password they will cause an error.
///
/// The entry data (FDAT chunks) is preserved as-is, maintaining the original
/// compression and encryption. Only the entry headers (paths, ownership) are modified.
/// compression and encryption. Only the entry headers (paths, ownership) are
/// modified. The exception is renaming a cipher mode 2 (GCM) entry, whose data
/// is bound to the header bytes: it is decrypted and re-encrypted under the new
/// name using the provided password, and refused when no password is available.
///
/// Entries whose path matches the filter exclusion rules will be skipped.
/// Time filters are also applied to filter entries by timestamps.
Expand All @@ -1907,6 +1911,7 @@ pub(crate) fn transform_archive_entries<R: io::Read>(
allow_concatenated_archives: bool,
) -> io::Result<Vec<io::Result<Option<NormalEntry>>>> {
let mut results = Vec::new();
let mut reencrypt_options = HashMap::new();
let read_options = ReadOptions::with_password(password);
run_process_archive(
std::iter::once(reader),
Expand All @@ -1921,7 +1926,12 @@ pub(crate) fn transform_archive_entries<R: io::Read>(
if !time_filters.matches(ctime, mtime) {
return Ok(());
}
results.push(transform_normal_entry(entry, create_options));
results.push(transform_normal_entry(
entry,
create_options,
password,
&mut reencrypt_options,
));
Ok(())
},
allow_concatenated_archives,
Expand Down Expand Up @@ -2052,6 +2062,8 @@ fn transform_normal_entry(
keep_options,
..
}: &CreateOptions,
password: Option<&[u8]>,
reencrypt_options: &mut ReencryptOptionsCache,
) -> io::Result<Option<NormalEntry>> {
// Apply path transformation
let original_name = entry.header().path();
Expand All @@ -2060,7 +2072,29 @@ fn transform_normal_entry(
return Ok(None);
};

let mut result = entry.with_name(new_name);
let mut result = if new_name == *entry.name() {
// Keep the raw header bytes on a no-op rename: re-serializing the
// header would break cipher mode 2 (GCM) entries written by tools
// whose serialization differs from ours.
entry
} else if entry.encryption() != pna::Encryption::NO
&& entry.cipher_mode() == pna::CipherMode::GCM
{
// The GCM stream key is bound to the header bytes, so a renamed entry
// is only readable if it is decrypted and re-encrypted under the new
// name.
let Some(password) = password else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"cannot rename encrypted entry {original_name}: renaming a cipher mode 2 (GCM) entry requires the password to re-encrypt it"
),
));
};
re_encrypt_entry_with_name(&entry, new_name, password, reencrypt_options)?
} else {
entry.with_name(new_name)
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.

let mut metadata = result.metadata().clone();
match keep_options.timestamp_strategy {
Expand Down Expand Up @@ -2136,6 +2170,47 @@ fn transform_normal_entry(
Ok(Some(result))
}

type ReencryptOptionsKey = (pna::Compression, pna::Encryption, pna::CipherMode);
type ReencryptOptionsCache = HashMap<ReencryptOptionsKey, WriteOptions>;

/// Decrypts `entry` and rebuilds it under `new_name`, re-encrypted with the
/// same encryption algorithm, cipher mode, and compression as the source
/// entry. The KDF parameters are not recoverable from a parsed entry, so the
/// rebuilt entry uses the default hash algorithm for its cipher mode.
fn re_encrypt_entry_with_name(
entry: &NormalEntry,
new_name: pna::EntryName,
password: &[u8],
reencrypt_options: &mut ReencryptOptionsCache,
) -> io::Result<NormalEntry> {
let header = entry.header();
let key = (
header.compression(),
header.encryption(),
header.cipher_mode(),
);
let options = match reencrypt_options.entry(key) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
std::collections::hash_map::Entry::Vacant(entry) => {
let options = WriteOptions::builder()
.compression(header.compression())
.encryption(header.encryption())
.cipher_mode(header.cipher_mode())
.password(Some(password))
.try_build()?;
entry.insert(options)
}
};
let mut builder = EntryBuilder::new_file(new_name, &*options)?;
let mut reader = entry.reader(pna::ReadOptions::with_password(Some(password)))?;
io::copy(&mut reader, &mut builder)?;
Ok(builder
.build()?
.with_metadata(entry.metadata().clone())
.with_xattrs(entry.xattrs())
.with_extra_chunks(entry.extra_chunks()))
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -2161,6 +2236,35 @@ mod tests {
}
}

#[test]
fn gcm_reencrypt_options_are_reused_for_matching_entries() {
let source_options = WriteOptions::builder()
.encryption(pna::Encryption::AES)
.cipher_mode(pna::CipherMode::GCM)
.hash_algorithm(pna::HashAlgorithm::pbkdf2_sha256_with(Some(1)))
.password(Some("password"))
.build();
let mut source = EntryBuilder::new_file("original".into(), &source_options).unwrap();
source.write_all(b"secret payload").unwrap();
let source = source.build().unwrap();
let mut cache = ReencryptOptionsCache::new();

let first =
re_encrypt_entry_with_name(&source, "first".into(), b"password", &mut cache).unwrap();
Comment thread
ChanTsune marked this conversation as resolved.
Dismissed
let second =
re_encrypt_entry_with_name(&source, "second".into(), b"password", &mut cache).unwrap();
Comment thread
ChanTsune marked this conversation as resolved.
Dismissed

assert_eq!(cache.len(), 1);
for entry in [first, second] {
let mut reader = entry
.reader(pna::ReadOptions::with_password(Some("password")))
.unwrap();
let mut out = Vec::new();
reader.read_to_end(&mut out).unwrap();
assert_eq!(out, b"secret payload");
}
}

fn default_collect_options<'a>(
filter: &'a PathFilter<'a>,
time_filters: &'a TimeFilters,
Expand Down
1 change: 1 addition & 0 deletions cli/tests/cli/bsdtar.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod archive_inclusion;
mod archive_source_uid_override;
mod encrypted_rename;
mod files_from;
mod list_line_ending;
mod missing_file;
Expand Down
Loading
Loading