From def6a3a05f02a53b814821ab6b9692e89c2df693 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 May 2026 19:18:06 -0500 Subject: add sanitize functions to FileSafety --- src/slskd/Common/FileSafety.cs | 106 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index f67af8d5..aae14a25 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -36,12 +36,34 @@ using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; +using System.Text.RegularExpressions; /// /// Utility functions to help safely work with paths from untrusted sources. /// public static class FileSafety { + + /// + /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). + /// + public static readonly char[] InvalidFileNameCharactersOnUnix = ['\0', '/']; + + /// + /// Invalid filename characters on Windows. + /// + public static readonly char[] InvalidFileNameCharactersOnWindows = + [ + '\"', '<', '>', '|', '\0', + (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, + (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, + (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, + (char)31, ':', '*', '?', '\\', '/', + ]; + + private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ + private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + /// /// An alternative to that disallows rooted segments in the second or /// subsequent position, and disallows segments containing path traversal characters "." and "..". @@ -193,4 +215,88 @@ public static class FileSafety /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + + /// + /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). + /// + /// The path to convert. + /// An optional operating system override, for testing. + /// The converted path. + public static string LocalizePath(this string path, OSPlatform? os = null) + { + os ??= Compute.OSPlatform(); + + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + return path.Replace('\\', sep).Replace('/', sep); + } + + /// + /// Sanitizes the specified (or string intended to be used as or as part of a filename) + /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and + /// and replacing any invalid characters with the specified . + /// + /// The filename (or string intended to be used as/part of one). + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized filename. + public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) + { + if (replacement is '/' or '\\') + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); + } + + os ??= Compute.OSPlatform(); + + var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + + if (characters.Contains(replacement)) + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid on {os}"); + } + + var sanitized = filename; + + foreach (var c in characters) + { + sanitized = sanitized.Replace(c, replacement); + } + + // regardless of which OS and what characters are disallowed on it, we don't allow slashes in filenames + // (or strings that will be used as filenames), otherwise we should/would have used SanitizePath() + return sanitized + .Replace('/', replacement) + .Replace('\\', replacement); + } + + /// + /// Sanitizes the specified to make it suitable and safe on the local operating system + /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with + /// the specified , and by dropping any path traversal segments. + /// + /// The path. + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized path. + public static string SanitizePath(this string path, char replacement = '_', OSPlatform? os = null) + { + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + // flip slashes the correct way + path = path.LocalizePath(os); + + // strip C:\ or //server, if present (regardless of slash variant, etc) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + var segments = path + .Split(sep) + .Select(s => SanitizeFilename(s, replacement, os)) + .Select(s => s is "." or ".." ? replacement.ToString() : s); + + return string.Join(sep, segments); + } } \ No newline at end of file -- cgit v1.2.3