aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Common/FileSafety.cs
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/slskd/Common/FileSafety.cs
parent0bc3f2e327d8ae9a8a0bd1058cb90c59c58933ee (diff)
parent8870f4f5590373d54370e64c7b9081521245d8dc (diff)
downloadslskd-746f7ceefa61e62ad801b825f80b87fe9c853c44.tar.gz
Merge pull request #1740 from slskd/paths
Change path manipulation logic (again)
Diffstat (limited to 'src/slskd/Common/FileSafety.cs')
-rw-r--r--src/slskd/Common/FileSafety.cs95
1 files changed, 71 insertions, 24 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