From 4245b4f8188db094bab202b490290101c8a14cff Mon Sep 17 00:00:00 2001 From: Devis Lucato Date: Tue, 13 Aug 2024 18:43:39 -0700 Subject: [PATCH] Ensure disk access is safe from malicious input --- .../Storage/AgentServiceStorage.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/dotnet/WorkbenchConnector/Storage/AgentServiceStorage.cs b/dotnet/WorkbenchConnector/Storage/AgentServiceStorage.cs index 8f995703..d47e326a 100644 --- a/dotnet/WorkbenchConnector/Storage/AgentServiceStorage.cs +++ b/dotnet/WorkbenchConnector/Storage/AgentServiceStorage.cs @@ -12,6 +12,17 @@ public class AgentServiceStorage : IAgentServiceStorage { private static readonly JsonSerializerOptions s_jsonOptions = new() { WriteIndented = true }; + private static readonly char[] s_notSafe = + [ + '\0', '\n', '\r', + Path.PathSeparator, // ':' (nix) or ';' (win) + Path.DirectorySeparatorChar, // '/' (nix) or '\' (win) + Path.VolumeSeparatorChar, // '/' (nix) or ':' (win) + Path.AltDirectorySeparatorChar, // '/' + ]; + + private static readonly char[] s_notSafe2 = Path.GetInvalidPathChars(); + private readonly ILogger _log; private readonly string _path; @@ -133,6 +144,7 @@ private async Task> GetAllAsync(string prefix, string suffix, Cancell private string GetAgentFilename(AgentBase agent) { + EnsureSafe(agent.Id); return Path.Join(this._path, $"{agent.Id}.agent.json"); } @@ -143,11 +155,23 @@ private string GetConversationFilename(Conversation conversation) private string GetConversationFilename(string agentId, string conversationId) { + EnsureSafe(agentId); + EnsureSafe(conversationId); return Path.Join(this._path, $"{agentId}.{conversationId}.conversation.json"); } private string GetInsightFilename(string agentId, string conversationId, string insightId) { + EnsureSafe(agentId); + EnsureSafe(conversationId); + EnsureSafe(insightId); return Path.Join(this._path, $"{agentId}.{conversationId}.{insightId}.insight.json"); } + + private static void EnsureSafe(string input) + { + if (input.IndexOfAny(s_notSafe) < 0 && input.IndexOfAny(s_notSafe2) < 0) { return; } + + throw new ArgumentException("The file or path value contains invalid chars"); + } }