aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-05-16 08:46:43 -0500
committerGitHub <noreply@github.com>2026-05-16 08:46:43 -0500
commitbdfb99300ed473791f23a0937d00e6d36250f39c (patch)
tree76c49451de8b072a2d137c81c508242cad9a5207 /src
parent072d9ad430042d1666f3260a57608119ffead254 (diff)
parentf37740a6eaee8ee04b5b517ba186b7f523aa271f (diff)
downloadslskd-bdfb99300ed473791f23a0937d00e6d36250f39c.tar.gz
Merge branch 'master' into dependabot/npm_and_yarn/src/web/fast-uri-3.1.2
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs16
-rw-r--r--src/slskd/Common/CommonExtensions.cs6
-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.cs149
-rw-r--r--src/slskd/Common/Validation/AbsolutePathAttribute.cs (renamed from src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs)19
-rw-r--r--src/slskd/Common/Validation/DisallowedCharactersAttribute.cs71
-rw-r--r--src/slskd/Common/Validation/RelativePathAttribute.cs63
-rw-r--r--src/slskd/Core/Options.cs6
-rw-r--r--src/slskd/Files/FileService.cs4
-rw-r--r--src/slskd/Relay/API/Controllers/RelayController.cs27
-rw-r--r--src/slskd/Relay/RelayClient.cs34
-rw-r--r--src/slskd/Shares/ShareService.cs6
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs6
-rw-r--r--src/web/package-lock.json8
-rw-r--r--src/web/package.json2
16 files changed, 532 insertions, 35 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index e36a5539..e3d212f7 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -572,6 +572,14 @@ namespace slskd
{
Metrics.Enqueue.RequestsReceived.Inc(1);
+ // it shouldn't be possible for us to be sharing any such files, as share paths are required to be absolute and rooted
+ // if someone is requesting a file like this, something is either really wrong, or they are a bad actor
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt from user {Username} to enqueue a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", username, filename);
+ throw new DownloadEnqueueException("File not shared.");
+ }
+
/*
circuit breaker/failsafe:
@@ -1413,6 +1421,14 @@ namespace slskd
/// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns>
private async Task<IEnumerable<Soulseek.Directory>> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory)
{
+ // we shouldn't be sharing any files with these segments because shares are required to be absolute and rooted
+ // if we see this, something has either gone really wrong, or someone is trying something funny
+ if (FileSafety.ContainsTraversalSegments(directory))
+ {
+ Log.Warning("Suspicious attempt from user {Username} to list a directory containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", username, directory);
+ return [];
+ }
+
if (Users.IsBlacklisted(username, endpoint.Address))
{
Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address);
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 77db91ef..e0d56511 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -390,9 +390,10 @@ namespace slskd
/// <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>
+ [Obsolete("Find something more intelligent to do instead of this")]
public static string ToLocalFilename(this string remoteFilename, string baseDirectory)
{
- return Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename());
+ return FileSafety.CombineSafely(baseDirectory, remoteFilename.ToLocalRelativeFilename());
}
/// <summary>
@@ -445,6 +446,7 @@ namespace slskd
/// </summary>
/// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
/// <returns>The converted filename.</returns>
+ [Obsolete("Find something more intelligent to do instead of this")]
public static string ToLocalRelativeFilename(this string remoteFilename)
{
if (string.IsNullOrWhiteSpace(remoteFilename))
@@ -465,7 +467,7 @@ namespace slskd
var file = parts.Last().ReplaceInvalidFileNameCharacters();
var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters();
- return Path.Combine(directory, file);
+ return FileSafety.CombineSafely(directory, file);
}
/// <summary>
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..f94b9c7b
--- /dev/null
+++ b/src/slskd/Common/FileSafety.cs
@@ -0,0 +1,149 @@
+// <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;
+
+/// <summary>
+/// Utility functions to help safely work with paths from untrusted sources.
+/// </summary>
+public static class FileSafety
+{
+ /// <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)
+ {
+ // 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 (segments is null || segments.Any(s => s is null))
+ {
+ throw new ArgumentNullException(nameof(segments), $"One or more segments is null");
+ }
+
+ 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))
+ {
+ throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'");
+ }
+
+ var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/');
+
+ // 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
+ if (parts.Any(s => s is "." or ".."))
+ {
+ throw new ArgumentException($"Path traversal is not permitted: '{segment}'");
+ }
+ }
+
+ var combined = Path.Combine(root, Path.Combine(segments));
+
+ // not sure how we could possibly get here, but if we do, throw.
+ if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root)))
+ {
+ throw new ArgumentException($"Path traversal detected in 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), using
+ /// platform-independent rules that recognize both Unix and Windows absolute path formats.
+ /// </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.
+ /// </remarks>
+ /// <param name="path">The path to check.</param>
+ /// <returns>True if the path is absolute, false otherwise.</returns>
+ public static bool IsPathAbsolute(string path)
+ {
+ 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 '\\')
+ {
+ return true;
+ }
+
+ // 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] == ':')
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether the specified <paramref name="path"/>, using
+ /// platform-independent rules that recognize both Unix and Windows absolute path formats.
+ /// </summary>
+ /// <param name="path">The path to check.</param>
+ /// <returns>True if the path is relative, false otherwise.</returns>
+ public static bool IsPathRelative(string path) => !IsPathAbsolute(path);
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
index 8f87e479..4c9f5e53 100644
--- a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs
+++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
@@ -1,4 +1,4 @@
-// <copyright file="AbsoluteFilePathAttribute.cs" company="JP Dillingham">
+// <copyright file="AbsolutePathAttribute.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
@@ -33,22 +33,27 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
- using System.IO;
/// <summary>
/// Validates that the specified path is absolute.
/// </summary>
- public class AbsoluteFilePathAttribute : ValidationAttribute
+ public class AbsolutePathAttribute : 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.IsPathAbsolute(path))
{
- return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path.");
+ return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path.");
+ }
+
+ // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here
+ if (FileSafety.ContainsTraversalSegments(path))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
}
}
diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs
new file mode 100644
index 00000000..90ed3d81
--- /dev/null
+++ b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs
@@ -0,0 +1,71 @@
+// <copyright file="DisallowedCharactersAttribute.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;
+
+/// <summary>
+/// Validates that the value does not contain any of the <see cref="Disallowed"/> characters.
+/// </summary>
+public class DisallowedCharactersAttribute : ValidationAttribute
+{
+ public DisallowedCharactersAttribute(params char[] disallowed)
+ {
+ Disallowed = disallowed;
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to <see langword="true"/>.
+ /// </summary>
+ public bool IgnoreCase { get; set; } = true;
+
+ private char[] Disallowed { get; }
+
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value is not null and string str)
+ {
+ var invalid = IgnoreCase
+ ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d)))
+ : str.Where(c => Disallowed.Contains(c));
+
+ if (invalid.Any())
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs
new file mode 100644
index 00000000..edaef1be
--- /dev/null
+++ b/src/slskd/Common/Validation/RelativePathAttribute.cs
@@ -0,0 +1,63 @@
+// <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
+ {
+ 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))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path.");
+ }
+
+ // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here
+ if (FileSafety.ContainsTraversalSegments(path))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 8cc369af..51b3cab1 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -198,6 +198,7 @@ namespace slskd
[Argument('i', "instance-name")]
[EnvironmentVariable("INSTANCE_NAME")]
[Description("optional; a unique name for this instance")]
+ [DisallowedCharacters('/', '\\')]
[RequiresRestart]
public string InstanceName { get; init; } = "default";
@@ -654,6 +655,7 @@ namespace slskd
[Description("the name for this agent")]
[StringLength(255, MinimumLength = 1)]
[NotNullOrWhiteSpace]
+ [DisallowedCharacters('/', '\\')]
[Secret]
public string InstanceName { get; init; }
@@ -765,6 +767,7 @@ namespace slskd
[Argument(default, "incomplete")]
[EnvironmentVariable("INCOMPLETE_DIR")]
[Description("path where incomplete downloads are saved")]
+ [AbsolutePath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory;
@@ -775,6 +778,7 @@ namespace slskd
[Argument('o', "downloads")]
[EnvironmentVariable("DOWNLOADS_DIR")]
[Description("path where downloaded files are saved")]
+ [AbsolutePath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Downloads { get; init; } = Program.DefaultDownloadsDirectory;
@@ -2010,7 +2014,7 @@ namespace slskd
[Argument(default, "http-socket")]
[EnvironmentVariable("HTTP_SOCKET")]
[Description("HTTP listen unix domain socket (UDS) path for web UI")]
- [AbsoluteFilePath]
+ [AbsolutePath]
[RequiresRestart]
public string Socket { get; init; }
diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs
index 575619d5..4b281863 100644
--- a/src/slskd/Files/FileService.cs
+++ b/src/slskd/Files/FileService.cs
@@ -164,7 +164,7 @@ namespace slskd.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));
+ bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed);
// if any of the resolved directory paths aren't rooted in one of the allowed directories, forbid the entire request
if (!directories.All(directory => IsAllowed(directory)))
@@ -222,7 +222,7 @@ namespace slskd.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));
+ bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed);
// if any of the resolved file paths aren't rooted in one of the allowed directories, forbid the entire request
if (!files.All(file => IsAllowed(file)))
diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs
index 0d2ef9c5..fdc6dbe6 100644
--- a/src/slskd/Relay/API/Controllers/RelayController.cs
+++ b/src/slskd/Relay/API/Controllers/RelayController.cs
@@ -149,6 +149,14 @@ namespace slskd.Relay
return BadRequest();
}
+ // check the path; the caller has a valid API key but we haven't validated the credential yet, so this is worth
+ // doing here instead of relying on the CombineSafely() backstop
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to download a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ return BadRequest();
+ }
+
Log.Information("Handling file download of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName);
// note: the token remains valid after the validation attempt, unlike most other endpoints.
@@ -159,7 +167,12 @@ namespace slskd.Relay
return Unauthorized();
}
- var sourceFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
+ // if we get this far, the caller has supplied a valid credential and filename, meaning the request
+ // to download is being made in response to the controller signaling the agent that a download had completed.
+ // it's not possible for the client to download arbitrary files; credentials are computed from a token, and
+ // this token is cached in the controller, so only file downloads that the controller solicited are possible
+ // still, for the abundance of caution, use the CombineSafely method in case the filename has traversal segments
+ var sourceFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
Log.Information("Agent {Agent} authenticated for token {Token}. Sending file {Filename}", agentName, guid, filename);
@@ -225,6 +238,14 @@ namespace slskd.Relay
throw new ArgumentException("Upload filename is null or empty");
}
+ // use an abundance of caution; the caller has a valid API key but we haven't validated the credential yet
+ // this is a really unlikely attack vector and it wouldn't do anything, but we're taking a hard stance on input validation
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to upload a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ return BadRequest();
+ }
+
if (stream == null || !stream.CanRead)
{
throw new ArgumentException("Unable to obtain stream from request");
@@ -323,8 +344,8 @@ namespace slskd.Relay
return Unauthorized();
}
- Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName));
- var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_{agentName}_{Path.GetRandomFileName()}.db");
+ Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName));
+ var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{agentName.ReplaceInvalidFileNameCharacters()}_{Path.GetRandomFileName()}.db");
try
{
diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs
index 9aec7b00..2e001bdc 100644
--- a/src/slskd/Relay/RelayClient.cs
+++ b/src/slskd/Relay/RelayClient.cs
@@ -370,6 +370,12 @@ namespace slskd.Relay
private async Task HandleFileInfoRequest(string filename, Guid id)
{
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to request file info containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0);
+ }
+
Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id);
try
@@ -387,8 +393,14 @@ namespace slskd.Relay
}
}
- private Task HandleFileUploadRequest(string filename, long startOffset, Guid token)
+ private async Task HandleFileUploadRequest(string filename, long startOffset, Guid token)
{
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to request a file upload containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token);
+ }
+
_ = Task.Run(async () =>
{
Log.Information("Relay controller requested file {Filename} with ID {Id}", filename, token);
@@ -442,28 +454,32 @@ namespace slskd.Relay
await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token);
}
});
-
- return Task.CompletedTask;
}
- private Task HandleNotifyFileDownloadCompleted(string filename, Guid token)
+ private async Task HandleNotifyFileDownloadCompleted(string filename, Guid token)
{
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to solicit a file download containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename);
+ return;
+ }
+
if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads)
{
- return Task.CompletedTask;
+ return;
}
Log.Information("Relay controller sent a download notification for {Filename} ({Token})", filename, token);
_ = Task.Run(async () =>
{
- var destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
+ var destinationFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename);
if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug)
{
// if we're debugging, we're referencing the same file for both the controller and agent which will lead to an
// access violation. prefix the destination file to avoid this.
- destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed");
+ destinationFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed");
}
// if the controller is Windows and the agent is Linux or vice versa, we need to translate the filename to the
@@ -498,8 +514,6 @@ namespace slskd.Relay
Log.Information("File {Filename} successfully downloaded to {Destination}", filename, destinationFile);
});
-
- return Task.CompletedTask;
}
private Task HubConnection_Closed(Exception arg)
@@ -579,7 +593,7 @@ namespace slskd.Relay
return;
}
- var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db");
+ var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db");
try
{
diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs
index a1dde4eb..054561bf 100644
--- a/src/slskd/Shares/ShareService.cs
+++ b/src/slskd/Shares/ShareService.cs
@@ -188,7 +188,9 @@ namespace slskd.Shares
directories.TryAdd(directory, new Directory(directory));
}
- var files = repositories.SelectMany(r => r.ListFiles(prefix, includeFullPath: true));
+ var files = repositories.SelectMany(r => r.ListFiles(
+ parentDirectory: prefix,
+ includeFullPath: true)); // includes the full *masked* filename; directory and file name and extension. not the local filename.
var groups = files
.GroupBy(file => file.Filename.GetNormalizedDirectoryName())
@@ -280,7 +282,7 @@ namespace slskd.Shares
/// <returns>The contents of the directory.</returns>
public Task<Directory> ListDirectoryAsync(string directory)
{
- var files = AllRepositories.SelectMany(r => r.ListFiles(directory));
+ var files = AllRepositories.SelectMany(r => r.ListFiles(directory, includeFullPath: false));
return Task.FromResult(new Directory(directory, files));
}
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index b6c5fc9d..ed594209 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -418,7 +418,7 @@ namespace slskd.Shares
while (reader.Read())
{
- var filename = reader.GetString(0);
+ var maskedFilename = reader.GetString(0);
var code = reader.GetInt32(1);
var size = reader.GetInt64(2);
var extension = reader.GetString(3);
@@ -426,9 +426,9 @@ namespace slskd.Shares
var attributeList = attributeJson.FromJson<List<FileAttribute>>();
- filename = includeFullPath ? filename : filename.GetNormalizedFileName();
+ maskedFilename = includeFullPath ? maskedFilename : maskedFilename.GetNormalizedFileName();
- var file = new Soulseek.File(code, filename, size, extension, attributeList);
+ var file = new Soulseek.File(code, maskedFilename, size, extension, attributeList);
results.Add(file);
}
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index af43771d..1489044c 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -13,7 +13,7 @@
"@codemirror/legacy-modes": "^6.0.0",
"@microsoft/signalr": "^7.0.7",
"@uiw/react-codemirror": "^4.2.4",
- "axios": "^1.15.0",
+ "axios": "^1.15.2",
"lz-string": "^1.4.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
@@ -5984,9 +5984,9 @@
}
},
"node_modules/axios": {
- "version": "1.15.0",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.0.tgz",
- "integrity": "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==",
+ "version": "1.15.2",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.2.tgz",
+ "integrity": "sha512-wLrXxPtcrPTsNlJmKjkPnNPK2Ihe0hn0wGSaTEiHRPxwjvJwT3hKmXF4dpqxmPO9SoNb2FsYXj/xEo0gHN+D5A==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.11",
diff --git a/src/web/package.json b/src/web/package.json
index 00491c52..57bb8d70 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -18,7 +18,7 @@
"@codemirror/legacy-modes": "^6.0.0",
"@microsoft/signalr": "^7.0.7",
"@uiw/react-codemirror": "^4.2.4",
- "axios": "^1.15.0",
+ "axios": "^1.15.2",
"lz-string": "^1.4.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",