aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-05-23 19:37:31 -0500
committerGitHub <noreply@github.com>2026-05-23 19:37:31 -0500
commit746f7ceefa61e62ad801b825f80b87fe9c853c44 (patch)
tree52afa6e3ee234950bbd338e3d086b682da277b58 /src
parent0bc3f2e327d8ae9a8a0bd1058cb90c59c58933ee (diff)
parent8870f4f5590373d54370e64c7b9081521245d8dc (diff)
downloadslskd-746f7ceefa61e62ad801b825f80b87fe9c853c44.tar.gz
Merge pull request #1740 from slskd/paths
Change path manipulation logic (again)
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/FileSafety.cs95
-rw-r--r--src/slskd/Common/Validation/AbsolutePathAttribute.cs14
-rw-r--r--src/slskd/Common/Validation/RelativePathAttribute.cs13
-rw-r--r--src/slskd/Files/FileService.cs57
4 files changed, 151 insertions, 28 deletions
diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs
index f94b9c7b..f67af8d5 100644
--- a/src/slskd/Common/FileSafety.cs
+++ b/src/slskd/Common/FileSafety.cs
@@ -35,6 +35,7 @@ namespace slskd;
using System;
using System.IO;
using System.Linq;
+using System.Runtime.InteropServices;
/// <summary>
/// Utility functions to help safely work with paths from untrusted sources.
@@ -50,7 +51,19 @@ public static class FileSafety
/// <returns>The combined path.</returns>
/// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception>
/// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception>
- public static string CombineSafely(string root, params string[] segments)
+ public static string CombineSafely(string root, params string[] segments) => CombineSafely(root, os: null, segments: segments);
+
+ /// <summary>
+ /// An alternative to <see cref="Path.Combine(string, string)"/> that disallows rooted segments in the second or
+ /// subsequent position, and disallows segments containing path traversal characters "." and "..".
+ /// </summary>
+ /// <param name="root">The root directory.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <param name="segments">The segments to append.</param>
+ /// <returns>The combined path.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception>
+ /// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception>
+ public static string CombineSafely(string root, OSPlatform? os, params string[] segments)
{
// ensure no inputs are null. matches the behavior of Path.Combine()
if (string.IsNullOrWhiteSpace(root))
@@ -58,19 +71,41 @@ public static class FileSafety
throw new ArgumentNullException(nameof(root), $"Specified root directory is null or consists only of whitespace");
}
+ if (ContainsTraversalSegments(root))
+ {
+ throw new ArgumentException("Specified root directory contains path traversal segments", nameof(root));
+ }
+
if (segments is null || segments.Any(s => s is null))
{
throw new ArgumentNullException(nameof(segments), $"One or more segments is null");
}
+ var isWindows = os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows();
+
foreach (var segment in segments)
{
// if any segment is rooted (leading slash), Path.Combine drops everyting up to that segment
// and it becomes the new root. example: Path.Combine("/home/users/foo", "/etc") results in "/etc"
// not what we want!
- if (IsPathAbsolute(segment))
+ if (IsPathAbsolute(segment, os))
{
- throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'");
+ throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'");
+ }
+
+ if (isWindows)
+ {
+ if (segment.Contains(':'))
+ {
+ throw new ArgumentException($"Colons are not permitted in segments: '{segment}'");
+ }
+
+ // on Windows, a segment beginning with a slash is considered 'drive rooted' and something like
+ // "\foo" translates to "C:\foo" when passed to Path.Combine()
+ if (segment.StartsWith('\\') || segment.StartsWith('/'))
+ {
+ throw new ArgumentException($"Drive-relative segments or those containing leading slashes are not permitted in segments: '{segment}'");
+ }
}
var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/');
@@ -79,16 +114,17 @@ public static class FileSafety
// untrusted input could use this to "break out" of the root directory and access sensitive areas
if (parts.Any(s => s is "." or ".."))
{
- throw new ArgumentException($"Path traversal is not permitted: '{segment}'");
+ throw new ArgumentException($"Path traversal is not permitted in segments: '{segment}'");
}
}
var combined = Path.Combine(root, Path.Combine(segments));
- // not sure how we could possibly get here, but if we do, throw.
+ // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting
+ // path is actually rooted in the root we provided; if not the input was successful in traversal
if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root)))
{
- throw new ArgumentException($"Path traversal detected in path {combined}, which is not allowed");
+ throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed");
}
return combined;
@@ -102,36 +138,46 @@ public static class FileSafety
public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false;
/// <summary>
- /// Returns a value indicating whether the specified <paramref name="path"/> is absolute (rooted), using
- /// platform-independent rules that recognize both Unix and Windows absolute path formats.
+ /// Returns a value indicating whether the specified <paramref name="path"/> is absolute (rooted) on the current
+ /// operating system.
/// </summary>
/// <remarks>
/// This is necessary because the base library is opaque and untestable in a cross-platform way, so we are
- /// implementing the nuclear option and merging the logic for Windows and non-Windows.
+ /// implementing the nuclear option and doing it ourselves.
/// </remarks>
/// <param name="path">The path to check.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
/// <returns>True if the path is absolute, false otherwise.</returns>
- public static bool IsPathAbsolute(string path)
+ public static bool IsPathAbsolute(string path, OSPlatform? os = null)
{
if (string.IsNullOrEmpty(path))
{
return false;
}
- // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with /
- // Windows root-relative paths and UNC paths start with \
- if (path[0] is '/' or '\\')
+ if (os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows())
{
- return true;
+ // Windows drive-letter path: X:\ or X:/
+ // X:foo is relative on windows
+ if (path.Length >= 3
+ && char.IsAsciiLetter(path[0])
+ && path[1] == ':'
+ && (path[2] == '\\' || path[2] == '/'))
+ {
+ return true;
+ }
+
+ // UNC path \\server\share
+ if (path.StartsWith("\\\\"))
+ {
+ return true;
+ }
+
+ return false;
}
- // Windows drive-letter paths: X:\ or X:/
- // X:foo is a "drive relative" path so it doesn't _technically_ count, but
- // it's questionable and the user probably intended to root it anyway
- // this matches the built in IsPathRooted but not IsPathFullyQualified
- if (path.Length >= 2
- && char.IsAsciiLetter(path[0])
- && path[1] == ':')
+ // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with /
+ if (path.StartsWith('/'))
{
return true;
}
@@ -140,10 +186,11 @@ public static class FileSafety
}
/// <summary>
- /// Returns a value indicating whether the specified <paramref name="path"/>, using
- /// platform-independent rules that recognize both Unix and Windows absolute path formats.
+ /// Returns a value indicating whether the specified <paramref name="path"/> is relative on the current
+ /// operating system.
/// </summary>
/// <param name="path">The path to check.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
/// <returns>True if the path is relative, false otherwise.</returns>
- public static bool IsPathRelative(string path) => !IsPathAbsolute(path);
+ public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os);
} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
index 1999220f..eb1c9069 100644
--- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs
+++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
@@ -33,19 +33,31 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
+ using System.Runtime.InteropServices;
/// <summary>
/// Validates that the specified path is absolute.
/// </summary>
public class AbsolutePathAttribute : ValidationAttribute
{
+ public AbsolutePathAttribute()
+ {
+ }
+
+ public AbsolutePathAttribute(OSPlatform? os = null)
+ {
+ OS = os;
+ }
+
+ public OSPlatform? OS { get; }
+
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null && value is string str && !string.IsNullOrEmpty(str))
{
var path = value.ToString();
- if (!FileSafety.IsPathAbsolute(path))
+ if (!FileSafety.IsPathAbsolute(path, os: OS))
{
return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path.");
}
diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs
index 64e418b1..f465ba98 100644
--- a/src/slskd/Common/Validation/RelativePathAttribute.cs
+++ b/src/slskd/Common/Validation/RelativePathAttribute.cs
@@ -33,19 +33,30 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
+ using System.Runtime.InteropServices;
/// <summary>
/// Validates that the specified path is relative.
/// </summary>
public class RelativePathAttribute : ValidationAttribute
{
+ public RelativePathAttribute()
+ {
+ }
+
+ public RelativePathAttribute(OSPlatform? os = null)
+ {
+ OS = os;
+ }
+
+ public OSPlatform? OS { get; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null && value is string str && !string.IsNullOrEmpty(str))
{
var path = value.ToString();
- if (!FileSafety.IsPathRelative(path))
+ if (!FileSafety.IsPathRelative(path, os: OS))
{
return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path.");
}
diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs
index 4b281863..3b304d99 100644
--- a/src/slskd/Files/FileService.cs
+++ b/src/slskd/Files/FileService.cs
@@ -79,6 +79,17 @@ namespace slskd.Files
{
ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename));
+ if (Path.GetFullPath(filename) != filename)
+ {
+ throw new ArgumentException("Only absolute paths may be specified", nameof(filename));
+ }
+
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to resolve file info for a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename);
+ throw new ArgumentException("Filenames containing traversal segments are not allowed", nameof(filename));
+ }
+
FileInfo info;
try
@@ -153,11 +164,22 @@ namespace slskd.Files
/// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception>
public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories)
{
+ if (directories is null or [] || directories.Any(directory => string.IsNullOrEmpty(directory)))
+ {
+ throw new ArgumentException("One or more directories are null or empty");
+ }
+
if (directories.Any(directory => Path.GetFullPath(directory) != directory))
{
throw new ArgumentException("Only absolute paths may be specified", nameof(directories));
}
+ if (directories.Any(directory => FileSafety.ContainsTraversalSegments(directory)))
+ {
+ Log.Warning("Suspicious attempt to delete a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directories: {Directories}", string.Join(", ", directories));
+ throw new ArgumentException("Directories containing traversal segments are not allowed", nameof(directories));
+ }
+
if (directories.Any(directory => AllowedDirectories.Contains(directory)))
{
throw new ArgumentException("Deletion of application-controlled directory roots is not supported");
@@ -216,11 +238,22 @@ namespace slskd.Files
/// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception>
public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files)
{
+ if (files is null or [] || files.Any(file => string.IsNullOrWhiteSpace(file)))
+ {
+ throw new ArgumentException("One or more files are null or empty", nameof(files));
+ }
+
if (files.Any(file => Path.GetFullPath(file) != file))
{
throw new ArgumentException("Only absolute paths may be specified", nameof(files));
}
+ if (files.Any(file => FileSafety.ContainsTraversalSegments(file)))
+ {
+ Log.Warning("Suspicious attempt to delete a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file(s): {File}", string.Join(", ", files));
+ throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(files));
+ }
+
// important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..'
bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed);
@@ -269,15 +302,23 @@ namespace slskd.Files
/// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception>
public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null)
{
+ ArgumentException.ThrowIfNullOrWhiteSpace(directory);
+
if (Path.GetFullPath(directory) != directory)
{
throw new ArgumentException("Only absolute paths may be specified", nameof(directory));
}
+ if (FileSafety.ContainsTraversalSegments(directory))
+ {
+ Log.Warning("Suspicious attempt to list a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directory: {Directory}", directory);
+ throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(directory));
+ }
+
// important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..'
- if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed)))
+ if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed + Path.DirectorySeparatorChar) || directory == allowed))
{
- throw new UnauthorizedException($"Only application-controlled directories can be deleted");
+ throw new UnauthorizedException($"Only application-controlled directories can be listed");
}
if (!Directory.Exists(directory))
@@ -340,6 +381,12 @@ namespace slskd.Files
{
ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename));
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to create a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename);
+ throw new ArgumentException("Filenames containing traversal segments are not allowed");
+ }
+
var path = Path.GetDirectoryName(filename);
UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode();
@@ -411,6 +458,12 @@ namespace slskd.Files
ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename));
ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory));
+ if (FileSafety.ContainsTraversalSegments(sourceFilename) || FileSafety.ContainsTraversalSegments(destinationDirectory))
+ {
+ Log.Warning("Suspicious attempt to move a file with either a source filename or destination directory name containing unsafe path segments (one or more of path traversal characters '.' and '..'). Source: {Source}, Destination: {Destination}", sourceFilename, destinationDirectory);
+ throw new ArgumentException("Filenames and directories containing traversal segments are not allowed");
+ }
+
if (!File.Exists(sourceFilename))
{
throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename);