# Restoring a TAR hard link can select old destination bytes

**Measured result:** selecting the hard-link member of our intact TAR into a
directory containing an old target completed without error in GNU tar 1.35 and
both tested Python builds, but restored the old bytes. The selected name existed,
its size was correct, and its content was wrong for the required recovery generation.

This is a controlled native experiment plus source synthesis, not a new
vulnerability claim. The contribution connects archive representation, destination
state, extraction API and the recovery acceptance requirement. Publication companion: the existing archive-recovery analysis and archive-member /
hard-link corpus records. The experiment is version-scoped, not a product ranking.

## What the same archive produced

GNU tar created a USTAR archive containing a regular entry named `target`,
then a zero-payload hard-link entry named `alias` referring to it. The intended
payload and the deliberately stale payload are both 29 bytes. Every operation
runs in its own fresh disposable directory; a stale or matching target is seeded
only for the designated controls. No damaged header, duplicate name or symlink
is needed.

| Operation on target-first fixture | Destination | Completion | Selected bytes |
|---|---|---|---|
| GNU tar, extract all | Empty | Status 0 | Expected, 29 bytes |
| GNU tar, extract alias | Empty | Nonzero status | No alias created |
| GNU tar, extract alias | Stale target | Status 0 | Stale, 29 bytes |
| GNU tar, extract alias | Matching target | Status 0 | Expected, shared with target |
| GNU tar, alias to stdout | Empty | Status 0 | Empty, 0 bytes |
| Python, extract all | Empty | No exception | Expected, shared with target |
| Python, extract alias | Empty | No exception | Expected copy; target not created |
| Python, extract alias | Stale target | No exception | Stale, shared with target |
| Python, extract alias | Matching target | No exception | Expected, shared with target |
| Python, seekable extractfile(alias) | No disk extraction | No exception | Expected, 29 bytes |
| Python, streaming extractfile(alias) | No disk extraction | StreamError | No returned payload |

Python disk extraction explicitly uses `filter="data"` and `errorlevel=2`.
Passing that filter does not establish the requested recovery generation.
The GNU stdout result is specific to this tested zero-payload hard-link entry;
it is not a statement that stdout extraction generally returns nothing.

The same normalized results appeared on CPython 3.12.3 (distribution build,
GCC 13.3.0) and CPython 3.12.15 (uv-managed build, Clang 22.1.3), on the same Linux
host and with the same GNU tar binary. Runtime module/binary hashes are retained.
These are two builds, not two independent Python implementations.

## Controls that change the result

Five archives and eleven operations produce 55 configurations per build.
Reversing the two input names makes `alias` the regular payload entry and
`target` the link; all selected-alias reads in that control return expected bytes.
Archiving only `alias` also creates a self-contained regular entry even though
the source still has another name. Equal bytes in genuinely distinct source
files do not acquire a hard-link relationship.

With `--hard-dereference`, both names have regular payload entries. Full
extraction returns the expected bytes but creates two distinct files. Our
post-observation write probe then changes only `alias`; after a normal
hard-link-preserving full extraction, the same write also changes `target`.

A byte-for-byte test goes further: after normalizing recorded metadata, the
dereferenced archive from a shared source is identical to the archive from two
independent equal-content files. Both have SHA-256
`6267bb4ec4fc93cd4f99aa4893bf096b8ab3f7541d3dce4d7a28bea0089856f8`.
The test compares actual archive bytes, not merely hashes.
**Inference:** the original sharing relationship cannot be reconstructed from
those archive bytes alone. A digest of each restored pathname can pass in both
cases while the required file relationships differ.

## Why the sources fit together

