Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 54 additions & 4 deletions src/Opc.Ua.Di.Server/SoftwareUpdate/FileSystemPackageStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public sealed class FileSystemPackageStore : ISoftwarePackageStore

private readonly IFileSystemProvider m_provider;
private readonly string m_rootPath;
private readonly string m_rootPrefix;
private readonly TimeProvider m_timeProvider;

#if NET8_0_OR_GREATER
Expand Down Expand Up @@ -109,7 +110,10 @@ public FileSystemPackageStore(
throw new ArgumentException(
"Root path must be a non-empty string.", nameof(rootPath));
}
m_rootPath = rootPath;
m_rootPath = CanonicalizeProviderPath(rootPath, nameof(rootPath));
m_rootPrefix = m_rootPath == "/"
? m_rootPath
: m_rootPath + "/";
m_timeProvider = timeProvider ?? TimeProvider.System;
}

Expand Down Expand Up @@ -299,9 +303,25 @@ await JsonSerializer

private string BuildPath(string packageId, string? leaf = null)
{
string root = m_rootPath.TrimEnd('/');
string path = $"{root}/{packageId}";
return leaf == null ? path : $"{path}/{leaf}";
ValidateId(packageId);

string path = m_rootPath == "/"
? $"/{packageId}"
: $"{m_rootPath}/{packageId}";
if (leaf != null)
{
path += $"/{leaf}";
}

string canonicalPath = CanonicalizeProviderPath(path, nameof(packageId));
Comment thread
marcschier marked this conversation as resolved.
Outdated
if (canonicalPath.Length <= m_rootPath.Length ||
!canonicalPath.StartsWith(m_rootPrefix, StringComparison.Ordinal))
{
throw new UnauthorizedAccessException(
"The package path escapes the configured package-store root.");
}

return canonicalPath;
}

private static void ValidateId(string packageId)
Expand All @@ -316,6 +336,36 @@ private static void ValidateId(string packageId)
throw new ArgumentException(
"Package id must not contain path separators.", nameof(packageId));
}
if (packageId is "." or "..")
{
throw new ArgumentException(
"Package id must not be a dot segment.", nameof(packageId));
}
}

private static string CanonicalizeProviderPath(string path, string parameterName)
{
string normalized = path.Replace('\\', '/');
string[] segments = normalized.Split('/');
var canonicalSegments = new List<string>(segments.Length);
Comment thread
marcschier marked this conversation as resolved.
Outdated
foreach (string segment in segments)
{
if (segment.Length == 0)
{
continue;
}
if (segment is "." or "..")
{
throw new ArgumentException(
"Provider-relative paths must not contain dot segments.",
parameterName);
}
canonicalSegments.Add(segment);
}

return canonicalSegments.Count == 0
? "/"
: "/" + string.Join("/", canonicalSegments);
}
}

Expand Down
92 changes: 92 additions & 0 deletions tests/Opc.Ua.Di.Tests/PackageStoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,98 @@ public void FileSystemStoreRejectsIdWithPathSeparator()
}
}

[TestCase(".")]
[TestCase("..")]
public void FileSystemStoreRejectsDotSegmentId(string packageId)
{
string tempRoot = Path.Combine(
Path.GetTempPath(),
"di-pkg-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
try
{
var provider = new PhysicalFileSystemProvider(
rootDirectory: tempRoot,
mountName: "Packages",
isWritable: true);
var store = new FileSystemPackageStore(provider, rootPath: "/Pkgs");

Assert.ThrowsAsync<ArgumentException>(
async () => await store.GetAsync(packageId).ConfigureAwait(false));
}
finally
{
if (Directory.Exists(tempRoot))
{
Directory.Delete(tempRoot, recursive: true);
}
}
}

[TestCase("/Pkgs/./Nested")]
[TestCase("/Pkgs/../Outside")]
[TestCase("\\Pkgs\\..\\Outside")]
public void FileSystemStoreRejectsRootWithDotSegment(string rootPath)
{
string tempRoot = Path.Combine(
Path.GetTempPath(),
"di-pkg-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
try
{
var provider = new PhysicalFileSystemProvider(
rootDirectory: tempRoot,
mountName: "Packages",
isWritable: true);

Assert.That(
() => new FileSystemPackageStore(provider, rootPath),
Throws.TypeOf<ArgumentException>());
}
finally
{
if (Directory.Exists(tempRoot))
{
Directory.Delete(tempRoot, recursive: true);
}
}
}

[Test]
public async Task FileSystemStoreCanonicalizesProviderRelativeRootAsync()
{
string tempRoot = Path.Combine(
Path.GetTempPath(),
"di-pkg-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempRoot);
try
{
var provider = new PhysicalFileSystemProvider(
rootDirectory: tempRoot,
mountName: "Packages",
isWritable: true);
var store = new FileSystemPackageStore(
provider,
rootPath: "\\Pkgs\\\\Nested\\");

await store.AddAsync(
NewMetadata("firmware"),
new MemoryStream([1, 2, 3])).ConfigureAwait(false);
Comment thread
marcschier marked this conversation as resolved.
Outdated

string packageRoot = Path.Combine(tempRoot, "Pkgs", "Nested", "firmware");
Assert.That(File.Exists(Path.Combine(packageRoot, "payload.bin")), Is.True);
Assert.That(File.Exists(Path.Combine(packageRoot, "metadata.json")), Is.True);
Assert.That(File.Exists(Path.Combine(tempRoot, "payload.bin")), Is.False);
}
finally
{
if (Directory.Exists(tempRoot))
{
Directory.Delete(tempRoot, recursive: true);
}
}
}

private static SoftwarePackage NewMetadata(string id)
{
return new(
Expand Down
Loading