Skip to content
Draft
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
598 changes: 531 additions & 67 deletions src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java

Large diffs are not rendered by default.

33 changes: 33 additions & 0 deletions src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,39 @@ public TarUnArchiver(File sourceFile) {
*/
private UntarCompressionMethod compression = UntarCompressionMethod.NONE;

private boolean failOnSymlinkTraversal;

/**
* Controls rejection of intermediate symbolic links in selected, mapped extraction paths.
* The default is {@code false}, allowing contained directory symlinks as GNU tar does.
* When enabled, destinations are checked before overwrite decisions or filesystem changes.
* An offending entry throws {@link ArchiverException}, leaving earlier extracted entries in place.
* The configured destination directory is trusted, and symbolic-link entries remain allowed.
* Existing destination-containment checks apply with either setting.
*
* @param failOnSymlinkTraversal whether intermediate symbolic links cause extraction to fail
* @since 5.0.0
*/
public void setFailOnSymlinkTraversal(boolean failOnSymlinkTraversal) {
this.failOnSymlinkTraversal = failOnSymlinkTraversal;
}

/**
* Returns whether intermediate symbolic links cause TAR extraction to fail.
*
* @return {@code true} when symlink traversal is rejected; {@code false} by default
* @since 5.0.0
*/
public boolean isFailOnSymlinkTraversal() {
return failOnSymlinkTraversal;
}

/** Applies the TAR traversal setting while the shared resolver examines the entry's parents. */
@Override
protected boolean rejectIntermediateSymlinks() {
return failOnSymlinkTraversal;
}

/**
* Set decompression algorithm to use; default=none.
* <p>
Expand Down
98 changes: 98 additions & 0 deletions src/site/markdown/extraction-paths.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Extraction paths and symbolic links

Extractors resolve existing path components before checking that output stays
inside the destination directory. Symbolic links are followed before processing
subsequent `..` components, including when the output file does not exist yet.
The same rules resolve the configured destination directory and classify it as
a file or directory.

For an existing root or entry parent, the resolver checks whether its spelling
matches its current physical directory. A match lets it skip the component
walk for that directory. Otherwise it walks the components and reuses cached
directories only after a fresh check of their filesystem identity without
following symbolic links. The cache lasts for one extraction. Resolution
stops after 64 symbolic-link expansions, rejecting cyclic or excessively long
paths.

## Archive formats and compatibility

TAR, including its compressed variants, and ZIP-based formats such as JAR,
WAR, and EAR use the shared entry extractor. The following behavior applies
with either setting of the TAR traversal option:

- When traversal is allowed, intermediate symbolic links are followed before
subsequent parent components are processed. Containment is checked even
when the destination leaf does not exist. The overwrite check and the write
both use the resolved destination.
- On Windows, a drive-relative mapper result such as `C:out\file` is relative
to the working directory of that drive. Its resolved destination must still
be inside the extraction directory.
- On Windows, an existing NTFS junction can serve as an extraction directory
when its resolved target is inside the extraction root. For example, if
`assets` is such a junction, both the directory entry `assets/` and the file
entry `assets/logo.png` are accepted. The file can also be extracted when
the archive omits the directory entry. A regular-file or symbolic-link entry
named `assets` cannot replace the junction. The same containment check
applies to the directory entry and to entries beneath it.
- With overwrite enabled (the default), a regular-file or symbolic-link entry
replaces an existing final symbolic link, including a dangling link. For
example, if `assets/logo.png` is a symlink, the archive entry becomes the
new `assets/logo.png` and the former target is untouched. With overwrite
disabled, a regular-file entry encountering a final symlink fails and a
symbolic-link entry keeps the existing link. A directory entry rejects a
final symlink with either setting. A directory entry selected for writing
over an existing regular file also fails.
- Symbolic links are created using the target stored in the archive. The
extractor skips permission changes for link entries and attempts to set the
modification time on the link itself. Link timestamps are best effort and
depend on filesystem support. The target's permissions and timestamps are
preserved.

Standalone GZIP, BZIP2, Snappy, XZ, and Zstandard extractors use the shared
destination validation and may report invalid destination paths during
validation. Each uses a format-specific stream copy to its configured output
file. The per-entry rules above apply to the archive readers.

## Optional TAR traversal policy

By default, TAR extractors allow intermediate directory symbolic links that
resolve inside the destination directory. To reject these paths, enable
`failOnSymlinkTraversal` before extraction:

```java
TarUnArchiver extractor = new TarUnArchiver(inputArchive);
extractor.setDestDirectory(outputDirectory);
extractor.setFailOnSymlinkTraversal(true);
extractor.extract();
```

The setting defaults to `false` and is inherited by compressed TAR extractors.
It is a TAR-specific API; the `UnArchiver` interface and provider configuration
interfaces do not expose it. Assembly's `archiverConfig` configures archivers,
rather than extractors.

With either setting, subclass extraction hooks receive the original entry name
and mapper array. The shared extractor applies each mapper once, in order,
then resolves the mapped name. If the filesystem cannot represent that name,
extraction throws an `ArchiverException` with the name and the underlying
`InvalidPathException`.

When enabled, the extractor checks selected, mapped output paths before
overwrite decisions or filesystem changes. It rejects intermediate symbolic
links, including existing links and links created by earlier archive entries.
An intermediate symbolic link appears before the path's last component.
Ordinary symbolic-link entries are still allowed. Excluded entries are skipped.

The configured destination directory is trusted even when its path contains
symbolic links or a symbolic link followed by `..`. Absolute mapped paths can
reach the root through an ancestor alias, such as `/var` referring to
`/private/var` on macOS. A separate alias pointing directly at the destination
root is accepted only in the configured root spelling. Once a path reaches the
root, further intermediate symbolic links are checked even if followed by `..`.
Harmless dot components in either root spelling do not bypass these checks.

An offending entry immediately throws `ArchiverException`, identifying the
archive entry, mapped destination, and symbolic link. Earlier output files can
remain in the destination directory. Physical containment is checked with
either setting; the policy does not require a preliminary archive scan or
temporary storage of archive payloads.
1 change: 1 addition & 0 deletions src/site/site.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<body>
<menu name="Overview">
<item name="Introduction" href="index.html"/>
<item name="Extraction Paths" href="extraction-paths.html"/>
<item name="Service Providers" href="providers.html"/>
<item name="Migration Guide" href="migration.html"/>
<item name="JavaDocs" href="apidocs/index.html"/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
/*
* Copyright 2026 The plexus developers.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.plexus.archiver;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;

import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

/** Changes directories between entries to ensure cached spellings never replace filesystem validation. */
class ExtractionPathCacheTest {
/** Temporary directory containing the extraction roots, link targets, and source fixture. */
@TempDir
Path temp;

/** A sequence of archive entries and filesystem changes to perform during one extraction. */
@FunctionalInterface
private interface Entries {
/**
* Runs the sequence against the active extractor.
*
* @param extractor the extractor whose directory cache is active
* @throws IOException if an entry or fixture operation fails
*/
void extract(Extractor extractor) throws IOException;
}

/** Exercises the shared extraction code with an in-memory entry stream. */
private static class Extractor extends AbstractUnArchiver {
/** The entry sequence supplied by the current test. */
Entries entries;

/** Runs the configured sequence and reports I/O failures as extraction failures. */
@Override
protected void execute() {
try {
entries.extract(this);
} catch (IOException e) {
throw new ArchiverException("Cannot extract fixture", e);
}
}

/**
* Runs the same fixture sequence through the explicit-directory extraction entry point.
*
* @param path the archive prefix supplied by the test
* @param outputDirectory the destination supplied by the test
*/
@Override
protected void execute(String path, File outputDirectory) {
execute();
}

/**
* Extracts a one-byte regular file into the configured destination.
*
* @param name the entry name passed to the shared extractor
* @throws IOException if resolving or writing the file fails
*/
void write(String name) throws IOException {
extractFile(
getSourceFile(),
getDestDirectory(),
new ByteArrayInputStream(new byte[] {1}),
name,
new Date(),
false,
null,
null,
null);
}

/**
* Starts an extraction through the selected public entry point.
*
* @param explicitDirectory whether to pass the configured destination to the extraction call
*/
void run(boolean explicitDirectory) {
if (explicitDirectory) {
extract("", getDestDirectory());
} else {
extract();
}
}
}

/**
* Configures a fixture extractor with a temporary source file.
*
* @param root the destination directory
* @return the extractor to which the test can assign an entry sequence
* @throws IOException if the temporary source file cannot be created
*/
private Extractor extractor(Path root) throws IOException {
Extractor extractor = new Extractor();
extractor.setDestDirectory(root.toFile());
extractor.setSourceFile(Files.createTempFile(temp, "source", ".archive").toFile());
return extractor;
}

/**
* Creates a symbolic link for the fixture, skipping the test if link creation is unavailable.
*
* @param link the path at which to create the link
* @param target the target stored in the link
* @throws IOException handled as a skipped test if link creation fails
*/
private void symlink(Path link, Path target) throws IOException {
try {
Files.createSymbolicLink(link, target);
} catch (IOException | UnsupportedOperationException e) {
assumeTrue(false, "Symbolic links unavailable: " + e);
}
}

/**
* Checks that replacing a previously used directory with a link cannot redirect the next write outside the root.
*
* @param explicitDirectory whether to pass the destination explicitly to the extraction call
* @throws Exception if the fixture cannot be prepared or inspected
*/
@ParameterizedTest
@ValueSource(booleans = {false, true})
void observesDirectoryReplacedBySymlinkWithinExtraction(boolean explicitDirectory) throws Exception {
Path root = Files.createDirectory(temp.resolve("root"));
Path outside = Files.createDirectory(temp.resolve("outside"));
Extractor extractor = extractor(root);
extractor.entries = current -> {
current.write("parent/first");
Files.move(root.resolve("parent"), root.resolve("saved"));
symlink(root.resolve("parent"), outside);
assertThrows(ArchiverException.class, () -> current.write("parent/new/file"));
assertArrayEquals(new byte[] {1}, Files.readAllBytes(root.resolve("saved/first")));
};
extractor.run(explicitDirectory);
try (var files = Files.list(outside)) {
assertEquals(0, files.count());
}
}

/**
* Checks that the next sibling resolves to the moved directory when its old name becomes a link.
*
* @param explicitDirectory whether to pass the destination explicitly to the extraction call
* @throws Exception if the fixture cannot be prepared or inspected
*/
@ParameterizedTest
@ValueSource(booleans = {false, true})
void resolvesExistingParentAgainAfterAncestorMoves(boolean explicitDirectory) throws Exception {
Path root = Files.createDirectory(temp.resolve("root"));
Path parent = Files.createDirectory(root.resolve("parent"));
Files.createDirectory(parent.resolve("nested"));
Extractor extractor = extractor(root);
extractor.entries = current -> {
current.write("parent/nested/first");
Path moved = Files.move(parent, root.resolve("moved"));
symlink(parent, moved);

Path sibling = current.resolveExtractionPath(root.toFile(), "parent/nested/second");
assertEquals(moved.resolve("nested").toRealPath().resolve("second"), sibling);
};
extractor.run(explicitDirectory);
}

/**
* Checks a formerly missing parent again when it appears as a symbolic link between entries.
*
* @param explicitDirectory whether to pass the destination explicitly to the extraction call
* @throws Exception if the fixture cannot be prepared or inspected
*/
@ParameterizedTest
@ValueSource(booleans = {false, true})
void observesPreviouslyMissingParent(boolean explicitDirectory) throws Exception {
Path root = Files.createDirectory(temp.resolve("root"));
Path outside = Files.createDirectory(temp.resolve("outside"));
Extractor extractor = extractor(root);
extractor.entries = current -> {
current.write("missing/../first");
symlink(root.resolve("missing"), outside);
assertThrows(ArchiverException.class, () -> current.write("missing/new/file"));
};
extractor.run(explicitDirectory);
try (var files = Files.list(outside)) {
assertEquals(0, files.count());
}
}

/**
* Verifies that a reused extractor observes the current link target after both failed and successful runs.
*
* @param explicitDirectory whether to pass the destination explicitly to the extraction call
* @throws Exception if the fixture cannot be prepared or inspected
*/
@ParameterizedTest
@ValueSource(booleans = {false, true})
void canReuseExtractorAfterFailureAndSuccess(boolean explicitDirectory) throws Exception {
Path root = Files.createDirectory(temp.resolve("root"));
Path first = Files.createDirectory(root.resolve("first"));
Path second = Files.createDirectory(root.resolve("second"));
Path outside = Files.createDirectory(temp.resolve("outside"));
Path link = root.resolve("link");
symlink(link, first);
Extractor extractor = extractor(root);
extractor.entries = current -> {
current.write("link/before");
Files.delete(link);
symlink(link, outside);
current.write("link/rejected");
};
assertThrows(ArchiverException.class, () -> extractor.run(explicitDirectory));
assertTrue(Files.exists(first.resolve("before")));

Files.delete(link);
symlink(link, second);
extractor.entries = current -> current.write("link/after");
extractor.run(explicitDirectory);
assertTrue(Files.exists(second.resolve("after")));

Files.delete(link);
symlink(link, first);
extractor.entries = current -> current.write("link/reused");
extractor.run(explicitDirectory);
assertTrue(Files.exists(first.resolve("reused")));
assertFalse(Files.exists(second.resolve("reused")));
try (var files = Files.list(outside)) {
assertEquals(0, files.count());
}
}
}
Loading