1#![cfg_attr(
7 feature = "fs",
8 doc = "[`ArchiveTrait::extract_in`] validates and normalizes them as",
9 doc = "specified by [`crate::extract::ExtractPolicy`]."
10)]
11
12use std::collections::HashSet;
13
14use archive_trait::{
15 Archive as ArchiveTrait, Member, MemberMetadata, MemberPayload as MemberPayloadTrait,
16 SpecialKind,
17};
18use tar_framing::{
19 FrameError, PaxExtension, PaxKeyword, PaxKind, PaxRecord, PaxValue, StreamPolicy, UstarKind,
20 logical::{MemberExtensions, MemberFrame, MemberPayload as FramingMemberPayload, TarReader},
21};
22use thiserror::Error;
23use tokio::io::AsyncRead;
24
25pub use tar_framing::{
26 DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE, DEFAULT_MAX_GNU_EXTENSION_SIZE,
27 DEFAULT_MAX_PAX_EXTENSION_SIZE, TrailingDataPolicy,
28};
29
30#[cfg_attr(
42 feature = "fs",
43 doc = "",
44 doc = "[`ArchiveTrait::extract_in`] validates member paths and link targets",
45 doc = "during extraction."
46)]
47pub struct TarArchive<R> {
48 reader: TarReader<R>,
49 policy: DecodePolicy,
50 poisoned: bool,
51}
52
53impl<R> TarArchive<R> {
54 pub fn new(reader: R) -> Self {
56 Self {
57 reader: TarReader::new(reader),
58 policy: DecodePolicy::default(),
59 poisoned: false,
60 }
61 }
62
63 pub fn with_policy(mut self, policy: DecodePolicy) -> Self {
67 let stream_policy = StreamPolicy::default()
68 .trailing_data_policy(policy.trailing_data_policy)
69 .max_pax_extension_size(policy.pax_policy.max_extension_size)
70 .max_global_pax_extensions_size(policy.pax_policy.max_global_extensions_size)
71 .allow_pax_hardlink_linkdata(policy.pax_policy.allow_hardlink_linkdata)
72 .allow_all_nul_numeric_fields(policy.allow_all_nul_numeric_fields)
73 .allow_header_uname_and_gname_without_terminator(
74 policy.allow_header_uname_and_gname_without_terminator,
75 )
76 .allow_gnu_extensions_without_terminator(policy.allow_gnu_extensions_without_terminator)
77 .allow_pax_base256_uid_and_gid(policy.pax_policy.allow_base256_uid_and_gid)
78 .max_gnu_extension_size(policy.max_gnu_extension_size);
79 self.reader = self.reader.with_policy(stream_policy);
80 self.policy = policy;
81 self
82 }
83}
84
85#[derive(Clone, Debug)]
89pub struct DecodePolicy {
90 trailing_data_policy: TrailingDataPolicy,
91 allow_gnu: bool,
92 allow_all_nul_numeric_fields: bool,
93 allow_header_uname_and_gname_without_terminator: bool,
94 allow_gnu_extensions_without_terminator: bool,
95 max_gnu_extension_size: u64,
96 pax_policy: PaxDecodePolicy,
97}
98
99#[derive(Clone, Debug, Eq, PartialEq)]
103pub struct PaxDecodePolicy {
104 max_extension_size: u64,
105 max_global_extensions_size: u64,
106 allow_non_utf8_pax_vendor_values: bool,
107 allow_global_pax_extensions: bool,
108 vendor_extension_policy: PaxVendorExtensionPolicy,
109 allow_duplicate_pax_records: bool,
110 allow_global_pax_member_metadata: bool,
111 allow_hardlink_linkdata: bool,
112 allow_base256_uid_and_gid: bool,
113}
114
115#[derive(Clone, Debug, Default, Eq, PartialEq)]
117pub enum PaxVendorExtensionPolicy {
118 #[default]
120 RejectUnknown,
121 Ignore(PaxVendorAllowlist),
125 AllowUnknown,
129}
130
131impl PaxVendorExtensionPolicy {
132 pub fn ignore(vendors: impl IntoIterator<Item = &'static str>) -> Self {
136 Self::Ignore(PaxVendorAllowlist {
137 vendors: vendors.into_iter().collect(),
138 })
139 }
140}
141
142#[derive(Clone, Debug, Eq, PartialEq)]
146pub struct PaxVendorAllowlist {
147 vendors: HashSet<&'static str>,
148}
149
150impl Default for PaxDecodePolicy {
151 fn default() -> Self {
152 Self {
153 max_extension_size: DEFAULT_MAX_PAX_EXTENSION_SIZE,
154 max_global_extensions_size: DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE,
155 allow_non_utf8_pax_vendor_values: true,
156 allow_global_pax_extensions: true,
157 vendor_extension_policy: PaxVendorExtensionPolicy::default(),
158 allow_duplicate_pax_records: false,
159 allow_global_pax_member_metadata: false,
160 allow_hardlink_linkdata: false,
161 allow_base256_uid_and_gid: false,
162 }
163 }
164}
165
166impl Default for DecodePolicy {
167 fn default() -> Self {
168 Self {
169 trailing_data_policy: TrailingDataPolicy::default(),
170 allow_gnu: true,
171 allow_all_nul_numeric_fields: true,
172 allow_header_uname_and_gname_without_terminator: false,
173 allow_gnu_extensions_without_terminator: false,
174 max_gnu_extension_size: DEFAULT_MAX_GNU_EXTENSION_SIZE,
175 pax_policy: PaxDecodePolicy::default(),
176 }
177 }
178}
179
180impl DecodePolicy {
181 pub fn trailing_data_policy(mut self, policy: TrailingDataPolicy) -> Self {
185 self.trailing_data_policy = policy;
186 self
187 }
188
189 pub fn allow_gnu(mut self, allow: bool) -> Self {
196 self.allow_gnu = allow;
197 self
198 }
199
200 pub fn allow_all_nul_numeric_fields(mut self, allow: bool) -> Self {
208 self.allow_all_nul_numeric_fields = allow;
209 self
210 }
211
212 pub fn allow_header_uname_and_gname_without_terminator(mut self, allow: bool) -> Self {
218 self.allow_header_uname_and_gname_without_terminator = allow;
219 self
220 }
221
222 pub fn allow_gnu_extensions_without_terminator(mut self, allow: bool) -> Self {
227 self.allow_gnu_extensions_without_terminator = allow;
228 self
229 }
230
231 pub fn max_gnu_extension_size(mut self, max_gnu_extension_size: u64) -> Self {
239 self.max_gnu_extension_size = max_gnu_extension_size;
240 self
241 }
242
243 pub fn pax_policy(mut self, policy: PaxDecodePolicy) -> Self {
245 self.pax_policy = policy;
246 self
247 }
248
249 fn check_member<R>(&self, frame: &MemberFrame<'_, R>) -> Result<(), DecodeError> {
250 match &frame.extensions {
251 MemberExtensions::Pax(state) => {
252 for extension in state.extensions() {
253 self.pax_policy.check_extension(extension)?;
254 }
255 }
256 MemberExtensions::Gnu {
257 long_name,
258 long_link,
259 } if !self.allow_gnu => {
260 let position = long_name
261 .iter()
262 .chain(long_link)
263 .map(|extension| extension.position)
264 .min()
265 .unwrap_or(frame.header.position);
266 return Err(DecodeError::policy_violation(
267 position,
268 DecodePolicyViolation::GnuArchive,
269 ));
270 }
271 MemberExtensions::Gnu { .. } => {}
272 }
273 Ok(())
274 }
275}
276
277impl PaxDecodePolicy {
278 pub fn max_extension_size(mut self, max_extension_size: u64) -> Self {
289 self.max_extension_size = max_extension_size;
290 self
291 }
292
293 pub fn max_global_extensions_size(mut self, max_global_extensions_size: u64) -> Self {
302 self.max_global_extensions_size = max_global_extensions_size;
303 self
304 }
305
306 pub fn allow_non_utf8_pax_vendor_values(mut self, allow: bool) -> Self {
316 self.allow_non_utf8_pax_vendor_values = allow;
317 self
318 }
319
320 pub fn allow_global_pax_extensions(mut self, allow: bool) -> Self {
329 self.allow_global_pax_extensions = allow;
330 self
331 }
332
333 pub fn vendor_extension_policy(mut self, policy: PaxVendorExtensionPolicy) -> Self {
350 self.vendor_extension_policy = policy;
351 self
352 }
353
354 pub fn allow_duplicate_pax_records(mut self, allow: bool) -> Self {
361 self.allow_duplicate_pax_records = allow;
362 self
363 }
364
365 pub fn allow_global_pax_member_metadata(mut self, allow: bool) -> Self {
373 self.allow_global_pax_member_metadata = allow;
374 self
375 }
376
377 #[cfg_attr(
385 feature = "fs",
386 doc = "See [`crate::extract::LinkPolicy::allow_hard_links`]."
387 )]
388 pub fn allow_hardlink_linkdata(mut self, allow: bool) -> Self {
389 self.allow_hardlink_linkdata = allow;
390 self
391 }
392
393 pub fn allow_base256_uid_and_gid(mut self, allow: bool) -> Self {
398 self.allow_base256_uid_and_gid = allow;
399 self
400 }
401
402 fn check_extension(&self, extension: &PaxExtension) -> Result<(), DecodeError> {
403 let position = extension.position;
404 if extension.kind == PaxKind::Global && !self.allow_global_pax_extensions {
405 return Err(DecodeError::policy_violation(
406 position,
407 DecodePolicyViolation::GlobalPaxExtension,
408 ));
409 }
410
411 let records = extension.records();
412 for record in records {
413 if let PaxRecord::Vendor {
414 vendor,
415 name,
416 value,
417 } = record
418 {
419 let allowed = match &self.vendor_extension_policy {
420 PaxVendorExtensionPolicy::RejectUnknown => false,
421 PaxVendorExtensionPolicy::Ignore(allowed) => {
422 allowed.vendors.contains(vendor.as_ref())
423 }
424 PaxVendorExtensionPolicy::AllowUnknown => true,
425 };
426 if !allowed {
427 return Err(DecodeError::policy_violation(
428 position,
429 DecodePolicyViolation::PaxVendorExtension {
430 vendor: vendor.to_string(),
431 name: name.to_string(),
432 },
433 ));
434 }
435
436 if !self.allow_non_utf8_pax_vendor_values
437 && let PaxValue::Value(value) = value
438 && std::str::from_utf8(value).is_err()
439 {
440 return Err(DecodeError::policy_violation(
441 position,
442 DecodePolicyViolation::NonUtf8PaxVendorValue {
443 vendor: vendor.to_string(),
444 name: name.to_string(),
445 },
446 ));
447 }
448 }
449 }
450
451 if extension.kind == PaxKind::Global && !self.allow_global_pax_member_metadata {
452 for record in records {
453 let keyword = match record.keyword() {
454 PaxKeyword::Path => Some("path"),
455 PaxKeyword::LinkPath => Some("linkpath"),
456 PaxKeyword::Size => Some("size"),
457 _ => None,
458 };
459 if let Some(keyword) = keyword {
460 return Err(DecodeError::policy_violation(
461 position,
462 DecodePolicyViolation::GlobalPaxMemberMetadata { keyword },
463 ));
464 }
465 }
466 }
467
468 if !self.allow_duplicate_pax_records {
469 let mut keywords = HashSet::new();
470 for record in records {
471 let keyword = record.keyword();
472 if !keywords.insert(keyword.clone()) {
473 return Err(DecodeError::policy_violation(
474 position,
475 DecodePolicyViolation::DuplicatePaxRecord {
476 keyword: keyword.to_string(),
477 },
478 ));
479 }
480 }
481 }
482
483 Ok(())
484 }
485}
486
487#[derive(Clone, Debug, Eq, PartialEq, Error)]
489pub enum DecodePolicyViolation {
490 #[error("GNU archives are not allowed")]
492 GnuArchive,
493 #[error("global pax extended headers are not allowed")]
495 GlobalPaxExtension,
496 #[error("pax vendor extension {vendor}.{name} is not allowed")]
498 PaxVendorExtension {
499 vendor: String,
501 name: String,
503 },
504 #[error("pax vendor extension {vendor}.{name} contains a non-UTF-8 value")]
506 NonUtf8PaxVendorValue {
507 vendor: String,
509 name: String,
511 },
512 #[error("pax extended header contains duplicate record {keyword}")]
514 DuplicatePaxRecord {
515 keyword: String,
517 },
518 #[error("global pax extended header contains restricted member metadata {keyword}")]
520 GlobalPaxMemberMetadata {
521 keyword: &'static str,
523 },
524}
525
526#[derive(Debug, Error)]
528pub enum DecodeError {
529 #[error(transparent)]
531 Framing(#[from] FrameError),
532 #[error("at byte {position}: {field} is not valid UTF-8")]
534 InvalidUtf8 {
535 position: u64,
537 field: &'static str,
539 },
540 #[error("at byte {position}: decode policy rejected input: {violation}")]
542 PolicyViolation {
543 position: u64,
545 violation: DecodePolicyViolation,
547 },
548 #[error("tar reader is poisoned after a decoding error")]
550 Poisoned,
551}
552
553impl DecodeError {
554 fn policy_violation(position: u64, violation: DecodePolicyViolation) -> Self {
555 Self::PolicyViolation {
556 position,
557 violation,
558 }
559 }
560}
561
562pub struct TarMemberPayload<'a, R> {
564 payload: FramingMemberPayload<'a, R>,
565 poisoned: &'a mut bool,
566}
567
568impl<R: AsyncRead + Unpin> MemberPayloadTrait for TarMemberPayload<'_, R> {
569 type Error = DecodeError;
570
571 async fn next_chunk(
572 &mut self,
573 buffer: &mut Vec<u8>,
574 target_len: usize,
575 ) -> Result<bool, Self::Error> {
576 if *self.poisoned {
577 return Err(DecodeError::Poisoned);
578 }
579 self.payload
580 .next_chunk(buffer, target_len)
581 .await
582 .inspect_err(|_| *self.poisoned = true)
583 .map_err(Into::into)
584 }
585
586 async fn skip(self) -> Result<(), Self::Error> {
587 if *self.poisoned {
588 return Err(DecodeError::Poisoned);
589 }
590 self.payload
591 .skip()
592 .await
593 .inspect_err(|_| *self.poisoned = true)
594 .map_err(Into::into)
595 }
596}
597
598impl<R: AsyncRead + Unpin> ArchiveTrait for TarArchive<R> {
599 type Error = DecodeError;
600 type Payload<'a>
601 = TarMemberPayload<'a, R>
602 where
603 Self: 'a;
604
605 async fn next_member<'a>(
606 &'a mut self,
607 ) -> Result<Option<Member<Self::Payload<'a>>>, Self::Error> {
608 let poisoned = &mut self.poisoned;
609 if *poisoned {
610 return Err(DecodeError::Poisoned);
611 }
612
613 let member = match self.reader.next_frame().await {
614 Ok(Some(frame)) => decode_member(frame, &self.policy).map(Some),
615 Ok(None) => Ok(None),
616 Err(error) => Err(error.into()),
617 }
618 .inspect_err(|_| *poisoned = true)?;
619 Ok(member
620 .map(|member| member.map_payload(|payload| TarMemberPayload { payload, poisoned })))
621 }
622}
623
624fn decode_member<'a, R>(
625 frame: MemberFrame<'a, R>,
626 policy: &DecodePolicy,
627) -> Result<Member<FramingMemberPayload<'a, R>>, DecodeError> {
628 policy.check_member(&frame)?;
629 let position = frame.header.position;
630 let kind = frame.header.kind;
631 let size = frame.header.effective_size;
632 let executable = frame.header.mode.unwrap_or_default() & 0o111 != 0;
633 let path = std::str::from_utf8(frame.effective_path()?)
634 .map(str::to_owned)
635 .map_err(|_| DecodeError::InvalidUtf8 {
636 position,
637 field: "path",
638 })?;
639 let target = if matches!(kind, UstarKind::HardLink | UstarKind::SymbolicLink) {
640 std::str::from_utf8(frame.effective_link_path()?)
641 .map(str::to_owned)
642 .map_err(|_| DecodeError::InvalidUtf8 {
643 position,
644 field: "linkpath",
645 })?
646 } else {
647 String::new()
648 };
649 let metadata = MemberMetadata { path, position };
650
651 Ok(match kind {
652 UstarKind::Regular | UstarKind::Contiguous => Member::File {
653 metadata,
654 size,
655 executable,
656 payload: frame.payload,
657 },
658 UstarKind::Directory => Member::Directory { metadata },
659 UstarKind::SymbolicLink => Member::SymbolicLink { metadata, target },
660 UstarKind::HardLink => Member::HardLink {
661 metadata,
662 target,
663 size,
664 payload: frame.payload,
665 },
666 UstarKind::CharacterDevice => Member::Special {
667 metadata,
668 kind: SpecialKind::CharacterDevice,
669 },
670 UstarKind::BlockDevice => Member::Special {
671 metadata,
672 kind: SpecialKind::BlockDevice,
673 },
674 UstarKind::Fifo => Member::Special {
675 metadata,
676 kind: SpecialKind::Fifo,
677 },
678 })
679}