remaining = new ArrayDeque<>();
+ path.forEach(remaining::addLast);
+ int links = 0;
+ while (!remaining.isEmpty()) {
+ if (check != null) {
+ check.visitDirectory(current, remaining.size());
+ }
+ Path name = remaining.removeFirst();
+ if (name.toString().isEmpty() || name.toString().equals(".")) {
+ continue;
+ }
+ if (name.toString().equals("..")) {
+ if (current.getParent() != null) {
+ current = current.getParent();
+ }
+ continue;
+ }
+ Path candidate = current.resolve(name);
+ BasicFileAttributes attributes;
+ try {
+ attributes = Files.readAttributes(candidate, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+ } catch (NoSuchFileException ignored) {
+ current = candidate;
+ continue;
+ }
+ if (attributes.isSymbolicLink()) {
+ if (remaining.isEmpty() && use != PathUse.ROOT) {
+ return candidate;
+ }
+ if (check != null) {
+ check.followLink(candidate, remaining.size());
+ }
+ if (++links > 64) {
+ throw new FileSystemLoopException(path.toString());
+ }
+ // Resolve the target against the physical parent. Do not normalize away link/.. components.
+ Path target = current.resolve(Files.readSymbolicLink(candidate)).toAbsolutePath();
+ for (int i = target.getNameCount() - 1; i >= 0; i--) {
+ remaining.addFirst(target.getName(i));
+ }
+ current = target.getRoot();
+ } else if (IS_WINDOWS && attributes.isOther()) {
+ // Windows reports junctions as "other", and from JDK 26 they no longer report as directories.
+ current = candidate.toRealPath();
+ boolean directoryRequired = !remaining.isEmpty();
+ if (use != PathUse.ROOT
+ && remaining.stream()
+ .allMatch(component -> component.toString().equals("."))
+ && !current.equals(candidate.toRealPath(LinkOption.NOFOLLOW_LINKS))) {
+ if (use != PathUse.DIRECTORY_ENTRY) {
+ throw new ArchiverException(
+ "Cannot extract to a redirected Windows reparse point (" + candidate + ")");
+ }
+ directoryRequired = true;
+ }
+ if (directoryRequired
+ && !Files.readAttributes(current, BasicFileAttributes.class)
+ .isDirectory()) {
+ throw new NotDirectoryException(candidate.toString());
+ }
+ } else {
+ if (!remaining.isEmpty() && !attributes.isDirectory()) {
+ throw new NotDirectoryException(candidate.toString());
+ }
+ // With no unresolved parent links or dots, this also handles Windows casing and short names.
+ current = resolveDirectory(candidate, attributes);
+ }
+ }
+ return current;
+ }
+
+ /**
+ * Checks whether the directory spelling exactly matches its current real path, including case on Windows.
+ *
+ * @param directory the absolute path of the root or entry parent
+ * @return {@code true} if the path names a directory with that spelling and the component walk can be skipped
+ */
+ private static boolean isOrdinaryDirectory(Path directory) {
+ try {
+ Path real = directory.toRealPath();
+ // Windows Path.equals folds case; on Unix it compares the underlying filename bytes.
+ boolean sameSpelling = IS_WINDOWS ? directory.toString().equals(real.toString()) : directory.equals(real);
+ return sameSpelling && Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS);
+ } catch (IOException ignored) {
+ // The walk handles missing components, link expansion limits, and filesystem-specific errors.
+ return false;
+ }
+ }
+
+ /**
+ * Resolves one existing component. An ordinary directory's real path can be reused when the
+ * freshly read file key matches the cached identity.
+ *
+ * @param candidate the component under its resolved parent
+ * @param attributes the attributes read without following the final link
+ * @return the component's real path
+ * @throws IOException if the real path cannot be obtained
+ */
+ private Path resolveDirectory(Path candidate, BasicFileAttributes attributes) throws IOException {
+ Object key = attributes.fileKey();
+ // Reparse points and providers without file identities need fresh resolution. Do not cache file leaves.
+ if (resolvedDirectories == null || !attributes.isDirectory() || attributes.isOther() || key == null) {
+ return candidate.toRealPath();
+ }
+ ResolvedDirectory cached = resolvedDirectories.get(candidate);
+ if (cached != null && key.equals(cached.fileKey())) {
+ return cached.path();
+ }
+ Path resolved = candidate.toRealPath();
+ // Only retain spellings that already match the resolved path; aliases still need fresh resolution.
+ if (candidate.equals(resolved)) {
+ resolvedDirectories.put(candidate, new ResolvedDirectory(key, resolved));
+ if (resolvedDirectories.size() > 1024) {
+ var oldest = resolvedDirectories.keySet().iterator();
+ oldest.next();
+ oldest.remove();
+ }
+ } else {
+ resolvedDirectories.remove(candidate);
+ }
+ return resolved;
+ }
+
/**
* Creates a symbolic link. Visible for testing, so a test can simulate a file system that refuses links.
*
@@ -371,18 +771,69 @@ protected void createSymbolicLink(File link, File target) throws IOException {
}
/**
+ * Writes a file or symbolic link. When replacing a final symlink, finish the new entry beside it before
+ * moving it into place. A sibling also gives a relative link target the same parent during creation.
+ *
+ * @param directory the configured extraction root
+ * @param destination the resolved output path
+ * @param contents the regular file contents
+ * @param target the archived target, or null or empty for a regular file
+ * @param entryName the mapped name for diagnostics
+ * @param replaceLink whether the existing final symlink is to be replaced
+ * @return whether the entry was written
+ * @throws IOException if writing or installing the entry fails
+ */
+ private boolean writeFileOrSymlink(
+ File directory,
+ Path destination,
+ InputStream contents,
+ String target,
+ String entryName,
+ boolean replaceLink)
+ throws IOException {
+ Path output = replaceLink ? Files.createTempFile(destination.getParent(), ".plexus-", ".tmp") : destination;
+ try {
+ if (StringUtils.isEmpty(target)) {
+ Files.copy(contents, output, REPLACE_EXISTING);
+ } else {
+ if (replaceLink) {
+ Files.delete(output);
+ }
+ if (!createSymlinkEntry(resolveExtractionRoot(directory), output, destination, target, entryName)) {
+ return false;
+ }
+ }
+ if (replaceLink) {
+ Files.move(output, destination, REPLACE_EXISTING);
+ }
+ return true;
+ } finally {
+ if (replaceLink) {
+ Files.deleteIfExists(output);
+ }
+ }
+ }
+
+ /**
+ * @param root the physical extraction root
+ * @param output the path at which to create the link
+ * @param destination the final path for a deferred copy
+ * @param target the archived link target
+ * @param entryName the mapped name for diagnostics
* @return {@code true} if the link exists on disk, {@code false} if it was skipped or deferred
+ * @throws IOException if the failure mode requires extraction to fail
*/
- private boolean createSymlinkEntry(Path root, File link, String target, String entryName) throws IOException {
+ private boolean createSymlinkEntry(Path root, Path output, Path destination, String target, String entryName)
+ throws IOException {
try {
- createSymbolicLink(link, new File(target));
+ createSymbolicLink(output.toFile(), new File(target));
return true;
} catch (IOException | UnsupportedOperationException e) {
if (symlinkFailureMode == SymlinkFailureMode.FAIL) {
if (e instanceof IOException) {
throw (IOException) e;
}
- throw new IOException("Cannot create symbolic link " + link, e);
+ throw new IOException("Cannot create symbolic link " + destination, e);
}
boolean copy = symlinkFailureMode == SymlinkFailureMode.COPY_TARGET && deferredSymlinks != null;
getLogger()
@@ -394,7 +845,7 @@ private boolean createSymlinkEntry(Path root, File link, String target, String e
e.getMessage(),
copy ? "the link target will be copied instead" : "the entry is skipped");
if (copy) {
- deferredSymlinks.add(root, link, target, entryName);
+ deferredSymlinks.add(root, destination.toFile(), target, entryName);
}
return false;
}
@@ -429,24 +880,20 @@ protected boolean shouldExtractEntry(File targetDirectory, File targetFileName,
return true;
}
- boolean entryIsDirectory =
- entryName.endsWith("/"); // directory entries always end with '/', regardless of the OS.
- String canonicalDestPath = targetFileName.getCanonicalPath();
- String suffix = (entryIsDirectory ? "/" : "");
- String relativeCanonicalDestPath =
- canonicalDestPath.replace(targetDirectory.getCanonicalPath() + File.separatorChar, "") + suffix;
+ Path requestedPath = resolveExtractionRoot(targetDirectory).resolve(mappedEntryPath(entryName));
+ String requestedName = requestedPath.toString();
+ String existingName =
+ existingEntrySpelling(requestedPath, targetFileName.toPath()).toString();
boolean fileOnDiskIsOlderThanEntry = targetFileName.lastModified() < entryDate.getTime();
- boolean differentCasing =
- !normalizedFileSeparator(entryName).equals(normalizedFileSeparator(relativeCanonicalDestPath));
// Warn for case (4) and (5) if the file system is case-insensitive
- if (differentCasing) {
+ if (!requestedName.equals(existingName) && requestedName.equalsIgnoreCase(existingName)) {
String casingMessage = String.format(
Locale.ENGLISH,
"Archive entry '%s' and existing file '%s' names differ only by case."
+ " This may lead to an unexpected outcome on case-insensitive filesystems.",
entryName,
- canonicalDestPath);
+ existingName);
getLogger().warn(casingMessage);
casingMessageEmitted.incrementAndGet();
}
@@ -456,7 +903,24 @@ protected boolean shouldExtractEntry(File targetDirectory, File targetFileName,
return isOverwrite() || fileOnDiskIsOlderThanEntry;
}
- private String normalizedFileSeparator(String pathOrEntry) {
- return pathOrEntry.replace("/", File.separator);
+ /**
+ * Looks up the spelling used on disk for the case-mismatch warning. On Windows the lookup keeps
+ * junction names in the requested path. If that spelling cannot be looked up, it uses the resolved destination.
+ *
+ * @param requestedPath the path with the spelling supplied by the entry or mapper
+ * @param destination the existing destination selected by the resolver
+ * @return the path spelling to compare with the requested name
+ * @throws IOException if the destination spelling cannot be determined
+ */
+ private Path existingEntrySpelling(Path requestedPath, Path destination) throws IOException {
+ if (IS_WINDOWS) {
+ try {
+ // Look up each name as stored on disk, keeping the junction name in the path.
+ return requestedPath.toRealPath(LinkOption.NOFOLLOW_LINKS);
+ } catch (IOException ignored) {
+ // A mapped name such as missing/../file may exist only at its resolved destination.
+ }
+ }
+ return resolvePath(destination, PathUse.OTHER_ENTRY);
}
}
diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java
index de73c106..b601b336 100644
--- a/src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java
+++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java
@@ -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.
*
diff --git a/src/site/markdown/extraction-paths.md b/src/site/markdown/extraction-paths.md
new file mode 100644
index 00000000..7214c51e
--- /dev/null
+++ b/src/site/markdown/extraction-paths.md
@@ -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.
diff --git a/src/site/site.xml b/src/site/site.xml
index dd5b761c..4e34d884 100644
--- a/src/site/site.xml
+++ b/src/site/site.xml
@@ -4,6 +4,7 @@