aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Common
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-06-07 18:46:25 -0500
committerJP Dillingham <jp@dillingham.me>2026-06-07 18:46:25 -0500
commit294fcabd3928b420a4dfbd7ddd0dc38ada523165 (patch)
treebcc92e42c71f2a9b67f7750c5ecd0a396b5897e5 /src/slskd/Common
parent60bc0c0c2ea6d9c80a7f091f022567b1d5e3240a (diff)
parent8e152ed6eccd5650179f2875eef4aa21243c8c15 (diff)
downloadslskd-294fcabd3928b420a4dfbd7ddd0dc38ada523165.tar.gz
Merge remote-tracking branch 'origin/master' into reports
Diffstat (limited to 'src/slskd/Common')
-rw-r--r--src/slskd/Common/CommonExtensions.cs84
-rw-r--r--src/slskd/Common/Compute.cs11
-rw-r--r--src/slskd/Common/Cryptography/X509.cs4
-rw-r--r--src/slskd/Common/Dumper.cs8
-rw-r--r--src/slskd/Common/Exceptions/ConflictException.cs75
-rw-r--r--src/slskd/Common/Exceptions/DuplicateException.cs75
-rw-r--r--src/slskd/Common/FileSafety.cs492
-rw-r--r--src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs2
-rw-r--r--src/slskd/Common/OperatingSystem.cs43
-rw-r--r--src/slskd/Common/Validation/AbsolutePathAttribute.cs81
-rw-r--r--src/slskd/Common/Validation/GuidAttribute.cs81
-rw-r--r--src/slskd/Common/Validation/NonTraversingPathAttribute.cs (renamed from src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs)15
-rw-r--r--src/slskd/Common/Validation/RelativePathAttribute.cs82
-rw-r--r--src/slskd/Common/Validation/StringAttribute.cs99
14 files changed, 1063 insertions, 89 deletions
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 77db91ef..95721163 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -382,20 +382,6 @@ namespace slskd
.Deserialize<T>(str);
/// <summary>
- /// Converts a fully qualified remote filename to a local filename based in the provided
- /// <paramref name="baseDirectory"/>, swapping directory characters for those specific to the local OS, removing any
- /// characters that are invalid for the local OS, and making the path relative to the remote store (including the
- /// filename and the parent folder).
- /// </summary>
- /// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
- /// <param name="baseDirectory">The base directory for the local filename.</param>
- /// <returns>The converted filename.</returns>
- public static string ToLocalFilename(this string remoteFilename, string baseDirectory)
- {
- return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename());
- }
-
- /// <summary>
/// Converts the given path to the normalized format (normalizes path separators to backslashes).
/// </summary>
/// <remarks>
@@ -409,16 +395,6 @@ namespace slskd
}
/// <summary>
- /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar).
- /// </summary>
- /// <param name="path">The path to convert.</param>
- /// <returns>The converted path.</returns>
- public static string LocalizePath(this string path)
- {
- return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
- }
-
- /// <summary>
/// <see cref="Path.GetDirectoryName(string)"/>, but for paths normalized to use backslashes.
/// </summary>
/// <param name="path"></param>
@@ -439,54 +415,6 @@ namespace slskd
}
/// <summary>
- /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific
- /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the
- /// remote store (including the filename and the parent folder).
- /// </summary>
- /// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
- /// <returns>The converted filename.</returns>
- public static string ToLocalRelativeFilename(this string remoteFilename)
- {
- if (string.IsNullOrWhiteSpace(remoteFilename))
- {
- throw new ArgumentException($"Invalid remote filename; expected a non-whitespace value, received '{remoteFilename}'", nameof(remoteFilename));
- }
-
- // normalize path separators
- var localizedRemoteFilename = remoteFilename.LocalizePath();
-
- var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar);
-
- if (parts.Length == 1)
- {
- return parts.First().ReplaceInvalidFileNameCharacters();
- }
-
- var file = parts.Last().ReplaceInvalidFileNameCharacters();
- var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters();
-
- return Path.Combine(directory, file);
- }
-
- /// <summary>
- /// Replaces any occurrence of an invalid filename character with the specified <see paramref="replacement"/>.
- /// </summary>
- /// <param name="path">The path to sanitize.</param>
- /// <param name="replacement">The character with which to replace invalid characters.</param>
- /// <returns>The sanitized path.</returns>
- public static string ReplaceInvalidFileNameCharacters(this string path, char replacement = '_')
- {
- var sanitized = path;
-
- foreach (var c in Path.GetInvalidFileNameChars())
- {
- sanitized = sanitized.Replace(c, replacement);
- }
-
- return sanitized;
- }
-
- /// <summary>
/// Converts a ModelStateDictionary into a human-readable format.
/// </summary>
/// <param name="dictionary">The ModelStateDictionary to format.</param>
@@ -555,9 +483,17 @@ namespace slskd
/// <returns>The new object deserialized from the string.</returns>
public static T FromJson<T>(this string str) => JsonSerializer.Deserialize<T>(str, GetJsonSerializerOptions());
- private static JsonSerializerOptions GetJsonSerializerOptions()
+ /// <summary>
+ /// Applies the standard json serializer options to the specified instance.
+ /// </summary>
+ /// <param name="opt">The instance.</param>
+ /// <returns>The instances with the standard options applied.</returns>
+ public static JsonSerializerOptions WithStandardOptions(this JsonSerializerOptions opt)
+ => GetJsonSerializerOptions(opt);
+
+ private static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerOptions opt = null)
{
- var options = new JsonSerializerOptions();
+ var options = opt ?? new JsonSerializerOptions();
options.Converters.Add(new IPAddressConverter());
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new KnownUnsupportedTypeConverter());
diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs
index 8d7c1ceb..d235a87c 100644
--- a/src/slskd/Common/Compute.cs
+++ b/src/slskd/Common/Compute.cs
@@ -33,6 +33,7 @@
namespace slskd
{
using System;
+ using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
@@ -64,5 +65,15 @@ namespace slskd
using var sha256 = SHA256.Create();
return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
}
+
+ public static OperatingSystem OperatingSystem()
+ {
+ if (System.OperatingSystem.IsWindows())
+ {
+ return slskd.OperatingSystem.Windows;
+ }
+
+ return slskd.OperatingSystem.Linux;
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs
index bed224cf..b003decf 100644
--- a/src/slskd/Common/Cryptography/X509.cs
+++ b/src/slskd/Common/Cryptography/X509.cs
@@ -64,7 +64,7 @@ namespace slskd.Cryptography
new DateTimeOffset(DateTime.UtcNow.AddDays(-1)),
new DateTimeOffset(DateTime.UtcNow.AddDays(36500)));
- return new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags);
+ return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags);
}
/// <summary>
@@ -80,7 +80,7 @@ namespace slskd.Cryptography
try
{
- _ = new X509Certificate2(fileName, password);
+ _ = X509CertificateLoader.LoadPkcs12FromFile(fileName, password);
return true;
}
catch (Exception ex)
diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs
index f4367e61..27304873 100644
--- a/src/slskd/Common/Dumper.cs
+++ b/src/slskd/Common/Dumper.cs
@@ -84,7 +84,7 @@ namespace slskd
await Download(url, BinFile);
- if (!OperatingSystem.IsWindows())
+ if (!System.OperatingSystem.IsWindows())
{
await ExecAsync("/bin/sh", $"-c \"chmod +x {BinFile}\"");
}
@@ -139,15 +139,15 @@ namespace slskd
string os = default;
// seems like there should be a way to just retrieve this, but there is not as of .NET 6
- if (OperatingSystem.IsLinux())
+ if (System.OperatingSystem.IsLinux())
{
os = "linux";
}
- else if (OperatingSystem.IsWindows())
+ else if (System.OperatingSystem.IsWindows())
{
os = "win";
}
- else if (OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
+ else if (System.OperatingSystem.IsMacOS() || System.OperatingSystem.IsFreeBSD())
{
os = "osx";
}
diff --git a/src/slskd/Common/Exceptions/ConflictException.cs b/src/slskd/Common/Exceptions/ConflictException.cs
new file mode 100644
index 00000000..c58708d0
--- /dev/null
+++ b/src/slskd/Common/Exceptions/ConflictException.cs
@@ -0,0 +1,75 @@
+// <copyright file="ConflictException.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+
+ /// <summary>
+ /// Represents errors that originate due to duplication.
+ /// </summary>
+ [ExcludeFromCodeCoverage]
+ public class ConflictException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConflictException"/> class.
+ /// </summary>
+ public ConflictException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConflictException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public ConflictException(string message)
+ : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ConflictException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
+ /// inner exception is specified.
+ /// </param>
+ public ConflictException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Exceptions/DuplicateException.cs b/src/slskd/Common/Exceptions/DuplicateException.cs
new file mode 100644
index 00000000..da603d87
--- /dev/null
+++ b/src/slskd/Common/Exceptions/DuplicateException.cs
@@ -0,0 +1,75 @@
+// <copyright file="DuplicateException.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+
+ /// <summary>
+ /// Represents errors that originate due to duplication.
+ /// </summary>
+ [ExcludeFromCodeCoverage]
+ public class DuplicateException : Exception
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DuplicateException"/> class.
+ /// </summary>
+ public DuplicateException()
+ : base()
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DuplicateException"/> class with a specified error message.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ public DuplicateException(string message)
+ : base(message)
+ {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DuplicateException"/> class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
+ /// <param name="message">The message that describes the error.</param>
+ /// <param name="innerException">
+ /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no
+ /// inner exception is specified.
+ /// </param>
+ public DuplicateException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs
new file mode 100644
index 00000000..6a6dea22
--- /dev/null
+++ b/src/slskd/Common/FileSafety.cs
@@ -0,0 +1,492 @@
+// <copyright file="FileSafety.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd;
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+
+/// <summary>
+/// Utility functions to help safely work with paths from untrusted sources.
+/// </summary>
+public static class FileSafety
+{
+ /// <summary>
+ /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc).
+ /// </summary>
+ public static readonly char[] InvalidFileNameCharactersOnUnix = ['\0', '/'];
+
+ /// <summary>
+ /// Invalid filename characters on Windows.
+ /// </summary>
+ 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
+ private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]?", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix
+
+ /// <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="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, 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, OperatingSystem? os, params string[] segments)
+ {
+ // ensure no inputs are null. matches the behavior of Path.Combine()
+ if (string.IsNullOrWhiteSpace(root))
+ {
+ 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");
+ }
+
+ root = root.TrimEnd('/', '\\');
+
+ if (segments.Length == 0)
+ {
+ return root;
+ }
+
+ var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows();
+ var sep = isWindows ? '\\' : '/';
+
+ foreach (var segment in segments)
+ {
+ // disallow any segments that:
+ // windows: are drive letter (C:\) or UNC path (\\)
+ // linux: begin with a forward slash (any number, covering both local and UNC paths)
+ if (IsPathAbsolute(segment, os))
+ {
+ 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('\\', '/');
+
+ // ensure the segments we're combining don't contain traversal segments "." or ".."
+ // untrusted input could use this to "break out" of the root directory and access sensitive areas
+ // this covers cases where the entire segment is . or .., or foo\..\bar, or \.. or ..\ or \..\
+ if (parts.Any(s => s is "." or ".."))
+ {
+ throw new ArgumentException($"Path traversal is not permitted in segments: '{segment}'");
+ }
+ }
+
+ segments = [.. segments
+ .Where(s => !string.IsNullOrEmpty(s))];
+
+ var combined = string.Join(sep, [root, .. segments]);
+
+ if (combined.TrimEnd('/', '\\') == root.TrimEnd('/', '\\'))
+ {
+ return combined;
+ }
+
+ // 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 (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\"))
+ {
+ throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed");
+ }
+
+ return combined;
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether the specified <paramref name="path"/> contains path traversal segments.
+ /// </summary>
+ /// <param name="path">The path to check.</param>
+ /// <returns>True if one or more segments is present, false otherwise.</returns>
+ 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) 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 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, OperatingSystem? os = null)
+ {
+ if (string.IsNullOrEmpty(path))
+ {
+ return false;
+ }
+
+ if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows())
+ {
+ // 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;
+ }
+
+ // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with /
+ if (path.StartsWith('/'))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// 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, OperatingSystem? os = null) => !IsPathAbsolute(path, os);
+
+ /// <summary>
+ /// Returns the filename from the specified <paramref name="path"/>, properly
+ /// handling both forward and backslashes and removing invalid characters.
+ /// </summary>
+ /// <param name="path">The path from which to extract the filename.</param>
+ /// <param name="sanitize">An optional value indicating that invalid characters should not be replaced.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The extracted filename.</returns>
+ public static string GetFileNameSafely(string path, bool sanitize = true, OperatingSystem? os = null)
+ {
+ if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\'))
+ {
+ return null;
+ }
+
+ if (StripPathRoot(path, os) == string.Empty)
+ {
+ return null;
+ }
+
+ var localPath = LocalizePath(path, os);
+ var segments = localPath.Split('/', '\\');
+
+ return segments
+ .TakeLast(1)
+ .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)
+ .Single();
+ }
+
+ /// <summary>
+ /// Returns the full directory name from the specified <paramref name="path"/>, properly handling both
+ /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments, and sanitizing
+ /// each of the remaining segments.
+ /// </summary>
+ /// <param name="path">The path from which to extract the directory name.</param>
+ /// <param name="retainRoot">An optional value indicating whether to keep the path's root, if present.</param>
+ /// <param name="sanitize">An optional value indicating that path segments should not be sanitized.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The directory name.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the specified path is null.</exception>
+ public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OperatingSystem? os = null)
+ {
+ if (path is null or "")
+ {
+ return null;
+ }
+
+ // a plain string is assumed to be a file. matches the behavior of the BCL method
+ if (!path.Contains('/') && !path.Contains('\\'))
+ {
+ return null;
+ }
+
+ var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count();
+
+ os ??= Compute.OperatingSystem();
+ var sep = os.Value == OperatingSystem.Windows ? '\\' : '/';
+
+ var local = LocalizePath(path, os)
+ .TrimEnd('/', '\\'); // treat file-less paths the same as files
+
+ var unrooted = StripPathRoot(local, os);
+
+ // were given a root; C:\, //server, @@abcde
+ if (unrooted is null or "")
+ {
+ return null;
+ }
+
+ if (!retainRoot)
+ {
+ local = unrooted;
+ }
+
+ // strip empty segments
+ var segments = local
+ .Split('/', '\\')
+ .Where(s => s is not "")
+ .ToArray();
+
+ // we were given all slashes, a file in the root, or some other case where
+ // only a file or subdirectory remains; no parent directory
+ if (segments.Length <= 1)
+ {
+ return null;
+ }
+
+ var newPath = string.Join(sep, segments
+ .SkipLast(1)
+ .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s));
+
+ if (retainRoot)
+ {
+ // leading slashes are stripped of leading slashes by Split() so we must add them back
+ return new string(sep, leadingSlashCount) + newPath;
+ }
+
+ return newPath;
+ }
+
+ /// <summary>
+ /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar).
+ /// </summary>
+ /// <param name="path">The path to convert.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The converted path.</returns>
+ public static string LocalizePath(string path, OperatingSystem? os = null)
+ {
+ if (path is null)
+ {
+ return null;
+ }
+
+ os ??= Compute.OperatingSystem();
+ var sep = os.Value == OperatingSystem.Windows ? '\\' : '/';
+
+ return path.Replace('\\', sep).Replace('/', sep);
+ }
+
+ /// <summary>
+ /// Sanitizes the specified <paramref name="filename"/> (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
+ /// replacing any invalid characters with the specified <paramref name="replacement"/>.
+ /// </summary>
+ /// <param name="filename">The filename (or string intended to be used as/part of one).</param>
+ /// <param name="replacement">The character to substitute for invalid characters.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The sanitized filename.</returns>
+ public static string SanitizeFilename(string filename, char replacement = '_', OperatingSystem? os = null)
+ {
+ if (filename is null)
+ {
+ return null;
+ }
+
+ if (replacement is '/' or '\\')
+ {
+ throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames");
+ }
+
+ os ??= Compute.OperatingSystem();
+
+ var characters = os.Value == OperatingSystem.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);
+ }
+
+ /// <summary>
+ /// Sanitizes the specified <paramref name="segment"/> to make it suitable and safe on the local operating
+ /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified
+ /// <paramref name="replacement"/>.
+ /// </summary>
+ /// <param name="segment">The path segment.</param>
+ /// <param name="replacement">The character to substitute for invalid characters.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The sanitized path segment.</returns>
+ public static string SanitizePathSegment(string segment, char replacement = '_', OperatingSystem? os = null)
+ {
+ var sanitized = SanitizeFilename(segment, replacement, os);
+
+ // is is possible for the result of sanitization to produce path traversal strings,
+ // which would result in traversal when combined (or throw an error because of CombineSafely)
+ // this can happen either because the segment is already periods, or because the replacement
+ // character is a period and the input one or two invalid characters.
+ // if this happens we follow the principle of least surprise and return an empty string
+ // avoid using a period for replacement (don't let users choose) and we won't have this problem
+ if (sanitized is "." or "..")
+ {
+ if (replacement is '.')
+ {
+ return string.Empty;
+ }
+
+ return replacement.ToString();
+ }
+
+ return sanitized;
+ }
+
+ /// <summary>
+ /// Sanitizes the specified <paramref name="path"/> to make it suitable and safe on the local operating system
+ /// by converting to the correct slashes, replacing any invalid characters with the specified
+ /// <paramref name="replacement"/>, and by dropping any path traversal segments.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <param name="replacement">The character to substitute for invalid characters.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The sanitized path.</returns>
+ public static string SanitizePath(string path, char replacement = '_', OperatingSystem? os = null)
+ {
+ if (path is null)
+ {
+ return null;
+ }
+
+ os ??= Compute.OperatingSystem();
+ var sep = os.Value == OperatingSystem.Windows ? '\\' : '/';
+
+ // flip slashes the correct way
+ path = LocalizePath(path, os);
+
+ // for each segment, drop nulls (created by double slashes), sanitize, replace traversal strings,
+ // and drop any segments that sanitization reduced to empty (e.g. a single invalid char with '.' replacement)
+ var segments = path
+ .Split('/', '\\')
+ .Where(s => s is not "")
+ .Select(s => SanitizePathSegment(s, replacement, os))
+ .Where(s => s is not "");
+
+ var newPath = string.Join(sep, segments);
+
+ return newPath;
+ }
+
+ /// <summary>
+ /// Removes the root of the specified <paramref name="path"/>, including Window's drive prefix (e.g. C:\),
+ /// UNC paths on any OS (e.g. \\server on Windows, //server on Linux), and drops the hashed prefix added by
+ /// Soulseek Qt to hide the path on disk (e.g. @@abcde).
+ /// </summary>
+ /// <param name="path">The path to strip.</param>
+ /// <param name="os">An optional operating system override, for testing.</param>
+ /// <returns>The path with the root stripped, if one was present.</returns>
+ public static string StripPathRoot(string path, OperatingSystem? os = null)
+ {
+ if (path is null)
+ {
+ return null;
+ }
+
+ // flip slashes the correct way
+ path = LocalizePath(path, os);
+
+ // strip C:\ or //server, if present (regardless of slash variant)
+ path = DriveRootRegex.Replace(path, string.Empty);
+ path = UncRootRegex.Replace(path, string.Empty);
+
+ // strip @@abcde prefixes used by SoulseekQt to obscure paths
+ path = SoulseekQtRootRegex.Replace(path, string.Empty);
+
+ return path;
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
index a7e7e0dc..760f7ba9 100644
--- a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
+++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
@@ -36,7 +36,7 @@ using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
-using Microsoft.OpenApi.Models;
+using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
/// <summary>
diff --git a/src/slskd/Common/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs
new file mode 100644
index 00000000..0c3dae2c
--- /dev/null
+++ b/src/slskd/Common/OperatingSystem.cs
@@ -0,0 +1,43 @@
+// <copyright file="OperatingSystem.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd;
+
+public enum OperatingSystem
+{
+ None = 0,
+ Linux = 1,
+ Windows = 2,
+ Current = 3,
+ Any = 4,
+ All = 5,
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
new file mode 100644
index 00000000..217a4eea
--- /dev/null
+++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
@@ -0,0 +1,81 @@
+// <copyright file="AbsolutePathAttribute.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the specified path is absolute.
+ /// </summary>
+ public class AbsolutePathAttribute : ValidationAttribute
+ {
+ public AbsolutePathAttribute(OperatingSystem os = OperatingSystem.Current)
+ {
+ if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All)
+ {
+ throw new System.ArgumentException("OperatingSystem argument for AbsolutePathAttribute must be one of: Current, Any, All", nameof(os));
+ }
+
+ OS = os;
+ }
+
+ public OperatingSystem OS { get; }
+ private OperatingSystem? Injected { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value != null && value is string str && !string.IsNullOrEmpty(str))
+ {
+ var path = value.ToString();
+
+ if (OS == OperatingSystem.Current)
+ {
+ if (!FileSafety.IsPathAbsolute(path, os: Injected ?? Compute.OperatingSystem()))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on the current operating system.");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ // OS == OperatingSystem.All or .Any
+ if (!FileSafety.IsPathAbsolute(path, os: OperatingSystem.Linux) || !FileSafety.IsPathAbsolute(path, os: OperatingSystem.Windows))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on all operating systems.");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs
new file mode 100644
index 00000000..7c04f1f9
--- /dev/null
+++ b/src/slskd/Common/Validation/GuidAttribute.cs
@@ -0,0 +1,81 @@
+// <copyright file="GuidAttribute.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System;
+
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the value is a valid Guid.
+ /// </summary>
+ public class GuidAttribute : ValidationAttribute
+ {
+ public GuidAttribute(bool allowEmpty = false)
+ {
+ AllowEmpty = allowEmpty;
+ }
+
+ public bool AllowEmpty { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value is null)
+ {
+ return ValidationResult.Success;
+ }
+
+ if (value is Guid guid)
+ {
+ if (!AllowEmpty && guid == Guid.Empty)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ if (value is string str && Guid.TryParse(str, out guid))
+ {
+ if (!AllowEmpty && guid == Guid.Empty)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID");
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs
index 8f87e479..1e2616bd 100644
--- a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs
+++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs
@@ -1,4 +1,4 @@
-// <copyright file="AbsoluteFilePathAttribute.cs" company="JP Dillingham">
+// <copyright file="NonTraversingPathAttribute.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
@@ -33,22 +33,21 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
- using System.IO;
/// <summary>
- /// Validates that the specified path is absolute.
+ /// Validates that the specified path does not contain traversal segments '.' or '..'.
/// </summary>
- public class AbsoluteFilePathAttribute : ValidationAttribute
+ public class NonTraversingPathAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
- if (value != null)
+ if (value != null && value is string str && !string.IsNullOrEmpty(str))
{
- var filePath = value.ToString();
+ var path = value.ToString();
- if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath))
+ if (FileSafety.ContainsTraversalSegments(path))
{
- return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path.");
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
}
}
diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs
new file mode 100644
index 00000000..ea2b627b
--- /dev/null
+++ b/src/slskd/Common/Validation/RelativePathAttribute.cs
@@ -0,0 +1,82 @@
+// <copyright file="RelativePathAttribute.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+
+ /// <summary>
+ /// Validates that the specified path is relative.
+ /// </summary>
+ public class RelativePathAttribute : ValidationAttribute
+ {
+ public RelativePathAttribute(OperatingSystem os = OperatingSystem.Current)
+ {
+ if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All)
+ {
+ throw new System.ArgumentException("OperatingSystem argument for RelativePathAttribute must be one of: Current, Any, All", nameof(os));
+ }
+
+ OS = os;
+ }
+
+ public OperatingSystem OS { get; }
+
+ private OperatingSystem? Injected { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value != null && value is string str && !string.IsNullOrEmpty(str))
+ {
+ var path = value.ToString();
+
+ if (OS == OperatingSystem.Current)
+ {
+ if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem()))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system.");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ // OS == OperatingSystem.All or .Any;
+ if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems.");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs
new file mode 100644
index 00000000..bb323ba2
--- /dev/null
+++ b/src/slskd/Common/Validation/StringAttribute.cs
@@ -0,0 +1,99 @@
+// <copyright file="StringAttribute.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ Copyright (c) JP Dillingham.
+// │
+// │ This program is free software: you can redistribute it and/or modify
+// │ it under the terms of the GNU Affero General Public License as published
+// │ by the Free Software Foundation, version 3.
+// │
+// │ This program is distributed in the hope that it will be useful,
+// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
+// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// │ GNU Affero General Public License for more details.
+// │
+// │ You should have received a copy of the GNU Affero General Public License
+// │ along with this program. If not, see https://www.gnu.org/licenses/.
+// │
+// │ This program is distributed with Additional Terms pursuant to Section 7
+// │ of the AGPLv3. See the LICENSE file in the root directory of this
+// │ project for the complete terms and conditions.
+// │
+// │ https://slskd.org
+// │
+// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
+// │ SPDX-FileCopyrightText: JP Dillingham
+// │ SPDX-License-Identifier: AGPL-3.0-only
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+ using System.Linq;
+ using System.Text.RegularExpressions;
+
+ /// <summary>
+ /// Validates that the value is not null or whitespace.
+ /// </summary>
+ public class StringAttribute : ValidationAttribute
+ {
+ public bool AllowNull { get; set; } = true;
+ public bool AllowEmpty { get; set; } = true;
+ public bool AllowWhiteSpace { get; set; } = true;
+ public char[] DisallowedCharacters { get; set; } = [];
+ public int MinimumLength { get; set; } = 0;
+ public int MaximumLength { get; set; } = int.MaxValue;
+ public Regex Pattern { get; set; } = null;
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ var val = (string)value;
+
+ if (val is null)
+ {
+ if (!AllowNull)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not be null");
+ }
+ else
+ {
+ return ValidationResult.Success;
+ }
+ }
+
+ if (!AllowEmpty && val is "")
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must contain at least one character");
+ }
+
+ // check this after empty to avoid overlap
+ if (!AllowWhiteSpace && val.All(c => char.IsWhiteSpace(c)))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace");
+ }
+
+ if (val.Length < MinimumLength || val.Length > MaximumLength)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be between {MinimumLength} and {MaximumLength} characters");
+ }
+
+ var invalid = val.Where(c => DisallowedCharacters.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d)));
+
+ if (invalid.Any())
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}");
+ }
+
+ if (Pattern is not null && Pattern.IsMatch(val))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}");
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+}