diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-05-17 15:55:56 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-05-17 15:55:56 -0500 |
| commit | c9acb8fbbb045c8b710fb3430084bd3e6490f00b (patch) | |
| tree | b097960843f3e84af6567cce6f473bf79c1f1806 /src | |
| parent | e3b6bd9954ea330402f1c44719a82fd56f173196 (diff) | |
| parent | 338ed57cd52806e3684ccaedd1f19f5eafd4123a (diff) | |
| download | slskd-c9acb8fbbb045c8b710fb3430084bd3e6490f00b.tar.gz | |
Merge pull request #1733 from slskd/validation
Add or adjust several new validation classes
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/Validation/AbsolutePathAttribute.cs | 6 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/GuidAttribute.cs | 81 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/NonTraversingPathAttribute.cs (renamed from src/slskd/Common/Validation/DisallowedCharactersAttribute.cs) | 44 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/RelativePathAttribute.cs | 6 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/StringAttribute.cs | 99 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 11 |
6 files changed, 204 insertions, 43 deletions
diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 4c9f5e53..1999220f 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { 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 '..')"); - } } return ValidationResult.Success; 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/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs index 90ed3d81..1e2616bd 100644 --- a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs +++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs @@ -1,4 +1,4 @@ -// <copyright file="DisallowedCharactersAttribute.cs" company="JP Dillingham"> +// <copyright file="NonTraversingPathAttribute.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ @@ -30,42 +30,28 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // </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 +namespace slskd.Validation { - public DisallowedCharactersAttribute(params char[] disallowed) - { - Disallowed = disallowed; - } + using System.ComponentModel.DataAnnotations; /// <summary> - /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to <see langword="true"/>. + /// Validates that the specified path does not contain traversal segments '.' or '..'. /// </summary> - public bool IgnoreCase { get; set; } = true; - - private char[] Disallowed { get; } - - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + public class NonTraversingPathAttribute : ValidationAttribute { - if (value is not null and string str) + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - var invalid = IgnoreCase - ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))) - : str.Where(c => Disallowed.Contains(c)); - - if (invalid.Any()) + if (value != null && value is string str && !string.IsNullOrEmpty(str)) { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + var path = value.ToString(); + + if (FileSafety.ContainsTraversalSegments(path)) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); + } } - } - return ValidationResult.Success; + 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 index edaef1be..edbb3483 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { 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; diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs new file mode 100644 index 00000000..807fef4c --- /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; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 51b3cab1..f952f014 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -198,7 +198,6 @@ 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"; @@ -655,7 +654,6 @@ namespace slskd [Description("the name for this agent")] [StringLength(255, MinimumLength = 1)] [NotNullOrWhiteSpace] - [DisallowedCharacters('/', '\\')] [Secret] public string InstanceName { get; init; } @@ -768,6 +766,7 @@ namespace slskd [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -779,6 +778,7 @@ namespace slskd [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; @@ -845,6 +845,12 @@ namespace slskd directories?.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); + // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /.. + // which is resolved by some OS and will cause weird, unintended side effects + bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + directories?.Where(share => ContainsTraversalSegments(share)).ToList() + .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment."))); + (string Raw, string Alias, string Path) Digest(string share) { var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$"); @@ -2015,6 +2021,7 @@ namespace slskd [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] [AbsolutePath] + [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } |
