Skip to content

Commit

Permalink
Ensure disk access is safe from malicious input (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
dluc authored Aug 14, 2024
1 parent 91d812b commit e31d590
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions dotnet/WorkbenchConnector/Storage/AgentServiceStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AgentServiceStorage> _log;
private readonly string _path;

Expand Down Expand Up @@ -133,6 +144,7 @@ private async Task<List<T>> GetAllAsync<T>(string prefix, string suffix, Cancell

private string GetAgentFilename(AgentBase agent)
{
EnsureSafe(agent.Id);
return Path.Join(this._path, $"{agent.Id}.agent.json");
}

Expand All @@ -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");
}
}

0 comments on commit e31d590

Please sign in to comment.