diff --git a/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java index e117800a..85471ef4 100644 --- a/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java @@ -20,12 +20,24 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.nio.file.FileSystemLoopException; import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +import java.nio.file.NotDirectoryException; import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Date; +import java.util.Deque; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.codehaus.plexus.archiver.util.ArchiveEntryUtils; @@ -34,7 +46,7 @@ import org.codehaus.plexus.components.io.filemappers.FileMapper; import org.codehaus.plexus.components.io.fileselectors.FileSelector; import org.codehaus.plexus.components.io.resources.PlexusIoResource; -import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,6 +59,9 @@ * @author Emmanuel Venisse */ public abstract class AbstractUnArchiver implements UnArchiver, FinalizerEnabled { + /** Whether to apply Windows-specific path and reparse point handling. */ + private static final boolean IS_WINDOWS = Os.isFamily(Os.FAMILY_WINDOWS); + private final Logger logger = LoggerFactory.getLogger(getClass()); protected Logger getLogger() { @@ -65,6 +80,17 @@ protected Logger getLogger() { private List finalizers; + /** Directory spellings are reused only after a fresh NOFOLLOW identity check, within one extraction. */ + private Map resolvedDirectories; + + /** + * A directory whose real path can be reused during the current extraction. + * + * @param fileKey the filesystem identity checked on each cache lookup + * @param path the real path observed for that identity + */ + private record ResolvedDirectory(Object fileKey, Path path) {} + private FileSelector[] fileSelectors; /** @@ -142,32 +168,42 @@ public void setFileMappers(final FileMapper[] fileMappers) { @Override public final void extract() throws ArchiverException { - validate(); - deferredSymlinks = new DeferredSymlinks(getLogger()); + resolvedDirectories = new LinkedHashMap<>(16, 0.75f, true); try { - execute(); - deferredSymlinks.resolve(); - } catch (IOException e) { - throw new ArchiverException("Error while copying symbolic link targets", e); + validate(); + deferredSymlinks = new DeferredSymlinks(getLogger()); + try { + execute(); + deferredSymlinks.resolve(); + } catch (IOException e) { + throw new ArchiverException("Error while copying symbolic link targets", e); + } finally { + deferredSymlinks = null; + } + runArchiveFinalizers(); } finally { - deferredSymlinks = null; + resolvedDirectories = null; } - runArchiveFinalizers(); } @Override public final void extract(final String path, final File outputDirectory) throws ArchiverException { - validate(path, outputDirectory); - deferredSymlinks = new DeferredSymlinks(getLogger()); + resolvedDirectories = new LinkedHashMap<>(16, 0.75f, true); try { - execute(path, outputDirectory); - deferredSymlinks.resolve(); - } catch (IOException e) { - throw new ArchiverException("Error while copying symbolic link targets", e); + validate(path, outputDirectory); + deferredSymlinks = new DeferredSymlinks(getLogger()); + try { + execute(path, outputDirectory); + deferredSymlinks.resolve(); + } catch (IOException e) { + throw new ArchiverException("Error while copying symbolic link targets", e); + } finally { + deferredSymlinks = null; + } + runArchiveFinalizers(); } finally { - deferredSymlinks = null; + resolvedDirectories = null; } - runArchiveFinalizers(); } @Override @@ -215,14 +251,19 @@ protected void validate() throws ArchiverException { throw new ArchiverException("You must choose between a destination directory and a destination file."); } - if (destDirectory != null && !destDirectory.isDirectory()) { - destFile = destDirectory; - destDirectory = null; - } + try { + // Use the same link/.. semantics for classification and extraction, retaining the configured spelling. + if (destDirectory != null && !Files.isDirectory(resolveExtractionRoot(destDirectory))) { + destFile = destDirectory; + destDirectory = null; + } - if (destFile != null && destFile.isDirectory()) { - destDirectory = destFile; - destFile = null; + if (destFile != null && Files.isDirectory(resolveExtractionRoot(destFile))) { + destDirectory = destFile; + destFile = null; + } + } catch (IOException e) { + throw new ArchiverException("Cannot resolve extraction destination", e); } } @@ -303,29 +344,21 @@ protected void extractFile( String symlinkDestination, final FileMapper[] fileMappers) throws IOException, ArchiverException { + String archiveName = entryName; if (fileMappers != null) { for (final FileMapper fileMapper : fileMappers) { entryName = fileMapper.getMappedFileName(entryName); } } - // Hmm. Symlinks re-evaluate back to the original file here. Unsure if this is a good thing... - final File targetFileName = FileUtils.resolveFile(dir, entryName); - - // Make sure that the resolved path of the extracted file doesn't escape the destination directory - // getCanonicalFile().toPath() is used instead of getCanonicalPath() (returns String), - // because "/opt/directory".startsWith("/opt/dir") would return false negative. - Path canonicalDirPath = dir.getCanonicalFile().toPath(); - Path canonicalDestPath = targetFileName.getCanonicalFile().toPath(); - - if (!canonicalDestPath.startsWith(canonicalDirPath)) { - throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")"); - } - - // don't allow override target symlink by standard file - if (StringUtils.isEmpty(symlinkDestination) && Files.isSymbolicLink(canonicalDestPath)) { + final boolean symlink = !StringUtils.isEmpty(symlinkDestination); + PathUse use = isDirectory && !symlink ? PathUse.DIRECTORY_ENTRY : PathUse.OTHER_ENTRY; + final Path destination = resolveExtractionPath(dir, entryName, use, archiveName); + boolean finalSymlink = Files.isSymbolicLink(destination); + if (finalSymlink && !symlink && (isDirectory || !isOverwrite())) { throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")"); } + final File targetFileName = destination.toFile(); try { if (!shouldExtractEntry(dir, targetFileName, entryName, entryDate)) { @@ -333,24 +366,38 @@ protected void extractFile( } // create intermediary directories - sometimes zip don't add them - final File dirF = targetFileName.getParentFile(); - if (dirF != null) { - dirF.mkdirs(); + if (destination.getParent() != null) { + Files.createDirectories(destination.getParent()); + } + + if (isDirectory && !symlink) { + Files.createDirectories(destination); + } else if (!writeFileOrSymlink( + dir, + destination, + compressedInputStream, + symlinkDestination, + entryName, + finalSymlink && isOverwrite())) { + return; } - if (!StringUtils.isEmpty(symlinkDestination)) { - if (!createSymlinkEntry(canonicalDirPath, targetFileName, symlinkDestination, entryName)) { - return; + if (symlink) { + // A link can point outside the extraction root. Never change its target's metadata. + if (Files.isSymbolicLink(destination)) { + try { + BasicFileAttributeView attributes = Files.getFileAttributeView( + destination, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); + attributes.setTimes(FileTime.fromMillis(entryDate.getTime()), null, null); + } catch (IOException | UnsupportedOperationException ignored) { + // Link timestamps are best effort, like File.setLastModified for ordinary entries. + } } - } else if (isDirectory) { - targetFileName.mkdirs(); } else { - Files.copy(compressedInputStream, targetFileName.toPath(), REPLACE_EXISTING); + targetFileName.setLastModified(entryDate.getTime()); } - targetFileName.setLastModified(entryDate.getTime()); - - if (!isIgnorePermissions() && mode != null && !isDirectory) { + if (!symlink && !isIgnorePermissions() && mode != null && !isDirectory) { ArchiveEntryUtils.chmod(targetFileName, mode); } } catch (final FileNotFoundException ex) { @@ -358,6 +405,359 @@ protected void extractFile( } } + /** + * Resolves the trusted root, following each link before processing subsequent parent components. + * @param directory the configured root, whose original spelling remains available to extraction hooks + * @return the physical root, including any not-yet-existing suffix + * @throws IOException if an existing component cannot be resolved + */ + protected final Path resolveExtractionRoot(File directory) throws IOException { + return resolvePath(directory.toPath(), PathUse.ROOT); + } + + /** + * Resolves an entry's parents and checks containment, leaving a final symlink for entry-type validation. + * @param directory the trusted extraction root + * @param name the mapped destination name + * @return a contained physical path without following its final symbolic link + * @throws IOException if an existing component cannot be resolved + * @throws ArchiverException if the name is invalid, the destination is outside the root, the reader rejects + * an intermediate symbolic link, or the destination ends at a redirected Windows reparse point + */ + protected final Path resolveExtractionPath(File directory, String name) throws IOException { + return resolveExtractionPath(directory, name, PathUse.OTHER_ENTRY, name); + } + + /** + * Allows an archive reader to reject intermediate symbolic links in selected entry destinations. + * + * @return whether mapped entry paths are subject to strict traversal checks + */ + protected boolean rejectIntermediateSymlinks() { + return false; + } + + /** Tracks which components of a single mapped entry are subject to strict traversal. */ + private static final class TraversalCheck { + private final Path root; + private final String archiveName; + private final String mappedName; + private int suffixLength; + private boolean reachedRoot; + private Path ancestorAlias; + + /** The suffix starts after any trusted spelling of the configured extraction directory. */ + private TraversalCheck(Path root, String archiveName, String mappedName, int suffixLength) { + this.root = root; + this.archiveName = archiveName; + this.mappedName = mappedName; + this.suffixLength = suffixLength; + } + + /** + * When the walk resumes the entry suffix, verify where its ancestor alias landed. + * The remaining component count includes the next name to visit. + */ + private void visitDirectory(Path directory, int remaining) { + if (remaining > suffixLength) { + return; + } + if (ancestorAlias != null) { + if (directory.equals(root) || !root.startsWith(directory)) { + throw rejected(ancestorAlias); + } + ancestorAlias = null; + } + // A later ".." cannot make ancestor aliases trusted again. + reachedRoot |= directory.equals(root); + } + + /** + * Reject an entry's intermediate link, allowing aliases of strict ancestors on the way to the root. + * The remaining component count excludes the link and its as-yet unexpanded target. + */ + private void followLink(Path link, int remaining) { + if (remaining < suffixLength) { + if (reachedRoot) { + throw rejected(link); + } + // Resolve the target in the same walk. Resume checking when only the original suffix remains. + ancestorAlias = link; + suffixLength = remaining; + } + } + + /** Reports the intermediate link along with both spellings of the entry. */ + private ArchiverException rejected(Path link) { + return new ArchiverException("Cannot extract entry '" + archiveName + "': destination '" + mappedName + + "' traverses symbolic link '" + link + "'"); + } + } + + /** Determines how to handle a symbolic link or Windows reparse point at the final component. */ + private enum PathUse { + /** Follow the configured extraction root to its physical location. */ + ROOT, + /** Preserve a final symbolic link for validation and allow a junction to an existing directory. */ + DIRECTORY_ENTRY, + /** Preserve a final symbolic link for validation and reject a redirected Windows reparse point. */ + OTHER_ENTRY + } + + /** + * Parses a mapped name using either slash for absolute paths and native separators for relative paths. + * Windows drive-relative names use the working directory of the named drive. + * + * @param name the entry name after applying file mappers + * @return the parsed path, which may still be relative to the extraction root + * @throws ArchiverException if the host cannot represent the name + */ + private static Path mappedEntryPath(String name) { + Path entry; + try { + // Preserve the previous resolver's portable absolute names and platform-native relative names. + Path portable = Path.of(name.replace('/', File.separatorChar).replace('\\', File.separatorChar)); + if (portable.isAbsolute()) { + return portable; + } + entry = Path.of(name); + } catch (InvalidPathException e) { + throw new ArchiverException("Invalid archive entry name (" + name + ")", e); + } + Path entryRoot = entry.getRoot(); + // A Windows drive-relative name (C:file) starts at that drive's working directory. + if (entryRoot != null && entryRoot.toString().endsWith(":")) { + return entry.toAbsolutePath(); + } + return entry; + } + + /** + * Resolves a mapped entry against the physical extraction root and verifies containment. + * + * @param directory the configured extraction root + * @param name the mapped entry name + * @param use how to handle the entry's final component + * @param archiveName the original archive member name for traversal diagnostics + * @return the resolved destination inside or equal to the extraction root + * @throws IOException if the root or an existing component cannot be resolved + * @throws ArchiverException if the name is invalid, the destination is outside the root, the reader rejects + * an intermediate symbolic link, or the entry would replace a redirected Windows reparse point + */ + private Path resolveExtractionPath(File directory, String name, PathUse use, String archiveName) + throws IOException { + Path root = resolveExtractionRoot(directory); + Path entry = mappedEntryPath(name); + // Only rootless entries can start at the resolved root. Windows rooted paths can be non-absolute. + boolean rooted = entry.getRoot() != null; + Path path = rooted ? root.resolve(entry) : entry; + TraversalCheck check = null; + if (rejectIntermediateSymlinks()) { + int prefix = + rooted ? trustedRootPrefixLength(path, directory.toPath().toAbsolutePath()) : 0; + check = new TraversalCheck(root, archiveName, name, path.getNameCount() - prefix); + } + Path destination = resolvePath(rooted ? path.getRoot() : root, path, use, check); + if (!destination.startsWith(root)) { + throw new ArchiverException("Entry is outside of the target directory (" + name + ")"); + } + return destination; + } + + /** + * Matches an absolute configured root while ignoring harmless dot components in either spelling. + * Parent components are compared literally so symlinks preceding {@code ..} retain their meaning. + * + * @param path the absolute mapped path whose suffix must remain unchanged + * @param root the absolute configured destination before filesystem resolution + * @return the number of components covered by the configured root, or zero when the prefix does not match + */ + private static int trustedRootPrefixLength(Path path, Path root) { + if (!root.getRoot().equals(path.getRoot())) { + return 0; + } + int next = 0; + for (Path component : root) { + if (component.toString().equals(".")) { + continue; + } + // Skip dots only while matching the trusted prefix; preserve every component of the remaining suffix. + while (next < path.getNameCount() && path.getName(next).toString().equals(".")) { + next++; + } + if (next == path.getNameCount() || !component.equals(path.getName(next))) { + return 0; + } + next++; + } + return next; + } + + /** + * Resolves a path starting at its filesystem root. Intermediate links are followed before processing + * a subsequent {@code ..}, even when the leaf is missing. + * + * @param path the path to resolve, relative to the working directory if necessary + * @param use how to handle the final component + * @return the resolved absolute path, including any missing suffix + * @throws IOException if an existing component cannot be resolved + * @throws ArchiverException if the entry would replace a redirected Windows reparse point + */ + private Path resolvePath(Path path, PathUse use) throws IOException { + Path absolute = path.toAbsolutePath(); + return resolvePath(absolute.getRoot(), absolute, use, null); + } + + /** + * Resolves the name components from a known physical prefix. An ordinary existing directory can be + * verified in one real-path lookup. The component walk handles aliases, missing parents and the + * entry's final component. + * + * @param current the physical starting directory or filesystem root + * @param path the path whose name components remain to be resolved + * @param use how to handle the final component + * @param check the strict traversal check for this entry, or {@code null} to follow intermediate links + * @return the resolved absolute path, including any missing suffix + * @throws IOException if a parent is not a directory, the link expansion limit is exceeded, + * or an existing component cannot be resolved + * @throws ArchiverException if the reader rejects an intermediate symbolic link or the entry would + * replace a redirected Windows reparse point + */ + private Path resolvePath(Path current, Path path, PathUse use, TraversalCheck check) throws IOException { + Path prefix = use == PathUse.ROOT ? path : path.getParent(); + if (prefix != null) { + Path directory = current.resolve(prefix); + if (isOrdinaryDirectory(directory)) { + if (use == PathUse.ROOT) { + return directory; + } + current = directory; + path = path.getFileName(); + } + } + Deque 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 @@

+ diff --git a/src/test/java/org/codehaus/plexus/archiver/ExtractionPathCacheTest.java b/src/test/java/org/codehaus/plexus/archiver/ExtractionPathCacheTest.java new file mode 100644 index 00000000..70e88d3e --- /dev/null +++ b/src/test/java/org/codehaus/plexus/archiver/ExtractionPathCacheTest.java @@ -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()); + } + } +} diff --git a/src/test/java/org/codehaus/plexus/archiver/ExtractionPathTest.java b/src/test/java/org/codehaus/plexus/archiver/ExtractionPathTest.java new file mode 100644 index 00000000..a2415c0f --- /dev/null +++ b/src/test/java/org/codehaus/plexus/archiver/ExtractionPathTest.java @@ -0,0 +1,948 @@ +/* + * 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.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystemLoopException; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.LinkOption; +import java.nio.file.NotDirectoryException; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.FileTime; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Arrays; +import java.util.Date; +import java.util.stream.Stream; +import java.util.zip.GZIPOutputStream; + +import org.apache.commons.compress.archivers.ArchiveEntry; +import org.apache.commons.compress.archivers.ArchiveOutputStream; +import org.apache.commons.compress.archivers.ArchiveStreamFactory; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.codehaus.plexus.archiver.gzip.GZipUnArchiver; +import org.codehaus.plexus.archiver.jar.JarUnArchiver; +import org.codehaus.plexus.archiver.tar.TarUnArchiver; +import org.codehaus.plexus.archiver.zip.ZipUnArchiver; +import org.codehaus.plexus.components.io.filemappers.FileMapper; +import org.codehaus.plexus.util.Os; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** Exercises the shared path policy through both archive readers and the protected extraction hook. */ +class ExtractionPathTest { + /** The modification time assigned to fixture entries, in milliseconds since the epoch. */ + private static final long ENTRY_TIME_MILLIS = 1234567000000L; + + /** The extraction entry point exercised by a fixture. */ + enum Format { + /** The protected extraction hook, supplied with an in-memory member. */ + SHARED, + /** The TAR reader. */ + TAR, + /** The ZIP reader. */ + ZIP, + /** The JAR reader, using a ZIP-format fixture. */ + JAR + } + + /** The archive member type written by the fixture. */ + enum Kind { + /** A regular file with UTF-8 content. */ + FILE, + /** A directory entry. */ + DIRECTORY, + /** A symbolic link whose value specifies its target. */ + SYMLINK + } + + /** Temporary directory for archives, extraction roots, and link targets. */ + @TempDir + Path temp; + + /** + * Supplies ordinary entry types for each extraction entry point. + * + * @return the combinations of format and regular-file or directory entry + */ + private static Stream ordinaryEntries() { + return Arrays.stream(Format.values()) + .flatMap(format -> Stream.of(Kind.FILE, Kind.DIRECTORY).map(kind -> Arguments.of(format, kind))); + } + + /** + * Supplies final-link collisions for both overwrite settings. + * + * @return the format, entry type, target location, and overwrite setting + */ + private static Stream finalLinks() { + return Arrays.stream(Format.values()).flatMap(format -> Arrays.stream(Kind.values()) + .flatMap(kind -> Stream.of("inside", "outside", "missing").flatMap(target -> Stream.of(false, true) + .map(overwrite -> Arguments.of(format, kind, target, overwrite))))); + } + + /** + * Supplies Windows paths rooted on the current drive with each supported slash spelling. + * + * @return the format, slash spelling, and whether the mapped path is inside the root + */ + private static Stream windowsRootedMappings() { + return Arrays.stream(Format.values()) + .flatMap(format -> Stream.of("rooted", "rooted-forward").flatMap(spelling -> Stream.of(false, true) + .map(contained -> Arguments.of(format, spelling, contained)))); + } + + /** + * 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); + } + } + + /** + * Creates an NTFS directory junction named {@code assets} using the native Windows command. + * + * @param directory the directory in which to create the junction + * @param target the directory to which the junction will point + * @return the junction path + * @throws IOException if the file store cannot be inspected or the command cannot be started or read + * @throws InterruptedException if interrupted while waiting for the command + */ + private Path assetsJunction(Path directory, Path target) throws IOException, InterruptedException { + assumeTrue("NTFS".equalsIgnoreCase(Files.getFileStore(directory).type()), "Requires an NTFS volume"); + Process mklink = new ProcessBuilder( + "cmd.exe", + "/d", + "/c", + "mklink", + "/j", + "assets", + directory.relativize(target).toString()) + .directory(directory.toFile()) + .redirectErrorStream(true) + .start(); + String output = new String(mklink.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + assertEquals(0, mklink.waitFor(), output); + return directory.resolve("assets"); + } + + /** + * Maps a neutral member name to the requested destination so the archive writer cannot rewrite it. + * + * @param format the extraction entry point to exercise + * @param root the extraction directory + * @param name the destination name returned by the fixture's mapper + * @param kind the archive member type + * @param value the file contents or symbolic-link target, ignored for directories + * @throws IOException if the archive fixture cannot be created or written + */ + private void extract(Format format, Path root, String name, Kind kind, String value) throws IOException { + String member = kind == Kind.DIRECTORY ? "member/" : "member"; + prepareMember(format, root, member, kind, value, ignored -> name).extract(); + } + + /** + * Builds a single-member fixture for the selected reader or shared extraction hook. + * + * @param format the extraction entry point to exercise + * @param root the extraction directory + * @param member the literal name passed to the archive writer or shared extraction hook + * @param kind the archive member type + * @param value the file contents or symbolic-link target, ignored for directories + * @param mappers the file mappers in application order + * @return the configured extractor + * @throws IOException if the archive fixture cannot be created + */ + private AbstractUnArchiver prepareMember( + Format format, Path root, String member, Kind kind, String value, FileMapper... mappers) + throws IOException { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + Path archive = Files.createTempFile(temp, "path", ".archive"); + AbstractUnArchiver extractor; + if (format == Format.TAR) { + try (TarArchiveOutputStream out = new TarArchiveOutputStream(Files.newOutputStream(archive))) { + byte type = (byte) (kind == Kind.FILE ? '0' : kind == Kind.DIRECTORY ? '5' : '2'); + TarArchiveEntry entry = new TarArchiveEntry(member, type); + entry.setModTime(ENTRY_TIME_MILLIS); + entry.setMode(0755); + if (kind == Kind.FILE) { + entry.setSize(bytes.length); + } else if (kind == Kind.SYMLINK) { + entry.setLinkName(value); + } + out.putArchiveEntry(entry); + if (kind == Kind.FILE) { + out.write(bytes); + } + out.closeArchiveEntry(); + } + extractor = new TarUnArchiver(); + } else if (format == Format.ZIP || format == Format.JAR) { + try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(Files.newOutputStream(archive))) { + ZipArchiveEntry entry = new ZipArchiveEntry(member); + entry.setUnixMode((kind == Kind.SYMLINK ? 0120000 : kind == Kind.DIRECTORY ? 0040000 : 0100000) | 0755); + entry.setTime(ENTRY_TIME_MILLIS); + out.putArchiveEntry(entry); + if (kind != Kind.DIRECTORY) { + out.write(bytes); + } + out.closeArchiveEntry(); + } + extractor = format == Format.JAR ? new JarUnArchiver() : new ZipUnArchiver(); + } else { + extractor = new AbstractUnArchiver() { + /** Passes the synthetic member and its metadata directly to the shared extraction hook. */ + @Override + protected void execute() { + try { + extractFile( + getSourceFile(), + getDestDirectory(), + new ByteArrayInputStream(bytes), + member, + new Date(ENTRY_TIME_MILLIS), + kind == Kind.DIRECTORY, + 0755, + kind == Kind.SYMLINK ? value : null, + getFileMappers()); + } catch (IOException e) { + throw new ArchiverException("Cannot extract fixture", e); + } + } + + /** + * Rejects partial extraction for this single-member fixture. + * + * @param path the requested archive prefix + * @param outputDirectory the requested destination directory + * @throws UnsupportedOperationException whenever partial extraction is requested + */ + @Override + protected void execute(String path, File outputDirectory) { + throw new UnsupportedOperationException(); + } + }; + } + extractor.setSourceFile(archive.toFile()); + extractor.setDestDirectory(root.toFile()); + extractor.setFileMappers(mappers); + return extractor; + } + + /** + * Checks that an invalid mapped name is reported with its original spelling and parsing cause. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource( + value = Format.class, + names = {"TAR", "ZIP"}) + void reportsInvalidMappedEntryName(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + String name = "dir/bad\0name"; + ArchiverException failure = + assertThrows(ArchiverException.class, () -> extract(format, root, name, Kind.FILE, "content")); + assertTrue(failure.getMessage().contains(name), failure::getMessage); + assertInstanceOf(InvalidPathException.class, failure.getCause()); + assertFalse(Files.exists(root.resolve("dir"))); + } + + /** + * Checks that a literal question mark is reported as invalid on Windows and preserved on Unix. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource( + value = Format.class, + names = {"TAR", "ZIP"}) + void handlesQuestionMarkInArchiveEntryName(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + String name = "dir/what?.txt"; + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + ArchiverException failure = + assertThrows(ArchiverException.class, () -> prepareMember(format, root, name, Kind.FILE, "content") + .extract()); + assertTrue(failure.getMessage().contains(name), failure::getMessage); + assertInstanceOf(InvalidPathException.class, failure.getCause()); + assertFalse(Files.exists(root.resolve("dir"))); + } else { + prepareMember(format, root, name, Kind.FILE, "content").extract(); + assertEquals("content", Files.readString(root.resolve(name))); + } + } + + /** + * A missing leaf must not hide the physical location of an existing symlinked parent on Windows. + * + * @param format the extraction entry point to exercise + * @param kind the archive member type + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @MethodSource("ordinaryEntries") + void rejectsOutsideParentBeforeCreatingDirectories(Format format, Kind kind) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path outside = Files.createDirectory(temp.resolve("outside")); + symlink(root.resolve("redirect"), outside); + assertThrows(ArchiverException.class, () -> extract(format, root, "redirect/new/entry", kind, "replacement")); + try (var files = Files.list(outside)) { + assertEquals(0, files.count()); + } + assertTrue(Files.isSymbolicLink(root.resolve("redirect"))); + } + + /** + * Checks that a link to an outside parent leaves its existing file intact. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void rejectsOutsideParentWithoutChangingExistingFile(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path outside = Files.createDirectory(temp.resolve("outside")); + Path file = Files.writeString(outside.resolve("file"), "original"); + symlink(root.resolve("redirect"), outside); + assertThrows(ArchiverException.class, () -> extract(format, root, "redirect/file", Kind.FILE, "replacement")); + assertEquals("original", Files.readString(file)); + } + + /** + * Directory creation must report a file collision instead of silently retaining the regular file. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void rejectsDirectoryOverExistingFile(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path file = Files.writeString(root.resolve("entry"), "original"); + Files.setLastModifiedTime(file, FileTime.fromMillis(1500000000000L)); + Throwable failure = + assertThrows(ArchiverException.class, () -> extract(format, root, "entry/", Kind.DIRECTORY, "")); + while (failure.getCause() != null) { + failure = failure.getCause(); + } + assertInstanceOf(java.nio.file.FileAlreadyExistsException.class, failure); + assertEquals("original", Files.readString(file)); + assertEquals(1500000000000L, Files.getLastModifiedTime(file).toMillis()); + } + + /** + * Checks that a regular file used as a parent produces a directory error and retains its contents. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void rejectsRegularFileAsParent(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path parent = Files.writeString(root.resolve("parent"), "original"); + + ArchiverException failure = + assertThrows(ArchiverException.class, () -> extract(format, root, "parent/file", Kind.FILE, "content")); + assertInstanceOf(NotDirectoryException.class, failure.getCause()); + assertEquals("original", Files.readString(parent)); + } + + /** + * Checks that GZIP reports a non-directory parent while validating the destination. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @Test + void gzipRejectsInvalidDestinationDuringSharedValidation() throws Exception { + Path source = temp.resolve("source.gz"); + try (GZIPOutputStream gzip = new GZIPOutputStream(Files.newOutputStream(source))) { + gzip.write("content".getBytes(StandardCharsets.UTF_8)); + } + Path parent = Files.writeString(temp.resolve("parent"), "original"); + GZipUnArchiver extractor = new GZipUnArchiver(source.toFile()); + extractor.setDestFile(parent.resolve("file").toFile()); + + ArchiverException failure = assertThrows(ArchiverException.class, extractor::extract); + assertEquals("Cannot resolve extraction destination", failure.getMessage()); + assertInstanceOf(NotDirectoryException.class, failure.getCause()); + assertEquals("original", Files.readString(parent)); + } + + /** + * Windows rooted paths can be non-absolute and must retain Path.resolve semantics through mappers. + * + * @param format the extraction entry point to exercise + * @param spelling the backslash or forward-slash spelling of the rooted path + * @param contained whether the mapped destination lies inside the extraction directory + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @MethodSource("windowsRootedMappings") + void preservesWindowsRootedMappings(Format format, String spelling, boolean contained) throws Exception { + assumeTrue(Os.isFamily(Os.FAMILY_WINDOWS), "Requires Windows path syntax"); + Path root = Files.createDirectory(temp.resolve("root")).toAbsolutePath(); + Path outside = Files.createDirectory(temp.resolve("outside")).toAbsolutePath(); + Path expected = (contained ? root : outside).resolve("file.txt"); + String rooted = "\\" + root.getRoot().relativize(expected); + String name = spelling.equals("rooted-forward") ? rooted.replace('\\', '/') : rooted; + Path path = Path.of(name); + assertFalse(path.isAbsolute()); + assertNotNull(path.getRoot()); + if (contained) { + extract(format, root, name, Kind.FILE, "content"); + assertEquals("content", Files.readString(expected)); + try (var files = Files.list(root)) { + assertEquals(1, files.count()); + } + } else { + assertThrows(ArchiverException.class, () -> extract(format, root, name, Kind.FILE, "content")); + assertFalse(Files.exists(expected)); + try (var files = Files.list(root)) { + assertEquals(0, files.count()); + } + } + try (var files = Files.list(outside)) { + assertEquals(0, files.count()); + } + } + + /** + * Checks contained and outside mappings when the drive's working directory differs from the extraction root. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnabledOnOs(OS.WINDOWS) + @EnumSource(Format.class) + void resolvesDriveRelativeMappingsFromDriveWorkingDirectory(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("out")).toAbsolutePath(); + String volume = root.getRoot().toString(); + assumeTrue(volume.length() == 3 && volume.charAt(1) == ':', "Requires a drive-letter destination"); + String drive = volume.substring(0, 2); + Path driveDirectory = Path.of(drive).toAbsolutePath(); + assertNotEquals(driveDirectory, root); + + Path expected = root.resolve("file.txt"); + String contained = drive + driveDirectory.relativize(expected); + extract(format, root, contained, Kind.FILE, "content"); + assertEquals("content", Files.readString(expected)); + + // A bare filename on the same drive is relative to the drive directory, outside the extraction root. + String bareName = temp.getFileName() + "-outside.txt"; + assertThrows(ArchiverException.class, () -> extract(format, root, drive + bareName, Kind.FILE, "content")); + assertFalse(Files.exists(root.resolve(bareName))); + } + + /** + * Both a safe root alias and a contained directory link must work with nonexistent descendants. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void acceptsAliasesWithMissingDescendants(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path real = Files.createDirectory(root.resolve("real")); + symlink(root.resolve("redirect"), Path.of("real")); + Path alias = temp.resolve("alias"); + symlink(alias, root); + extract(format, alias, "redirect/new/file", Kind.FILE, "relative"); + extract(format, alias, alias.resolve("redirect/other/file").toString(), Kind.FILE, "absolute"); + assertEquals("relative", Files.readString(real.resolve("new/file"))); + assertEquals("absolute", Files.readString(real.resolve("other/file"))); + } + + /** + * Checks that a file is written to the approved destination after its directory alias disappears. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @Test + void writesToDestinationApprovedByOverwriteCheck() throws Exception { + Path target = Files.createDirectory(temp.resolve("target")).toRealPath(); + Path alias = temp.resolve("assets"); + symlink(alias, target); + Path expected = target.resolve("new/logo.png"); + AbstractUnArchiver extractor = new ZipUnArchiver() { + /** + * Removes the directory alias after the overwrite check to verify which destination the writer uses. + * + * @param dir the configured extraction directory + * @param file the resolved destination supplied to the overwrite check + * @param entryName the mapped archive name + * @param entryDate the timestamp of the archive entry + * @return the overwrite decision for the resolved destination + * @throws IOException if the overwrite check or removal of the alias fails + */ + @Override + protected boolean shouldExtractEntry(File dir, File file, String entryName, Date entryDate) + throws IOException { + assertEquals(expected, file.toPath()); + boolean approved = super.shouldExtractEntry(dir, file, entryName, entryDate); + Files.delete(alias); + return approved; + } + }; + extractor.setOverwrite(false); + byte[] content = "logo".getBytes(StandardCharsets.UTF_8); + extractor.extractFile( + null, + temp.toFile(), + new ByteArrayInputStream(content), + "assets/new/logo.png", + new Date(ENTRY_TIME_MILLIS), + false, + null, + null, + null); + assertArrayEquals(content, Files.readAllBytes(expected)); + } + + /** + * Extracts a TAR or ZIP fixture containing {@code assets/logo.png}. + * + * @param format the TAR or ZIP reader to exercise + * @param root the extraction directory + * @param logo the source file to store as the logo + * @param explicitDirectory whether the archive includes an {@code assets/} directory entry + * @return the extractor so its case-mismatch warning count can be inspected + * @throws IOException if the archive fixture cannot be created or written + */ + private AbstractUnArchiver extractAssets(Format format, Path root, Path logo, boolean explicitDirectory) + throws IOException { + Path archive = Files.createTempFile(temp, "assets", ".archive"); + try (var bytes = Files.newOutputStream(archive); + ArchiveOutputStream out = + ArchiveStreamFactory.DEFAULT.createArchiveOutputStream(format.name(), bytes)) { + if (explicitDirectory) { + out.putArchiveEntry(out.createArchiveEntry(logo.getParent(), "assets/")); + out.closeArchiveEntry(); + } + out.putArchiveEntry(out.createArchiveEntry(logo, "assets/logo.png")); + Files.copy(logo, out); + out.closeArchiveEntry(); + } + AbstractUnArchiver extractor = format == Format.TAR ? new TarUnArchiver() : new ZipUnArchiver(); + extractor.setSourceFile(archive.toFile()); + extractor.setDestDirectory(root.toFile()); + extractor.extract(); + return extractor; + } + + /** + * Checks extraction and case warnings for a nested file with and without an explicit parent entry. + * + * @param format the extraction entry point to exercise + * @param useJunction whether the existing parent is an NTFS junction + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @CsvSource({"TAR, false", "ZIP, false", "TAR, true", "ZIP, true"}) + void extractsAssetsWithAndWithoutDirectoryEntry(Format format, boolean useJunction) throws Exception { + assumeTrue(!useJunction || Os.isFamily(Os.FAMILY_WINDOWS), "Requires Windows for the junction case"); + Path root = Files.createDirectory(temp.resolve("root")); + Path target = Files.createDirectory(root.resolve(useJunction ? "target" : "assets")); + Path assets = useJunction ? assetsJunction(root, target) : target; + try { + for (boolean explicitDirectory : new boolean[] {false, true}) { + Path logo = Files.writeString(temp.resolve("logo.png"), explicitDirectory ? "explicit" : "implicit"); + AbstractUnArchiver extractor = extractAssets(format, root, logo, explicitDirectory); + assertEquals(0, extractor.casingMessageEmitted.get()); + assertTrue(Files.isSameFile(assets, target)); + assertEquals(Files.readString(logo), Files.readString(target.resolve("logo.png"))); + } + } finally { + if (useJunction) { + Files.delete(assets); + } + } + } + + /** + * Checks that an exactly spelled file reached through a directory symlink produces no case warning. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @Test + void doesNotWarnAboutCasingThroughDirectorySymlink() throws Exception { + Path target = Files.createDirectory(temp.resolve("target")); + symlink(temp.resolve("assets"), target); + Path logo = Files.writeString(target.resolve("logo.png"), "existing"); + AbstractUnArchiver extractor = extractAssets(Format.ZIP, temp, logo, false); + assertEquals(0, extractor.casingMessageEmitted.get()); + } + + /** + * Checks that a filename case difference beneath an NTFS junction produces one warning. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @Test + @EnabledOnOs(OS.WINDOWS) + void warnsForDifferentFileCasingUnderJunction() throws Exception { + Path target = Files.createDirectory(temp.resolve("target")); + Path logo = Files.writeString(target.resolve("LOGO.PNG"), "existing"); + assumeTrue(Files.exists(target.resolve("logo.png")), "Requires a case-insensitive directory"); + Path assets = assetsJunction(temp, target); + try { + AbstractUnArchiver extractor = extractAssets(Format.ZIP, temp, logo, false); + assertEquals(1, extractor.casingMessageEmitted.get()); + } finally { + Files.delete(assets); + } + } + + /** + * Checks the resolver's treatment of a junction as a root, parent, or final component. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @EnabledOnOs(OS.WINDOWS) + @Test + void checksJunctionPositionBeforeWriting() throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path target = Files.createDirectory(temp.resolve("target")); + Path link = assetsJunction(root, target); + try { + AbstractUnArchiver resolver = new TarUnArchiver(); + assertEquals(target.toRealPath(), resolver.resolveExtractionRoot(link.toFile())); + assertThrows(ArchiverException.class, () -> resolver.resolveExtractionPath(root.toFile(), "assets/file")); + for (String entry : new String[] {"root/assets", "root/assets/."}) { + ArchiverException failure = assertThrows( + ArchiverException.class, () -> resolver.resolveExtractionPath(temp.toFile(), entry)); + assertTrue(failure.getMessage().contains("redirected Windows reparse point"), failure::getMessage); + } + assertTrue(Files.isSameFile(link, target)); + } finally { + Files.delete(link); + } + } + + /** + * Checks that file and link entries preserve a junction and that directory entries respect containment. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @EnabledOnOs(OS.WINDOWS) + @ParameterizedTest + @EnumSource( + value = Format.class, + names = {"TAR", "ZIP"}) + void protectsExistingJunctionDuringExtraction(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path target = Files.createDirectory(temp.resolve("target")); + Path marker = Files.writeString(target.resolve("keep"), "original"); + Path assets = assetsJunction(root, target); + try { + // The target is contained when extracting into temp, but outside the narrower root. + for (Kind kind : new Kind[] {Kind.FILE, Kind.SYMLINK}) { + ArchiverException failure = + assertThrows(ArchiverException.class, () -> extract(format, temp, "root/assets", kind, "keep")); + assertTrue(failure.getMessage().contains("redirected Windows reparse point"), failure::getMessage); + } + ArchiverException outside = + assertThrows(ArchiverException.class, () -> extract(format, root, "assets/", Kind.DIRECTORY, "")); + assertTrue(outside.getMessage().contains("outside of the target directory"), outside::getMessage); + assertTrue(Files.isSameFile(assets, target)); + assertEquals("original", Files.readString(marker)); + } finally { + Files.delete(assets); + } + } + + /** + * Validation and writes must agree on link/.. even when the lexical destination does not exist. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void resolvesRootLinkBeforeParentComponent(Format format) throws Exception { + Path lexical = Files.createDirectory(temp.resolve("lexical")); + Path actual = Files.createDirectory(temp.resolve("actual")); + Path sub = Files.createDirectory(actual.resolve("sub")); + Path destination = Files.createDirectory(actual.resolve("only")); + symlink(lexical.resolve("hop"), sub); + Path root = lexical.resolve("hop/../only"); + extract(format, root, "file", Kind.FILE, "content"); + extract(format, root, root.resolve("absolute").toString(), Kind.FILE, "mapped"); + assertEquals("content", Files.readString(destination.resolve("file"))); + assertEquals("mapped", Files.readString(destination.resolve("absolute"))); + assertFalse(Files.exists(lexical.resolve("only"))); + } + + /** + * A regular file or symlink can replace a final symlink when overwrite is enabled. Its former target is preserved. + * + * @param format the extraction entry point to exercise + * @param kind the archive member type + * @param location whether the link target is inside the root, outside it, or missing + * @param overwrite whether replacement is enabled + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @MethodSource("finalLinks") + void handlesFinalSymlink(Format format, Kind kind, String location, boolean overwrite) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path target = (location.equals("inside") ? root : temp).resolve("target"); + if (!location.equals("missing")) { + if (kind == Kind.DIRECTORY) { + Files.createDirectory(target); + } else { + Files.writeString(target, "original"); + } + Files.setLastModifiedTime(target, FileTime.fromMillis(1500000000000L)); + } + Path link = root.resolve("entry"); + symlink(link, target); + Path newTarget = Files.writeString(root.resolve("new-target"), "new target contents"); + FileTime targetTime = FileTime.fromMillis(1500000000000L); + Files.setLastModifiedTime(newTarget, targetTime); + String value = kind == Kind.SYMLINK ? "new-target" : "replacement"; + AbstractUnArchiver extractor = + prepareMember(format, root, kind == Kind.DIRECTORY ? "entry/" : "entry", kind, value); + extractor.setOverwrite(overwrite); + if (kind == Kind.DIRECTORY || (kind == Kind.FILE && !overwrite)) { + assertThrows(ArchiverException.class, extractor::extract); + assertEquals(target, Files.readSymbolicLink(link)); + } else { + extractor.extract(); + if (kind == Kind.FILE) { + assertTrue(Files.isRegularFile(link, LinkOption.NOFOLLOW_LINKS)); + assertEquals("replacement", Files.readString(link)); + } else { + assertEquals(overwrite ? Path.of("new-target") : target, Files.readSymbolicLink(link)); + } + } + assertEquals("new target contents", Files.readString(newTarget)); + assertEquals(targetTime, Files.getLastModifiedTime(newTarget)); + if (location.equals("missing")) { + assertFalse(Files.exists(target, LinkOption.NOFOLLOW_LINKS)); + } else if (kind == Kind.DIRECTORY) { + assertTrue(Files.isDirectory(target)); + } else { + assertEquals("original", Files.readString(target)); + } + if (!location.equals("missing")) { + assertEquals(1500000000000L, Files.getLastModifiedTime(target).toMillis()); + } + } + + /** A replacement link to a relative directory must resolve from the entry's parent, including on Windows. */ + @Test + void replacesFinalDirectorySymlink() throws Exception { + Path first = Files.createDirectory(temp.resolve("first")); + Path second = Files.createDirectory(temp.resolve("second")); + Path entry = temp.resolve("entry"); + symlink(entry, first); + + extract(Format.TAR, temp, "entry", Kind.SYMLINK, "second"); + assertEquals(Path.of("second"), Files.readSymbolicLink(entry)); + assertTrue(Files.isSameFile(entry, second)); + + extract(Format.TAR, temp, "entry", Kind.FILE, "contents"); + assertTrue(Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)); + assertEquals("contents", Files.readString(entry)); + assertTrue(Files.isDirectory(first)); + assertTrue(Files.isDirectory(second)); + } + + /** An unreadable file entry leaves the old link in place and cleans up the incomplete replacement. */ + @Test + void preservesFinalSymlinkOnReadFailure() throws Exception { + Path target = Files.writeString(temp.resolve("target"), "original"); + Path entry = temp.resolve("entry"); + symlink(entry, target); + IOException failure = new IOException("Cannot read archive member"); + InputStream broken = new InputStream() { + @Override + public int read() throws IOException { + throw failure; + } + }; + AbstractUnArchiver extractor = new ZipUnArchiver(); + assertSame( + failure, + assertThrows( + IOException.class, + () -> extractor.extractFile( + null, + temp.toFile(), + broken, + "entry", + new Date(ENTRY_TIME_MILLIS), + false, + null, + null, + null))); + assertEquals(target, Files.readSymbolicLink(entry)); + assertEquals("original", Files.readString(target)); + try (var children = Files.list(temp)) { + assertEquals(2, children.count()); + } + } + + /** + * A symlink member may name an outside target, but must not set metadata on that target. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void symlinkMetadataDoesNotFollowTarget(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path target = Files.writeString(temp.resolve("target"), "original"); + symlink(temp.resolve("probe"), target); + Files.setLastModifiedTime(target, FileTime.fromMillis(1500000000000L)); + var attributes = Files.readAttributes(target, "basic:lastModifiedTime"); + var permissions = PosixFilePermissions.fromString("rw-------"); + boolean posix = Files.getFileStore(target).supportsFileAttributeView("posix"); + if (posix) { + Files.setPosixFilePermissions(target, permissions); + } + extract(format, root, "entry", Kind.SYMLINK, target.toString()); + assertEquals(attributes, Files.readAttributes(target, "basic:lastModifiedTime")); + // Replacing an existing symlink also preserves its target's metadata. + extract(format, root, "entry", Kind.SYMLINK, target.toString()); + assertEquals(target, Files.readSymbolicLink(root.resolve("entry"))); + assertEquals(attributes, Files.readAttributes(target, "basic:lastModifiedTime")); + if (posix) { + assertEquals(permissions, Files.getPosixFilePermissions(target)); + } + assertEquals("original", Files.readString(target)); + } + + /** + * Checks that a filesystem supporting link timestamps receives the entry time on the link itself. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource( + value = Format.class, + names = {"TAR", "ZIP", "JAR"}) + void setsTimestampOnTheLinkItself(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path target = Files.writeString(root.resolve("target"), "original"); + FileTime targetTime = FileTime.fromMillis(1500000000000L); + Files.setLastModifiedTime(target, targetTime); + + Path probe = root.resolve("probe"); + symlink(probe, Path.of("target")); + FileTime entryTime = FileTime.fromMillis(ENTRY_TIME_MILLIS); + BasicFileAttributeView probeAttributes = + Files.getFileAttributeView(probe, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); + assumeTrue(probeAttributes != null, "Symbolic-link timestamps unavailable"); + try { + probeAttributes.setTimes(entryTime, null, null); + } catch (IOException | UnsupportedOperationException e) { + assumeTrue(false, "Symbolic-link timestamps unavailable: " + e); + } + assumeTrue( + entryTime.equals(Files.getLastModifiedTime(probe, LinkOption.NOFOLLOW_LINKS)) + && targetTime.equals(Files.getLastModifiedTime(target)), + "Filesystem cannot set a symbolic link's own timestamp"); + + extract(format, root, "entry", Kind.SYMLINK, "target"); + Path link = root.resolve("entry"); + assertEquals(Path.of("target"), Files.readSymbolicLink(link)); + assertEquals(entryTime, Files.getLastModifiedTime(link, LinkOption.NOFOLLOW_LINKS)); + assertEquals(targetTime, Files.getLastModifiedTime(target)); + } + + /** + * Checks that a cycle is reported as a filesystem loop within the test timeout. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + @Timeout(5) + void rejectsSymlinkCycles(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + symlink(root.resolve("loop"), Path.of("loop")); + Throwable error = + assertThrows(ArchiverException.class, () -> extract(format, root, "loop/file", Kind.FILE, "content")); + while (error.getCause() != null) { + error = error.getCause(); + } + assertInstanceOf(FileSystemLoopException.class, error); + } + + /** + * Resolve long chains ourselves instead of depending on an operating system's whole-path link limit. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void boundsSymlinkExpansions(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path real = Files.createDirectory(root.resolve("real")); + for (int i = 64; i >= 0; i--) { + symlink(root.resolve("link" + i), Path.of(i == 64 ? "real" : "link" + (i + 1))); + } + extract(format, root, "link1/accepted", Kind.FILE, "content"); + assertEquals("content", Files.readString(real.resolve("accepted"))); + Throwable error = assertThrows( + ArchiverException.class, () -> extract(format, root, "link0/rejected", Kind.FILE, "content")); + while (error.getCause() != null) { + error = error.getCause(); + } + assertInstanceOf(FileSystemLoopException.class, error); + assertFalse(Files.exists(real.resolve("rejected"))); + } +} diff --git a/src/test/java/org/codehaus/plexus/archiver/SymlinkFailureModeTest.java b/src/test/java/org/codehaus/plexus/archiver/SymlinkFailureModeTest.java index fe55d416..27bc0dfb 100644 --- a/src/test/java/org/codehaus/plexus/archiver/SymlinkFailureModeTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/SymlinkFailureModeTest.java @@ -33,9 +33,12 @@ import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Extraction when the file system refuses symbolic links, as Windows does without the symlink privilege. @@ -214,6 +217,36 @@ void failsWhenModeIsFail() throws Exception { .hasRootCauseInstanceOf(AccessDeniedException.class); } + /** A refused replacement leaves the old link intact, including when a deferred copy finds it occupied. */ + @ParameterizedTest + @EnumSource(SymlinkFailureMode.class) + void refusedReplacementPreservesExistingLink(SymlinkFailureMode mode) throws Exception { + TarUnArchiver extractor = refusingTar(tar("link", "->new")); + Files.writeString(dest.resolve("old"), "old contents"); + Files.writeString(dest.resolve("new"), "new contents"); + Path link = dest.resolve("link"); + try { + Files.createSymbolicLink(link, Path.of("old")); + } catch (IOException | UnsupportedOperationException e) { + assumeTrue(false, "Symbolic links unavailable: " + e); + } + extractor.setSymlinkFailureMode(mode); + if (mode == SymlinkFailureMode.FAIL) { + assertThatThrownBy(extractor::extract) + .isInstanceOf(ArchiverException.class) + .hasRootCauseInstanceOf(AccessDeniedException.class); + } else { + extractor.extract(); + } + assertThat(Files.readSymbolicLink(link)).isEqualTo(Path.of("old")); + assertThat(read("old")).isEqualTo("old contents"); + assertThat(read("new")).isEqualTo("new contents"); + try (var children = Files.list(dest)) { + assertThat(children.map(path -> path.getFileName().toString())) + .containsExactlyInAnyOrder("old", "new", "link"); + } + } + @Test void extractsTwiceIntoTheSameDirectory() throws Exception { TarUnArchiver unArchiver = refusingTar(tar("link", "->file.txt", "file.txt", "content")); diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarSymlinkTraversalTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarSymlinkTraversalTest.java new file mode 100644 index 00000000..c8776743 --- /dev/null +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarSymlinkTraversalTest.java @@ -0,0 +1,661 @@ +/* + * 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.tar; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Date; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.apache.commons.compress.compressors.CompressorStreamFactory; +import org.codehaus.plexus.archiver.ArchiverException; +import org.codehaus.plexus.components.io.filemappers.FileMapper; +import org.codehaus.plexus.components.io.fileselectors.FileSelector; +import org.codehaus.plexus.util.Os; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +class TarSymlinkTraversalTest { + @TempDir + Path temp; + + /** Describes independently constructed headers; value is either regular contents or a link target. */ + private record Member(String name, char type, String value) {} + + /** Writes a fixture directly through the selected compressor, without using the production writer. */ + private Path archive(TarUnArchiver.UntarCompressionMethod compression, Member... members) throws Exception { + Path archive = Files.createTempFile(temp, "symlinks", ".tar"); + String algorithm = + switch (compression) { + case NONE -> null; + case GZIP -> "gz"; + case BZIP2 -> "bzip2"; + case SNAPPY -> "snappy-framed"; + case XZ -> "xz"; + case ZSTD -> "zstd"; + }; + try (OutputStream file = Files.newOutputStream(archive); + OutputStream encoded = algorithm == null + ? file + : new CompressorStreamFactory().createCompressorOutputStream(algorithm, file); + TarArchiveOutputStream out = new TarArchiveOutputStream(encoded)) { + for (Member member : members) { + TarArchiveEntry entry = new TarArchiveEntry(member.name, (byte) member.type); + entry.setMode(0755); + entry.setModTime(1234567000000L); + byte[] bytes = member.value.getBytes(StandardCharsets.UTF_8); + if (member.type == '0') { + entry.setSize(bytes.length); + } else if (member.type == '2') { + entry.setLinkName(member.value); + } + out.putArchiveEntry(entry); + if (member.type == '0') { + out.write(bytes); + } + out.closeArchiveEntry(); + } + } + return archive; + } + + /** Creates a symlink only when the test filesystem permits it. */ + private void symlink(Path link, Path target) throws IOException { + try { + Files.createSymbolicLink(link, target); + assumeTrue(Files.isSymbolicLink(link), "Filesystem did not create a symbolic link"); + } catch (IOException | UnsupportedOperationException e) { + assumeTrue(false, "Symbolic links unavailable: " + e); + } + } + + /** Checks actual link capabilities, so unsupported filesystems skip only the affected cases. */ + private void requireSymlinks() throws IOException { + Path original = Files.writeString(temp.resolve("probe"), "probe"); + symlink(temp.resolve("probe-symlink"), original); + } + + /** Covers the inherited setting on each concrete compressed TAR extractor. */ + private TarUnArchiver extractor(Path archive, Path output, TarUnArchiver.UntarCompressionMethod compression) { + TarUnArchiver extractor = + switch (compression) { + case NONE -> new TarUnArchiver(); + case GZIP -> new TarGZipUnArchiver(); + case BZIP2 -> new TarBZip2UnArchiver(); + case SNAPPY -> new TarSnappyUnArchiver(); + case XZ -> new TarXZUnArchiver(); + case ZSTD -> new TarZstdUnArchiver(); + }; + extractor.setSourceFile(archive.toFile()); + extractor.setDestDirectory(output.toFile()); + return extractor; + } + + /** Exercises both policies through every TAR decoder. */ + static Stream policies() { + return Arrays.stream(TarUnArchiver.UntarCompressionMethod.values()) + .flatMap(compression -> Stream.of(false, true).map(reject -> Arguments.of(compression, reject))); + } + + /** GNU defaults use the current target; rejection stops before the redirected replacement is written. */ + @ParameterizedTest + @MethodSource("policies") + void directorySymlinkCollision(TarUnArchiver.UntarCompressionMethod compression, boolean reject) throws Exception { + requireSymlinks(); + Path source = archive( + compression, + new Member("real/file", '0', "original"), + new Member("redirect", '2', "real"), + new Member("redirect/file", '0', "changed!")); + Path output = Files.createDirectory(temp.resolve("output")); + TarUnArchiver extractor = extractor(source, output, compression); + assertFalse(extractor.isFailOnSymlinkTraversal()); + if (reject) { + extractor.setFailOnSymlinkTraversal(true); + assertTrue(extractor.isFailOnSymlinkTraversal()); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains("destination 'redirect/file'")); + assertTrue(error.getMessage() + .contains("symbolic link '" + output.toRealPath().resolve("redirect") + "'")); + assertEquals("original", Files.readString(output.resolve("real/file"))); + } else { + extractor.extract(); + assertEquals("changed!", Files.readString(output.resolve("real/file"))); + } + assertTrue(Files.isSymbolicLink(output.resolve("redirect"))); + } + + /** Existing subclass hooks see original names and mappers, while each mapped destination is computed once. */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void preservesExtractionHookArgumentsAndStatefulMapping(boolean reject) throws Exception { + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("logical", '0', "content")); + Path output = Files.createDirectory(temp.resolve("output")); + AtomicInteger mappings = new AtomicInteger(); + FileMapper[] mappers = { + name -> { + assertEquals(1, mappings.incrementAndGet()); + assertEquals("logical", name); + return "mapped/" + name; + }, + name -> { + assertEquals(2, mappings.incrementAndGet()); + assertEquals("mapped/logical", name); + return name + ".txt"; + } + }; + TarUnArchiver extractor = new TarUnArchiver(source.toFile()) { + @Override + protected void extractFile( + File archive, + File directory, + InputStream contents, + String name, + Date date, + boolean isDirectory, + Integer mode, + String symlink, + FileMapper[] fileMappers) + throws IOException { + assertEquals("logical", name); + assertSame(mappers, fileMappers); + super.extractFile(archive, directory, contents, name, date, isDirectory, mode, symlink, fileMappers); + } + }; + extractor.setDestDirectory(output.toFile()); + extractor.setFileMappers(mappers); + assertFalse(extractor.isFailOnSymlinkTraversal()); + if (reject) { + extractor.setFailOnSymlinkTraversal(true); + } + extractor.extract(); + assertEquals(2, mappings.get()); + assertEquals("content", Files.readString(output.resolve("mapped/logical.txt"))); + } + + /** Both traversal settings report an invalid mapper result with its original spelling and cause. */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void reportsInvalidMappedName(boolean reject) throws Exception { + Path output = Files.createDirectory(temp.resolve("output")); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("logical", '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(reject); + String mapped = "dir/bad\0name"; + extractor.setFileMappers(new FileMapper[] {name -> mapped}); + + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains(mapped), error::getMessage); + assertInstanceOf(InvalidPathException.class, error.getCause()); + assertFalse(Files.exists(output.resolve("dir"))); + } + + /** A question mark in a TAR header follows the host's filename rules under either traversal setting. */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void handlesQuestionMarkInArchiveName(boolean reject) throws Exception { + String name = "dir/what?.txt"; + Path output = Files.createDirectory(temp.resolve("output")); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member(name, '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(reject); + + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains(name), error::getMessage); + assertInstanceOf(InvalidPathException.class, error.getCause()); + assertFalse(Files.exists(output.resolve("dir"))); + } else { + extractor.extract(); + assertEquals("content", Files.readString(output.resolve(name))); + } + } + + /** Spells an absolute destination relative to the working directory of its Windows drive. */ + private static String driveRelativeName(Path destination) { + String volume = destination.getRoot().toString(); + assumeTrue(volume.length() == 3 && volume.charAt(1) == ':', "Requires a drive-letter destination"); + String drive = volume.substring(0, 2); + Path workingDirectory = Path.of(drive).toAbsolutePath(); + return drive + workingDirectory.relativize(destination); + } + + /** Both settings resolve drive-relative mappings from the drive directory before checking containment. */ + @ParameterizedTest + @EnabledOnOs(OS.WINDOWS) + @ValueSource(booleans = {false, true}) + void resolvesDriveRelativeMapping(boolean reject) throws Exception { + Path output = Files.createDirectory(temp.resolve("output")).toAbsolutePath(); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("logical", '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(reject); + Path file = output.resolve("file.txt"); + String mapped = driveRelativeName(file); + assertNotEquals(file, output.resolve(Path.of(mapped))); + extractor.setFileMappers(new FileMapper[] {name -> mapped}); + extractor.extract(); + assertEquals("content", Files.readString(file)); + + Path outside = temp.resolve("outside.txt").toAbsolutePath(); + extractor.setFileMappers(new FileMapper[] {name -> driveRelativeName(outside)}); + assertThrows(ArchiverException.class, extractor::extract); + assertFalse(Files.exists(outside)); + } + + /** Strict traversal inspects the parent named by a drive-relative mapping, including a contained link. */ + @ParameterizedTest + @EnabledOnOs(OS.WINDOWS) + @ValueSource(booleans = {false, true}) + void checksLinkInDriveRelativeMapping(boolean reject) throws Exception { + Path output = Files.createDirectory(temp.resolve("output")).toAbsolutePath(); + Path target = Files.createDirectory(output.resolve("assets")); + Path alias = output.resolve("alias"); + symlink(alias, target); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("logo", '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(reject); + String mapped = driveRelativeName(alias.resolve("logo")); + extractor.setFileMappers(new FileMapper[] {name -> mapped}); + if (reject) { + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains("destination '" + mapped + "'"), error::getMessage); + assertFalse(Files.exists(target.resolve("logo"))); + } else { + extractor.extract(); + assertEquals("content", Files.readString(target.resolve("logo"))); + } + } + + /** Mapping and normalization must not conceal existing symlink parents, even with missing prefixes. */ + @ParameterizedTest + @ValueSource( + strings = { + "redirect/file", + "./redirect//file", + "redirect/../file", + "redirect/./file", + "missing/../redirect/file", + "real/../redirect/file", + "redirect/new/file" + }) + void checksMappedPathsBeforeNormalization(String mapped) throws Exception { + Path output = Files.createDirectory(temp.resolve("output")); + Files.createDirectory(output.resolve("real")); + symlink(output.resolve("redirect"), Path.of("real")); + Path source = archive( + TarUnArchiver.UntarCompressionMethod.NONE, + new Member("before", '0', "before"), + new Member("logical", '0', "replacement")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers(new FileMapper[] {name -> name.equals("logical") ? mapped : name}); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains("entry 'logical'")); + assertTrue(error.getMessage().contains("destination '" + mapped + "'")); + assertTrue(error.getMessage().contains("symbolic link")); + assertEquals("before", Files.readString(output.resolve("before"))); + try (var children = Files.list(output.resolve("real"))) { + assertEquals(0, children.count()); + } + assertFalse(Files.exists(output.resolve("file"))); + assertFalse(Files.exists(output.resolve("missing"))); + } + + /** Every output kind checks parents before creating directories, files, or additional links. */ + @ParameterizedTest + @ValueSource(strings = {"0", "2", "5"}) + void rejectsAllEntryKindsBeforeChanges(String kind) throws Exception { + requireSymlinks(); + Path source = archive( + TarUnArchiver.UntarCompressionMethod.NONE, + new Member("real/file", '0', "original"), + new Member("redirect", '2', "real"), + new Member("redirect/new/entry", kind.charAt(0), "real/file")); + Path output = Files.createDirectory(temp.resolve("output")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains("destination 'redirect/new/entry")); + assertFalse(Files.exists(output.resolve("real/new"))); + assertEquals("original", Files.readString(output.resolve("real/file"))); + } + + /** Selection skips unsafe entries, but overwrite policy does not bypass validation of selected paths. */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void selectionAndOverwrite(boolean excluded) throws Exception { + Path output = Files.createDirectory(temp.resolve("output")); + Files.createDirectory(output.resolve("real")); + Files.writeString(output.resolve("real/file"), "existing"); + symlink(output.resolve("redirect"), Path.of("real")); + Path source = archive( + TarUnArchiver.UntarCompressionMethod.NONE, + new Member("redirect/file", '0', "replacement"), + new Member("after", '0', "after")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setOverwrite(false); + if (excluded) { + extractor.setFileSelectors( + new FileSelector[] {file -> !file.getName().equals("redirect/file")}); + extractor.extract(); + assertEquals("after", Files.readString(output.resolve("after"))); + } else { + assertThrows(ArchiverException.class, extractor::extract); + assertFalse(Files.exists(output.resolve("after"))); + } + assertEquals("existing", Files.readString(output.resolve("real/file"))); + } + + /** The configured root is trusted, while unrelated symbolic-link entries remain allowed. */ + @Test + void acceptsTrustedRootAndUnrelatedSymlinks() throws Exception { + Path realRoot = Files.createDirectory(temp.resolve("real-root")); + Path output = temp.resolve("output"); + symlink(output, realRoot); + Path source = archive( + TarUnArchiver.UntarCompressionMethod.NONE, + new Member("redirect", '2', "elsewhere"), + new Member("./nested/../directory/file", '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.extract(); + assertEquals("content", Files.readString(realRoot.resolve("directory/file"))); + assertTrue(Files.isSymbolicLink(realRoot.resolve("redirect"))); + } + + /** Builds a trusted root whose lexical parent differs from its filesystem-resolved parent. */ + private Path rootThroughSymlinkAndParent() throws IOException { + Path actual = Files.createDirectory(temp.resolve("actual")); + Files.createDirectory(actual.resolve("sub")); + Path lexical = Files.createDirectory(temp.resolve("lexical")); + symlink(lexical.resolve("hop"), actual.resolve("sub")); + return lexical.resolve("hop/.."); + } + + /** Both relative and absolute mappings must inspect the actual children of a trusted root alias. */ + @ParameterizedTest + @ValueSource(strings = {"relative", "configured-absolute", "canonical-absolute"}) + void checksChildrenOfRootThroughSymlinkAndParent(String spelling) throws Exception { + Path output = rootThroughSymlinkAndParent(); + Path actual = temp.resolve("actual").toRealPath(); + Files.createDirectory(actual.resolve("real")); + symlink(actual.resolve("redirect"), Path.of("real")); + String mapped = + switch (spelling) { + case "configured-absolute" -> + output.resolve("redirect/file").toString(); + case "canonical-absolute" -> actual.resolve("redirect/file").toString(); + default -> "redirect/file"; + }; + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("logical", '0', "changed")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers(new FileMapper[] {name -> mapped}); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains("entry 'logical'")); + assertTrue(error.getMessage().contains("symbolic link '" + actual.resolve("redirect") + "'")); + assertFalse(Files.exists(actual.resolve("real/file"))); + } + + /** Unrelated symlinks in the lexical tree must not reject safe extraction in the actual tree. */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void acceptsSafeChildrenOfRootThroughSymlinkAndParent(boolean reject) throws Exception { + requireSymlinks(); + Path output = rootThroughSymlinkAndParent(); + Path actual = temp.resolve("actual").toRealPath(); + symlink(temp.resolve("lexical/real"), Path.of("elsewhere")); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("real/file", '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(reject); + extractor.extract(); + assertEquals("content", Files.readString(actual.resolve("real/file"))); + assertTrue(Files.isSymbolicLink(temp.resolve("lexical/real"))); + } + + /** Dot components in either root spelling must not prevent safe regular-file extraction. */ + @ParameterizedTest + @CsvSource({ + "output, output", + "output, ./output", + "./output, output", + "output/., output", + "./output/., ./output/.", + "output, actual", + "lexical/./hop/.., lexical/hop/../.", + "lexical/hop/../., lexical/./hop/.." + }) + void acceptsHarmlessRootSpellings(String configured, String mapped) throws Exception { + requireSymlinks(); + Path actual = Files.createDirectory(temp.resolve("actual")); + Files.createDirectory(actual.resolve("sub")); + symlink(temp.resolve("output"), actual); + Files.createDirectory(temp.resolve("lexical")); + symlink(temp.resolve("lexical/hop"), actual.resolve("sub")); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("file", '0', "content")); + TarUnArchiver extractor = + extractor(source, temp.resolve(configured), TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers( + new FileMapper[] {name -> temp.resolve(mapped).resolve(name).toString()}); + extractor.extract(); + assertEquals("content", Files.readString(actual.resolve("file"))); + } + + /** Matching a dotted root must leave its suffix intact, including terminal dots and symlinks before parents. */ + @ParameterizedTest + @ValueSource( + strings = { + "./redirect/file", + "redirect/../file", + "redirect/./../file", + "redirect/.", + "missing/../redirect/file" + }) + void dottedRootStillChecksEntrySuffix(String suffix) throws Exception { + Path actual = Files.createDirectory(temp.resolve("actual")); + Files.createDirectory(actual.resolve("real")); + symlink(actual.resolve("redirect"), Path.of("real")); + symlink(temp.resolve("output"), actual); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("logical", '0', "changed")); + TarUnArchiver extractor = + extractor(source, temp.resolve("./output/."), TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers( + new FileMapper[] {name -> temp.resolve("output").resolve(suffix).toString()}); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + // Rejection must identify the symlink beneath the trusted root, not the root alias itself. + assertTrue(error.getMessage() + .contains("symbolic link '" + actual.toRealPath().resolve("redirect") + "'")); + assertFalse(Files.exists(actual.resolve("file"))); + assertFalse(Files.exists(actual.resolve("real/file"))); + } + + /** Models a temporary directory reached through an ancestor symlink, such as /var on macOS. */ + private Path rootUnderSymlinkedParent() throws IOException { + Path parent = Files.createDirectory(temp.resolve("parent")); + Files.createDirectory(parent.resolve("actual")); + symlink(temp.resolve("parent-alias"), parent); + symlink(parent.resolve("output"), Path.of("actual")); + return temp.resolve("parent-alias/actual"); + } + + /** Absolute mappings may name the actual root through an ancestor alias rather than the configured root alias. */ + @ParameterizedTest + @EnumSource(TarUnArchiver.UntarCompressionMethod.class) + void acceptsRootUnderSymlinkedParent(TarUnArchiver.UntarCompressionMethod compression) throws Exception { + requireSymlinks(); + Path mappedRoot = rootUnderSymlinkedParent(); + Path actual = mappedRoot.toRealPath(); + Path source = archive(compression, new Member("file", '0', "content")); + TarUnArchiver extractor = extractor(source, mappedRoot.resolveSibling("output"), compression); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers( + new FileMapper[] {name -> mappedRoot.resolve(name).toString()}); + extractor.extract(); + assertEquals("content", Files.readString(actual.resolve("file"))); + } + + /** Resolving an ancestor alias must not conceal symlinks in the remaining mapped path. */ + @ParameterizedTest + @ValueSource( + strings = { + "./redirect/file", + "redirect/../file", + "redirect/./../file", + "redirect/.", + "missing/../redirect/file" + }) + void checksEntrySuffixUnderSymlinkedParent(String suffix) throws Exception { + Path mappedRoot = rootUnderSymlinkedParent(); + Path actual = mappedRoot.toRealPath(); + Files.createDirectory(actual.resolve("real")); + Files.writeString(actual.resolve("real/file"), "existing"); + Files.writeString(actual.resolve("file"), "existing"); + symlink(actual.resolve("redirect"), Path.of("real")); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("logical", '0', "changed")); + TarUnArchiver extractor = + extractor(source, mappedRoot.resolveSibling("output"), TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers( + new FileMapper[] {name -> mappedRoot.resolve(suffix).toString()}); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue( + error.getMessage().contains("symbolic link '" + actual.resolve("redirect") + "'"), error::getMessage); + assertEquals("existing", Files.readString(actual.resolve("file"))); + assertEquals("existing", Files.readString(actual.resolve("real/file"))); + assertTrue(Files.isSymbolicLink(actual.resolve("redirect"))); + assertFalse(Files.exists(actual.resolve("missing"))); + } + + /** An ancestor alias is trusted, but a separate alias pointing directly at the root is not. */ + @Test + void rejectsUnconfiguredRootAlias() throws Exception { + Path mappedRoot = rootUnderSymlinkedParent(); + Path actual = mappedRoot.toRealPath(); + Path alternate = mappedRoot.resolveSibling("alternate"); + symlink(alternate, Path.of("actual")); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("file", '0', "content")); + TarUnArchiver extractor = + extractor(source, mappedRoot.resolveSibling("output"), TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers( + new FileMapper[] {name -> alternate.resolve(name).toString()}); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue( + error.getMessage().contains("symbolic link '" + actual.resolveSibling("alternate") + "'"), + error::getMessage); + assertFalse(Files.exists(actual.resolve("file"))); + } + + /** Reaching the root ends ancestor exemptions, even if a later parent component leaves the root again. */ + @ParameterizedTest + @ValueSource(strings = {"back/actual/file", "../back/actual/file"}) + void rejectsAncestorAliasAfterReachingRoot(String suffix) throws Exception { + Path mappedRoot = rootUnderSymlinkedParent(); + Path actual = mappedRoot.toRealPath(); + Files.writeString(actual.resolve("file"), "existing"); + Path link = (suffix.startsWith("../") ? actual.getParent() : actual).resolve("back"); + symlink(link, actual.getParent()); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("file", '0', "changed")); + TarUnArchiver extractor = + extractor(source, mappedRoot.resolveSibling("output"), TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers( + new FileMapper[] {name -> mappedRoot.resolve(suffix).toString()}); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains("symbolic link '" + link + "'"), error::getMessage); + assertEquals("existing", Files.readString(actual.resolve("file"))); + } + + /** Absolute mappings must be checked before FileUtils canonicalization erases the symlink components. */ + @ParameterizedTest + @ValueSource(strings = {"lexical", "canonical", "alternate", "backslash"}) + void checksAbsoluteMappedPaths(String spelling) throws Exception { + Path realRoot = Files.createDirectory(temp.resolve("real-root")); + Files.createDirectory(realRoot.resolve("real")); + symlink(realRoot.resolve("redirect"), Path.of("real")); + Path output = temp.resolve("output"); + symlink(output, realRoot); + Path alternate = temp.resolve("alternate"); + symlink(alternate, realRoot); + String mapped = + switch (spelling) { + case "canonical" -> realRoot.resolve("redirect/file").toString(); + case "alternate" -> alternate.resolve("redirect/file").toString(); + case "backslash" -> output.resolve("redirect").toString() + "\\file"; + default -> output.resolve("redirect/file").toString(); + }; + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("logical", '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.setFileMappers(new FileMapper[] {name -> mapped}); + ArchiverException error = assertThrows(ArchiverException.class, extractor::extract); + assertTrue(error.getMessage().contains("destination '" + mapped + "'")); + assertTrue(error.getMessage().contains("symbolic link")); + assertFalse(Files.exists(realRoot.resolve("real/file"))); + } + + /** Relative backslashes remain literal on Unix, matching the existing extraction path resolver. */ + @Test + void acceptsLiteralRelativeBackslashes() throws Exception { + assumeTrue(java.io.File.separatorChar == '/', "Backslash is a path separator on this platform"); + Path output = Files.createDirectory(temp.resolve("output")); + symlink(output.resolve("redirect"), Path.of("elsewhere")); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("redirect\\file", '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + extractor.extract(); + assertEquals("content", Files.readString(output.resolve("redirect\\file"))); + } + + /** Switching the instance policy after a failure takes effect without retaining per-archive path state. */ + @Test + void canDisableRejectionAfterFailure() throws Exception { + Path output = Files.createDirectory(temp.resolve("output")); + Files.createDirectory(output.resolve("real")); + symlink(output.resolve("redirect"), Path.of("real")); + Path source = archive(TarUnArchiver.UntarCompressionMethod.NONE, new Member("redirect/file", '0', "content")); + TarUnArchiver extractor = extractor(source, output, TarUnArchiver.UntarCompressionMethod.NONE); + extractor.setFailOnSymlinkTraversal(true); + assertThrows(ArchiverException.class, extractor::extract); + extractor.setFailOnSymlinkTraversal(false); + extractor.extract(); + assertEquals("content", Files.readString(output.resolve("real/file"))); + } +} diff --git a/src/test/java/org/codehaus/plexus/archiver/zip/ZipArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/zip/ZipArchiverTest.java index 09fe66d9..c00962ee 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zip/ZipArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/zip/ZipArchiverTest.java @@ -33,6 +33,7 @@ import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.text.DateFormat; @@ -83,6 +84,8 @@ import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; 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.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -824,15 +827,25 @@ void fixedEntryModificationTime() throws Exception { } } - @Test + /** A regular entry after a dangling symlink at the same name replaces it only with overwrite enabled. */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) @DisabledOnOs(OS.WINDOWS) - void nonExistingSymlink() throws Exception { + void nonExistingSymlink(boolean overwrite) throws Exception { File zipFile = new File("src/test/resources/symlinks/non_existing_symlink.zip"); ZipUnArchiver unArchiver = getZipUnArchiver(zipFile); - String tmpdir = Files.createTempDirectory("tmpe_extract").toFile().getAbsolutePath(); - unArchiver.setDestDirectory(new File(tmpdir)); - ArchiverException exception = assertThrows(ArchiverException.class, unArchiver::extract); - assertEquals("Entry is outside of the target directory (entry1)", exception.getMessage()); + unArchiver.setDestDirectory(tempDir); + unArchiver.setOverwrite(overwrite); + Path entry = tempDir.toPath().resolve("entry1"); + if (overwrite) { + unArchiver.extract(); + assertTrue(Files.isRegularFile(entry, LinkOption.NOFOLLOW_LINKS)); + assertEquals("“content”", Files.readString(entry)); + } else { + ArchiverException exception = assertThrows(ArchiverException.class, unArchiver::extract); + assertEquals("Entry is outside of the target directory (entry1)", exception.getMessage()); + assertTrue(Files.isSymbolicLink(entry)); + } } /**