#![cfg_attr(
feature = "fs",
doc = "[`ArchiveTrait::extract_in`] validates and normalizes them as",
doc = "specified by [`crate::extract::ExtractPolicy`]."
)]
use std::collections::HashSet;
use archive_trait::{
Archive as ArchiveTrait, Member, MemberMetadata, MemberPayload as MemberPayloadTrait,
SpecialKind,
};
use tar_framing::{
FrameError, PaxExtension, PaxKeyword, PaxKind, PaxRecord, PaxValue, StreamPolicy, UstarKind,
logical::{MemberExtensions, MemberFrame, MemberPayload as FramingMemberPayload, TarReader},
};
use thiserror::Error;
use tokio::io::AsyncRead;
pub use tar_framing::{
DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE, DEFAULT_MAX_GNU_EXTENSION_SIZE,
DEFAULT_MAX_PAX_EXTENSION_SIZE, TrailingDataPolicy,
};
#[cfg_attr(
feature = "fs",
doc = "",
doc = "[`ArchiveTrait::extract_in`] validates member paths and link targets",
doc = "during extraction."
)]
pub struct TarArchive<R> {
reader: TarReader<R>,
policy: DecodePolicy,
poisoned: bool,
}
impl<R> TarArchive<R> {
pub fn new(reader: R) -> Self {
Self {
reader: TarReader::new(reader),
policy: DecodePolicy::default(),
poisoned: false,
}
}
pub fn with_policy(mut self, policy: DecodePolicy) -> Self {
let stream_policy = StreamPolicy::default()
.trailing_data_policy(policy.trailing_data_policy)
.max_pax_extension_size(policy.pax_policy.max_extension_size)
.max_global_pax_extensions_size(policy.pax_policy.max_global_extensions_size)
.allow_pax_hardlink_linkdata(policy.pax_policy.allow_hardlink_linkdata)
.allow_all_nul_numeric_fields(policy.allow_all_nul_numeric_fields)
.allow_header_uname_and_gname_without_terminator(
policy.allow_header_uname_and_gname_without_terminator,
)
.allow_gnu_extensions_without_terminator(policy.allow_gnu_extensions_without_terminator)
.allow_pax_base256_uid_and_gid(policy.pax_policy.allow_base256_uid_and_gid)
.max_gnu_extension_size(policy.max_gnu_extension_size);
self.reader = self.reader.with_policy(stream_policy);
self.policy = policy;
self
}
}
#[derive(Clone, Debug)]
pub struct DecodePolicy {
trailing_data_policy: TrailingDataPolicy,
allow_gnu: bool,
allow_all_nul_numeric_fields: bool,
allow_header_uname_and_gname_without_terminator: bool,
allow_gnu_extensions_without_terminator: bool,
max_gnu_extension_size: u64,
pax_policy: PaxDecodePolicy,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PaxDecodePolicy {
max_extension_size: u64,
max_global_extensions_size: u64,
allow_non_utf8_pax_vendor_values: bool,
allow_global_pax_extensions: bool,
vendor_extension_policy: PaxVendorExtensionPolicy,
allow_duplicate_pax_records: bool,
allow_global_pax_member_metadata: bool,
allow_hardlink_linkdata: bool,
allow_base256_uid_and_gid: bool,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum PaxVendorExtensionPolicy {
#[default]
RejectUnknown,
Ignore(PaxVendorAllowlist),
AllowUnknown,
}
impl PaxVendorExtensionPolicy {
pub fn ignore(vendors: impl IntoIterator<Item = &'static str>) -> Self {
Self::Ignore(PaxVendorAllowlist {
vendors: vendors.into_iter().collect(),
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PaxVendorAllowlist {
vendors: HashSet<&'static str>,
}
impl Default for PaxDecodePolicy {
fn default() -> Self {
Self {
max_extension_size: DEFAULT_MAX_PAX_EXTENSION_SIZE,
max_global_extensions_size: DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE,
allow_non_utf8_pax_vendor_values: true,
allow_global_pax_extensions: true,
vendor_extension_policy: PaxVendorExtensionPolicy::default(),
allow_duplicate_pax_records: false,
allow_global_pax_member_metadata: false,
allow_hardlink_linkdata: false,
allow_base256_uid_and_gid: false,
}
}
}
impl Default for DecodePolicy {
fn default() -> Self {
Self {
trailing_data_policy: TrailingDataPolicy::default(),
allow_gnu: true,
allow_all_nul_numeric_fields: true,
allow_header_uname_and_gname_without_terminator: false,
allow_gnu_extensions_without_terminator: false,
max_gnu_extension_size: DEFAULT_MAX_GNU_EXTENSION_SIZE,
pax_policy: PaxDecodePolicy::default(),
}
}
}
impl DecodePolicy {
pub fn trailing_data_policy(mut self, policy: TrailingDataPolicy) -> Self {
self.trailing_data_policy = policy;
self
}
pub fn allow_gnu(mut self, allow: bool) -> Self {
self.allow_gnu = allow;
self
}
pub fn allow_all_nul_numeric_fields(mut self, allow: bool) -> Self {
self.allow_all_nul_numeric_fields = allow;
self
}
pub fn allow_header_uname_and_gname_without_terminator(mut self, allow: bool) -> Self {
self.allow_header_uname_and_gname_without_terminator = allow;
self
}
pub fn allow_gnu_extensions_without_terminator(mut self, allow: bool) -> Self {
self.allow_gnu_extensions_without_terminator = allow;
self
}
pub fn max_gnu_extension_size(mut self, max_gnu_extension_size: u64) -> Self {
self.max_gnu_extension_size = max_gnu_extension_size;
self
}
pub fn pax_policy(mut self, policy: PaxDecodePolicy) -> Self {
self.pax_policy = policy;
self
}
fn check_member<R>(&self, frame: &MemberFrame<'_, R>) -> Result<(), DecodeError> {
match &frame.extensions {
MemberExtensions::Pax(state) => {
for extension in state.extensions() {
self.pax_policy.check_extension(extension)?;
}
}
MemberExtensions::Gnu {
long_name,
long_link,
} if !self.allow_gnu => {
let position = long_name
.iter()
.chain(long_link)
.map(|extension| extension.position)
.min()
.unwrap_or(frame.header.position);
return Err(DecodeError::policy_violation(
position,
DecodePolicyViolation::GnuArchive,
));
}
MemberExtensions::Gnu { .. } => {}
}
Ok(())
}
}
impl PaxDecodePolicy {
pub fn max_extension_size(mut self, max_extension_size: u64) -> Self {
self.max_extension_size = max_extension_size;
self
}
pub fn max_global_extensions_size(mut self, max_global_extensions_size: u64) -> Self {
self.max_global_extensions_size = max_global_extensions_size;
self
}
pub fn allow_non_utf8_pax_vendor_values(mut self, allow: bool) -> Self {
self.allow_non_utf8_pax_vendor_values = allow;
self
}
pub fn allow_global_pax_extensions(mut self, allow: bool) -> Self {
self.allow_global_pax_extensions = allow;
self
}
pub fn vendor_extension_policy(mut self, policy: PaxVendorExtensionPolicy) -> Self {
self.vendor_extension_policy = policy;
self
}
pub fn allow_duplicate_pax_records(mut self, allow: bool) -> Self {
self.allow_duplicate_pax_records = allow;
self
}
pub fn allow_global_pax_member_metadata(mut self, allow: bool) -> Self {
self.allow_global_pax_member_metadata = allow;
self
}
#[cfg_attr(
feature = "fs",
doc = "See [`crate::extract::LinkPolicy::allow_hard_links`]."
)]
pub fn allow_hardlink_linkdata(mut self, allow: bool) -> Self {
self.allow_hardlink_linkdata = allow;
self
}
pub fn allow_base256_uid_and_gid(mut self, allow: bool) -> Self {
self.allow_base256_uid_and_gid = allow;
self
}
fn check_extension(&self, extension: &PaxExtension) -> Result<(), DecodeError> {
let position = extension.position;
if extension.kind == PaxKind::Global && !self.allow_global_pax_extensions {
return Err(DecodeError::policy_violation(
position,
DecodePolicyViolation::GlobalPaxExtension,
));
}
let records = extension.records();
for record in records {
if let PaxRecord::Vendor {
vendor,
name,
value,
} = record
{
let allowed = match &self.vendor_extension_policy {
PaxVendorExtensionPolicy::RejectUnknown => false,
PaxVendorExtensionPolicy::Ignore(allowed) => {
allowed.vendors.contains(vendor.as_ref())
}
PaxVendorExtensionPolicy::AllowUnknown => true,
};
if !allowed {
return Err(DecodeError::policy_violation(
position,
DecodePolicyViolation::PaxVendorExtension {
vendor: vendor.to_string(),
name: name.to_string(),
},
));
}
if !self.allow_non_utf8_pax_vendor_values
&& let PaxValue::Value(value) = value
&& std::str::from_utf8(value).is_err()
{
return Err(DecodeError::policy_violation(
position,
DecodePolicyViolation::NonUtf8PaxVendorValue {
vendor: vendor.to_string(),
name: name.to_string(),
},
));
}
}
}
if extension.kind == PaxKind::Global && !self.allow_global_pax_member_metadata {
for record in records {
let keyword = match record.keyword() {
PaxKeyword::Path => Some("path"),
PaxKeyword::LinkPath => Some("linkpath"),
PaxKeyword::Size => Some("size"),
_ => None,
};
if let Some(keyword) = keyword {
return Err(DecodeError::policy_violation(
position,
DecodePolicyViolation::GlobalPaxMemberMetadata { keyword },
));
}
}
}
if !self.allow_duplicate_pax_records {
let mut keywords = HashSet::new();
for record in records {
let keyword = record.keyword();
if !keywords.insert(keyword.clone()) {
return Err(DecodeError::policy_violation(
position,
DecodePolicyViolation::DuplicatePaxRecord {
keyword: keyword.to_string(),
},
));
}
}
}
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq, Error)]
pub enum DecodePolicyViolation {
#[error("GNU archives are not allowed")]
GnuArchive,
#[error("global pax extended headers are not allowed")]
GlobalPaxExtension,
#[error("pax vendor extension {vendor}.{name} is not allowed")]
PaxVendorExtension {
vendor: String,
name: String,
},
#[error("pax vendor extension {vendor}.{name} contains a non-UTF-8 value")]
NonUtf8PaxVendorValue {
vendor: String,
name: String,
},
#[error("pax extended header contains duplicate record {keyword}")]
DuplicatePaxRecord {
keyword: String,
},
#[error("global pax extended header contains restricted member metadata {keyword}")]
GlobalPaxMemberMetadata {
keyword: &'static str,
},
}
#[derive(Debug, Error)]
pub enum DecodeError {
#[error(transparent)]
Framing(#[from] FrameError),
#[error("at byte {position}: {field} is not valid UTF-8")]
InvalidUtf8 {
position: u64,
field: &'static str,
},
#[error("at byte {position}: decode policy rejected input: {violation}")]
PolicyViolation {
position: u64,
violation: DecodePolicyViolation,
},
#[error("tar reader is poisoned after a decoding error")]
Poisoned,
}
impl DecodeError {
fn policy_violation(position: u64, violation: DecodePolicyViolation) -> Self {
Self::PolicyViolation {
position,
violation,
}
}
}
pub struct TarMemberPayload<'a, R> {
payload: FramingMemberPayload<'a, R>,
poisoned: &'a mut bool,
}
impl<R: AsyncRead + Unpin> MemberPayloadTrait for TarMemberPayload<'_, R> {
type Error = DecodeError;
async fn next_chunk(
&mut self,
buffer: &mut Vec<u8>,
target_len: usize,
) -> Result<bool, Self::Error> {
if *self.poisoned {
return Err(DecodeError::Poisoned);
}
self.payload
.next_chunk(buffer, target_len)
.await
.inspect_err(|_| *self.poisoned = true)
.map_err(Into::into)
}
async fn skip(self) -> Result<(), Self::Error> {
if *self.poisoned {
return Err(DecodeError::Poisoned);
}
self.payload
.skip()
.await
.inspect_err(|_| *self.poisoned = true)
.map_err(Into::into)
}
}
impl<R: AsyncRead + Unpin> ArchiveTrait for TarArchive<R> {
type Error = DecodeError;
type Payload<'a>
= TarMemberPayload<'a, R>
where
Self: 'a;
async fn next_member<'a>(
&'a mut self,
) -> Result<Option<Member<Self::Payload<'a>>>, Self::Error> {
let poisoned = &mut self.poisoned;
if *poisoned {
return Err(DecodeError::Poisoned);
}
let member = match self.reader.next_frame().await {
Ok(Some(frame)) => decode_member(frame, &self.policy).map(Some),
Ok(None) => Ok(None),
Err(error) => Err(error.into()),
}
.inspect_err(|_| *poisoned = true)?;
Ok(member
.map(|member| member.map_payload(|payload| TarMemberPayload { payload, poisoned })))
}
}
fn decode_member<'a, R>(
frame: MemberFrame<'a, R>,
policy: &DecodePolicy,
) -> Result<Member<FramingMemberPayload<'a, R>>, DecodeError> {
policy.check_member(&frame)?;
let position = frame.header.position;
let kind = frame.header.kind;
let size = frame.header.effective_size;
let executable = frame.header.mode.unwrap_or_default() & 0o111 != 0;
let path = std::str::from_utf8(frame.effective_path()?)
.map(str::to_owned)
.map_err(|_| DecodeError::InvalidUtf8 {
position,
field: "path",
})?;
let target = if matches!(kind, UstarKind::HardLink | UstarKind::SymbolicLink) {
std::str::from_utf8(frame.effective_link_path()?)
.map(str::to_owned)
.map_err(|_| DecodeError::InvalidUtf8 {
position,
field: "linkpath",
})?
} else {
String::new()
};
let metadata = MemberMetadata { path, position };
Ok(match kind {
UstarKind::Regular | UstarKind::Contiguous => Member::File {
metadata,
size,
executable,
payload: frame.payload,
},
UstarKind::Directory => Member::Directory { metadata },
UstarKind::SymbolicLink => Member::SymbolicLink { metadata, target },
UstarKind::HardLink => Member::HardLink {
metadata,
target,
size,
payload: frame.payload,
},
UstarKind::CharacterDevice => Member::Special {
metadata,
kind: SpecialKind::CharacterDevice,
},
UstarKind::BlockDevice => Member::Special {
metadata,
kind: SpecialKind::BlockDevice,
},
UstarKind::Fifo => Member::Special {
metadata,
kind: SpecialKind::Fifo,
},
})
}