GNU's manual explains that hard-link records can make individual-member
extraction depend on another name and offers hard dereferencing as an alternative.
That choice changes the stored representation. Our fixtures measure its consequences
for selected reads and restored sharing.
[GNU tar 1.35, section 8.3.3](https://www.gnu.org/software/tar/manual/html_node/hard-links.html)

The Python API distinguishes extraction to disk from returning a file object.
In the pinned implementation, the disk hard-link path tries an existing target
before falling back to an earlier archive member. Seekable `extractfile`
resolves the archive member; its streaming link path raises `StreamError`.
This explains the measured contrast without treating every reader as equivalent.
[API documentation](https://docs.python.org/3.12/library/tarfile.html),
[CPython v3.12.15 implementation](https://github.com/python/cpython/blob/v3.12.15/Lib/tarfile.py)

Zwicky's LISA 2003 paper notes the symmetry of hard-linked names and the possible
importance of which name an archiver encounters first. We make encounter order
explicit in a small controlled test and connect it to recovery selection.
This is a methodological connection, not a replication of that paper's broad
historical test suite or evidence for a present-day failure rate.
[USENIX paper](https://www.usenix.org/conference/lisa-03/further-torture-more-testing-backup-and-archive-programs)

## A recovery requirement with three separate checks

1. Decide whether recovery requires the selected file's bytes, the full namespace,
   or preservation of which names share a file. These are different acceptance criteria.
2. Resolve the selected member's dependencies in a fresh, isolated staging area.
   Do not assume an existing destination target belongs to the required generation.
   An empty directory alone is insufficient for GNU's selected-link case:
   the necessary target must also be restored or the intended bytes recovered explicitly.
3. Verify expected content against an independently recorded requirement.
   When sharing matters, also compare equivalence classes of restored names.
   Use live device/inode pairs for that comparison, not raw inode numbers as
   persistent identities. Do not infer sharing from equal hashes.

For our fixed payload the independent expected SHA-256 is
`de8e2c4386f01529449f1714cfd6dedbc94e3d26a955b88da6bd1c7135c48ced`.
The write probe is illustrative and runs only in disposable test directories;
it is not an instruction to modify a real restored backup.

## Reproduce and verify

Requires GNU tar 1.35 and Python with tarfile's data extraction filter. Work
inside this directory. The harness accepts only an output pathname, never a
real source/backup path, and refuses to overwrite a result.

```sh
python3 experiment.py --output new-system.json
python3.12 experiment.py --output new-uv.json
python3 validate.py observation-system.json observation-uv.json replay-system.json replay-uv.json
python3 validate.py new-system.json
python3 validate.py new-uv.json
python3 compare_semantics.py observation-system.json new-system.json new-uv.json
python3 -m unittest -v test_experiment.py test_compare_semantics.py
python3.12 -m unittest -v test_experiment.py test_compare_semantics.py
python3 -O -m unittest -v test_experiment.py test_compare_semantics.py
python3.12 -O -m unittest -v test_experiment.py test_compare_semantics.py
```

Retained files contain 55 observations each: `observation-system.json`,
`observation-uv.json`, `replay-system.json`, `replay-uv.json`.
All four normalized matrices match exactly, including archive hashes, commands,
errors, payload decisions and identity/probe results. This strict same-environment check includes file permission modes. Timestamp and build metadata
are excluded from that equality check; the validator separately checks harness hashes.

The initial suite had 20 tests, passed in four build/mode configurations (80 test
executions). Each suite creates fresh fixtures. Tests include explicit matrix
coverage, wrong-generation acceptance rejection, missing/duplicate evidence
rejection, overwrite refusal and exact archive-byte equality.
Initial command results are retained in `validation.json`.

The publication review adds six validator mutation tests (26 tests total): missing
write probes, contradictory probe targets, inconsistent shared-file metadata,
missing identity, altered inventory and altered expected byte strings. The publication replay matched all 55 normalized rows on each build; 26 tests
passed on each build both normally and with optimization (104 test executions).
The separate extracted-bundle run passed another 26 tests. The native
observer and original captures are unchanged. Standalone validation checks
internal consistency; it cannot authenticate an observation without rerunning the
experiment or establish behavior beyond the tested builds.

## Comparing a different environment

The independent CPython 3.12.14 captures reproduce all 55 payload, archive,
command, exception, sharing and write-probe outcomes, with different permission
modes. The harness does not pin effective UID or umask. An additional replay
under umask 077 confirms that strict equality of permission modes is not an
appropriate cross-environment acceptance criterion for these measured outcomes.
The original captures remain unchanged; these are not new population samples.

Validate each new record individually, then use `compare_semantics.py`. It excludes
only timestamps, environment metadata and mode values at documented file-snapshot
paths from equality. It retains original file hashes, environment, timestamp and
harness identity in its report. All other values must match; missing mode fields
still fail comparison. It supplements, not replaces, evidence validation.
`test_compare_semantics.py` adds 11 tests for these exclusions and rejection of
changed content, archive identity, relationships, probe outcomes and provenance.
See `independent-byteexact-cpython31214.json` and its `-umask077` companion;
`review.md` describes the independent review's scope and transport correction.

## Scope and limitations

The original study is synthetic, benign, uncompressed USTAR on one Linux host;
the bounded independent replay adds a second host without broadening its inference. It tests regular
files and hard links, not ACLs, xattrs, ownership fidelity, cross-filesystem links,
Windows, libarchive, malicious paths, incremental archives, crashes or media
failure. The temporary filesystem reports the family label `ext2/ext3` through
`stat -f`; no more-specific filesystem identification is asserted.

There is no sampling population or failure-rate estimate, so confidence intervals
would be inappropriate. `data` filtering can alter metadata and is not a claim
of complete metadata restoration. Repeated results do not establish all-version
compatibility. Source version strings alone do not identify backported patches.

The protocol was written before the native runs, not externally preregistered.
`sources.json` distinguishes browser-reviewed sources from runtime hashes.
Direct GNU-site retrieval from the research host failed; no fetched-page hash
is invented. No third-party full text or figure is redistributed.

## Existing Hesela coverage to deepen

The [archive analysis](https://hesela.com/analyses/compressed-archives-dictionary-dependencies/)
already covers name identity, read coverage and TAR termination. This study adds
a distinct question: where do a selected link's bytes come from?
The [hard-link record](https://hesela.dev/terms/hard-link/) covers filesystem and
rsync sharing; the [archive-member record](https://hesela.dev/terms/archive-member/)
is the matching entry point for archive dependencies.
The companion analysis explains the practical recovery requirement; both corpus
records retain their stable identifiers.

## Overwrite-policy controls

A follow-up holds the target-first archive fixed and varies three GNU tar
policies (default, --keep-old-files, --skip-old-files), two selections (all
members, alias only), and two initial destinations (empty, stale target).
The twelve configurations run in fresh disposable directories with GNU tar 1.35.
The retained replay matches every field except the capture timestamp.

With a stale target and full extraction, default behavior restores the expected
bytes with status 0; --keep-old-files reports status 2, while --skip-old-files
reports status 0. Both preservation options leave the alias sharing stale bytes.
For alias-only extraction against the stale target, all three policies return
status 0 and stale bytes. No target overwrite is attempted in that selection.
Empty-destination full restores succeed; empty-destination alias-only restores
fail for all three policies.

Thus overwrite protection is not content-generation verification. The official
manual distinguishes the two policies' status handling; the link-generation
contrast above is our bounded observation, not a universal guarantee.
[GNU tar: Keep Old Files](https://www.gnu.org/software/tar/manual/html_node/Keep-Old-Files.html)

Run `python3 overwrite_controls.py --output new-overwrite.json` and
`python3 -B -m unittest -v test_overwrite_controls.py`.
Code, `overwrite-observations.json` and `overwrite-replay.json` retain binary,
harness and fixture hashes. The five-test suite recreates all twelve controls
and checks status, content and live identity against explicit requirements.
These are synthetic cases using one binary on one host, not additional
independent implementations, incidence estimates or the historical LISA suite.
Neither the original 55-row captures nor their observer was changed.

The final acceptance review also adds eight mutation tests to the original
validator: missing byte-return evidence, stdout inconsistency, impossible
return channels and non-Boolean outcomes now fail. The complete native suite
contains 50 tests including the semantic comparator and overwrite controls.
