diff --git a/Directory.Packages.props b/Directory.Packages.props index e56b9af..56e638b 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,6 +9,6 @@ - + \ No newline at end of file diff --git a/README.md b/README.md index 218b8d9..26a7951 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,16 @@ public bool IsEnabled(LogEvent logEvent) This makes it easy to create dynamic, human-readable expressions for filtering or evaluating objects at runtime. +### Limits + +An expression tree can be at most 256 levels deep. Each operator, member access, call, indexer, +and pair of parentheses adds a level, so `a + b + c` counts as deeply as `((a + b) + c)`. +Parsing fails with an error rather than crashing the process when an expression is deeper than that, +or when it is nested too deeply to fit on the stack of the current thread. + +Parsing an expression takes time and memory that grow with its length, +so limit the length of expressions that come from untrusted sources. + ## Supported Versions | | Version | diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs index 16760db..7c8e1cf 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs @@ -16,6 +16,19 @@ public partial class ExpressionBuilder(Binder binder) : ExprVisitor /// public Binder Binder { get; } = binder; + /// + /// + /// Throws a if the thread's stack is too small + /// to visit the expression safely. + /// + public override Expression Visit(Expr expr) + { + if (!RuntimeHelpers.TryEnsureSufficientExecutionStack()) + Error.Throw("The expression is nested too deeply."); + + return base.Visit(expr); + } + /// protected internal override Expression VisitReference(Expr.Reference expr) { diff --git a/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs b/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs index 9c71eee..46bc185 100644 --- a/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs +++ b/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs @@ -6,9 +6,27 @@ namespace Ramstack.Parsing; partial class ExpressionParser { + /// + /// The maximum depth of an expression tree produced by the parser. + /// + /// + /// The expression builder, the ToString methods of the expression nodes, and other visitors + /// process the tree recursively. + /// On a 1 MB stack, the expression builder runs out of stack at a depth of about 1,000 in a Debug build, + /// so the limit leaves room for the caller's own stack frames. + /// + private const int MaxDepth = 256; + /// /// Gets the sub-expression parser, which serves as the base parser for expressions. /// + /// + /// Parsing stops with a fatal error if the expression tree is deeper than 256 levels. + /// Each operator, member access, call, indexer, and pair of parentheses adds a level, + /// so a chain such as a + b + c counts as deeply as the nested expression ((a + b) + c). + /// Parsing also stops with a fatal error if the thread's stack runs short. On a small stack, this can happen + /// before the limit is reached for deeply nested parentheses, arguments, indexers, and conditional expressions. + /// public static Parser Subparser { get; } = CreateParser(); /// @@ -131,7 +149,12 @@ private static Parser CreateParser() expr = indexer ? new Expr.Indexer(expr, parameters) : new Expr.Call(expr, parameters); - return expr; + + // + // HijackMemberExpression processes this chain recursively during parsing, + // so check the depth before the chain reaches it. + // + return EnsureDepth(expr); }); var member_expression = @@ -241,25 +264,44 @@ static Expr HijackMemberExpression(Expr result, Expr value) L("??").ThenIgnore(S).Do(CreateIdentifier), (lhs, rhs, op) => new Expr.Binary(op, lhs, rhs)); - var conditional_expression = Deferred(); - conditional_expression.Parser = + var conditional_expression = Seq( null_coalesce_expression, Seq( L('?'), S, expression, L(':').Or(Fail("Expected ':'")), S, - conditional_expression.Or(Fail("Expected expression")) + expression.Or(Fail("Expected expression")) ).Optional() ).Do(Expr (Expr condition, OptionalValue<(char, Unit, Expr @true, char, Unit, Expr @false)> optional) => optional.HasValue ? new Expr.Conditional(condition, optional.Value.@true, optional.Value.@false) : condition); + // + // Every recursion of the grammar (parentheses, arguments, indexers, and both branches + // of a conditional expression) re-enters it through this parser, so a single check + // protects the parser from a stack overflow on deeply nested input. + // expression.Parser = - conditional_expression; + new StackGuardParser(conditional_expression); + + return S.Then(expression).Do(EnsureDepth); + } + + /// + /// Stops parsing with a fatal error if the specified expression tree is deeper than . + /// + /// The expression tree to check. + /// + /// The specified expression tree. + /// + private static Expr EnsureDepth(Expr expr) + { + if (expr.Depth > MaxDepth) + FatalError($"The expression exceeds the maximum depth of {MaxDepth}."); - return S.Then(expression); + return expr; } private static Identifier CreateIdentifier(string v) => diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs index c2f1561..210fd3c 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs @@ -5,7 +5,8 @@ partial class Expr /// /// Represents a binary operation expression in an expression tree, consisting of an operator and two operands. /// - public sealed class Binary(Identifier @operator, Expr lhs, Expr rhs) : Expr(ExprKind.Binary) + public sealed class Binary(Identifier @operator, Expr lhs, Expr rhs) + : Expr(ExprKind.Binary, Math.Max(lhs.Depth, rhs.Depth) + 1) { /// /// Gets the operator of the binary expression. diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs index b1141e1..81282c7 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs @@ -7,7 +7,8 @@ partial class Expr /// [SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", Justification = "The type is named after the ExprKind.Call expression kind, and renaming it would break the public API.")] - public sealed class Call(Expr expression, IReadOnlyList parameters) : Expr(ExprKind.Call) + public sealed class Call(Expr expression, IReadOnlyList parameters) + : Expr(ExprKind.Call, ComputeDepth(expression, parameters)) { /// /// Gets the expression being called, such as a method or function reference. diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs index 077b210..057c15d 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs @@ -5,7 +5,8 @@ partial class Expr /// /// Represents a conditional (ternary) expression in an expression tree. /// - public sealed class Conditional(Expr test, Expr ifTrue, Expr ifFalse) : Expr(ExprKind.Conditional) + public sealed class Conditional(Expr test, Expr ifTrue, Expr ifFalse) + : Expr(ExprKind.Conditional, Math.Max(test.Depth, Math.Max(ifTrue.Depth, ifFalse.Depth)) + 1) { /// /// Gets the condition expression evaluated to determine the outcome. diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs index 42df46c..810b30a 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs @@ -5,7 +5,8 @@ partial class Expr /// /// Represents an indexing operation in an expression tree, such as accessing an array or a parameterized property. /// - public sealed class Indexer(Expr expression, IReadOnlyList parameters) : Expr(ExprKind.Index) + public sealed class Indexer(Expr expression, IReadOnlyList parameters) + : Expr(ExprKind.Index, ComputeDepth(expression, parameters)) { /// /// Gets the expression being indexed, such as an array or object with an indexer. diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs index 4017429..3428cc2 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs @@ -6,7 +6,8 @@ partial class Expr /// Represents a member access operation in an expression tree, /// such as accessing a field or property like obj.Property. /// - public sealed class MemberAccess(Expr expression, Expr member) : Expr(ExprKind.MemberAccess) + public sealed class MemberAccess(Expr expression, Expr member) + : Expr(ExprKind.MemberAccess, Math.Max(expression.Depth, member.Depth) + 1) { /// /// Gets the expression whose member is being accessed. diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs index 36ad1c2..bd21709 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs @@ -6,7 +6,8 @@ partial class Expr /// Represents a parenthesized expression in an expression tree, used to enforce precedence or grouping. /// /// The enclosed within parentheses. - public sealed class Parenthesized(Expr expression) : Expr(ExprKind.Parenthesized) + public sealed class Parenthesized(Expr expression) + : Expr(ExprKind.Parenthesized, expression.Depth + 1) { /// /// Gets the expression enclosed within parentheses. diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs index 37cf3e3..b779d61 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs @@ -8,7 +8,8 @@ partial class Expr /// The representing the unary operator, e.g., "-" or "int". /// The specifying the kind of unary operation (e.g., arithmetic or conversion). /// The on which the unary operation is applied. - public sealed class Unary(Identifier @operator, UnaryType unaryType, Expr operand) : Expr(ExprKind.Unary) + public sealed class Unary(Identifier @operator, UnaryType unaryType, Expr operand) + : Expr(ExprKind.Unary, operand.Depth + 1) { /// /// Gets the operator of the unary expression. diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.cs index 59ad12a..50294f8 100644 --- a/src/Ramstack.ExpressionParser/Expressions/Expr.cs +++ b/src/Ramstack.ExpressionParser/Expressions/Expr.cs @@ -13,6 +13,45 @@ public abstract partial class Expr(ExprKind kind) /// public ExprKind Kind { get; init; } = kind; + /// + /// Gets the depth of this expression node. + /// + /// + /// One for a node without child expressions; otherwise, one more than the depth of its deepest child. + /// + /// + /// The depth is computed from the depths of the children when the node is created, + /// so the tree is not traversed recursively. + /// + internal int Depth { get; } = 1; + + /// + /// Initializes a new instance of the class with the specified kind and depth. + /// + /// The kind of this expression node. + /// The depth of this expression node. + private Expr(ExprKind kind, int depth) : this(kind) => + Depth = depth; + + /// + /// Computes the depth of a node whose children are the specified expression and the specified list of expressions. + /// + /// The first child expression. + /// The remaining child expressions. + /// + /// One more than the depth of the deepest child. + /// + private static int ComputeDepth(Expr expression, IReadOnlyList list) + { + var depth = expression.Depth; + var count = list.Count; + + for (var i = 0; i < count; i++) + depth = Math.Max(depth, list[i].Depth); + + return depth + 1; + } + /// /// Deconstructs the expression into its kind. /// diff --git a/src/Ramstack.ExpressionParser/Parsers/StackGuardParser.cs b/src/Ramstack.ExpressionParser/Parsers/StackGuardParser.cs new file mode 100644 index 0000000..2b317c0 --- /dev/null +++ b/src/Ramstack.ExpressionParser/Parsers/StackGuardParser.cs @@ -0,0 +1,27 @@ +namespace Ramstack.Parsing.Parsers; + +/// +/// Represents a parser that stops parsing with a fatal error when the thread's stack +/// is too small to run the underlying parser safely. +/// +/// +/// Wrap the parser through which a recursive grammar re-enters itself, so that deeply nested input +/// produces a parse error instead of a . +/// +/// The type of the value produced by the underlying parser. +/// The underlying parser. +internal sealed class StackGuardParser(Parser parser) : Parser +{ + /// + public override bool TryParse(ref ParseContext context, [NotNullWhen(true)] out T? value) + { + if (!RuntimeHelpers.TryEnsureSufficientExecutionStack()) + Parser.FatalError("The expression is nested too deeply."); + + return parser.TryParse(ref context, out value); + } + + // + // NOTE: The default void wrapper calls TryParse, so the check also runs when the value is discarded. + // +} diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index 0c99636..3b93928 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -1,5 +1,8 @@ using System.Globalization; using System.Linq.Expressions; +using System.Runtime.ExceptionServices; + +using Ramstack.Parsing.Expressions; namespace Ramstack.Parsing; @@ -34,6 +37,72 @@ private static List EvaluatesSource } } + private static IEnumerable DeepExpressionSource + { + get + { + const int Count = 200_000; + + yield return Case("prefix operators", new string('-', Count) + "1"); + yield return Case("casts", "1" + Repeat(":int", Count)); + yield return Case("binary operators", string.Join(" + ", Enumerable.Repeat("1", Count))); + yield return Case("null-coalescing operators", string.Join(" ?? ", Enumerable.Repeat("\"a\"", Count))); + yield return Case("member access", "\"a\"" + Repeat(".Length.ToString()", Count)); + yield return Case("indexers", "\"a\"" + Repeat("[0].ToString()", Count)); + yield return Case("calls", "\"a\"" + Repeat("()", Count)); + yield return Case("calls on a member", "\"a\".ToString" + Repeat("()", Count)); + + static TestCaseData Case(string name, string expression) => + new TestCaseData(expression).SetArgDisplayNames(name); + + static string Repeat(string value, int count) => + string.Concat(Enumerable.Repeat(value, count)); + } + } + + private static IEnumerable DeepNestingSource + { + get + { + const int Count = 200_000; + + foreach (var stackSize in new[] { 256 * 1024, 1024 * 1024 }) + { + yield return Case("parentheses", new string('(', Count) + "1" + new string(')', Count), stackSize); + yield return Case("arguments", Repeat("f(", Count) + "1" + Repeat(")", Count), stackSize); + yield return Case("indexers", Repeat("x[", Count) + "1" + Repeat("]", Count), stackSize); + yield return Case("conditional true branches", Repeat("1 > 0 ? ", Count) + "1" + Repeat(" : 1", Count), stackSize); + yield return Case("conditional false branches", Repeat("1 > 0 ? 1 : ", Count) + "1", stackSize); + } + + static TestCaseData Case(string name, string expression, int stackSize) => + new TestCaseData(expression, stackSize).SetArgDisplayNames(name, $"{stackSize / 1024} KB"); + + static string Repeat(string value, int count) => + string.Concat(Enumerable.Repeat(value, count)); + } + } + + private static IEnumerable StackBudgetSource + { + get + { + yield return Case("prefix operators", new string('-', 255) + "1"); + yield return Case("casts", "1" + Repeat(":int", 255)); + yield return Case("binary operators", string.Join(" + ", Enumerable.Repeat("1", 256))); + yield return Case("null-coalescing operators", string.Join(" ?? ", Enumerable.Repeat("\"a\"", 256))); + yield return Case("indexers and calls", "\"abc\"" + Repeat("[0].ToString()", 85)); + yield return Case("conditional operators", Repeat("1 > 0 ? 1 : ", 254) + "1"); + yield return Case("parentheses", new string('(', 150) + "1" + new string(')', 150)); + + static TestCaseData Case(string name, string expression) => + new TestCaseData(expression).SetArgDisplayNames(name); + + static string Repeat(string value, int count) => + string.Concat(Enumerable.Repeat(value, count)); + } + } + [OneTimeSetUp] public void Setup() { @@ -66,6 +135,76 @@ public void ParseErrorExpression(string expression, string expected) Assert.That(result.ToString(), Is.EqualTo(expected)); } + [Test] + public void MaxDepthTest() + { + // + // The literal is the first level, and each operator adds one more level. + // + Assert.That(ExpressionParser.Parse(new string('-', 255) + "1").Success, Is.True); + Assert.That(ExpressionParser.Parse(new string('-', 256) + "1").ToString(), + Is.EqualTo("(1:258) The expression exceeds the maximum depth of 256.")); + + Assert.That(ExpressionParser.Parse(string.Join("+", Enumerable.Repeat("1", 256))).Success, Is.True); + Assert.That(ExpressionParser.Parse(string.Join("+", Enumerable.Repeat("1", 257))).Success, Is.False); + } + + [TestCaseSource(nameof(DeepExpressionSource))] + public void DeepExpressionTest(string expression) + { + var result = ExpressionParser.Parse(expression, new DefaultBinder()); + + Assert.That(result.Success, Is.False); + Assert.That(result.ErrorMessage, Does.EndWith("The expression exceeds the maximum depth of 256.")); + } + + [TestCaseSource(nameof(DeepNestingSource))] + public void DeepNestingTest(string expression, int stackSize) + { + var result = RunOnThread(stackSize, () => ExpressionParser.Parse(expression, new DefaultBinder())); + + Assert.That(result.Success, Is.False); + Assert.That(result.ErrorMessage, Does.EndWith("The expression is nested too deeply.")); + } + + [TestCaseSource(nameof(StackBudgetSource))] + public void StackBudgetTest(string expression) + { + // + // The default stack of a thread on Windows is 1 MB, so the expressions at the maximum depth + // and moderately nested parentheses must be parsed and built on such a stack. + // + var result = RunOnThread(1024 * 1024, () => ExpressionParser.Parse(expression, new DefaultBinder())); + Assert.That(result.Success, Is.True, result.ErrorMessage); + } + + [Test] + public void DeepTreeBuildTest() + { + // + // The parser does not produce such a tree, but the tree can be created directly. + // + Expr expr = new Expr.Literal(1); + for (var i = 0; i < 100_000; i++) + expr = new Expr.Unary(new Identifier("-"), UnaryType.Negate, expr); + + var builder = new ExpressionBuilder(new DefaultBinder()); + var exception = RunOnThread(1024 * 1024, () => + { + try + { + builder.Visit(expr); + return null; + } + catch (ParseErrorException e) + { + return e; + } + }); + + Assert.That(exception?.Message, Is.EqualTo("The expression is nested too deeply.")); + } + [TestCaseSource(nameof(ExpressionSource))] public void ParseExpressionTest(string source, string expected) { @@ -80,6 +219,30 @@ public void StringConcatTest(string source, string expected) Assert.That(result.ToString(), Is.EqualTo(expected)); } + private static T RunOnThread(int maxStackSize, Func func) + { + var result = default(T); + var exception = default(ExceptionDispatchInfo); + + var thread = new Thread(() => + { + try + { + result = func(); + } + catch (Exception e) + { + exception = ExceptionDispatchInfo.Capture(e); + } + }, maxStackSize); + + thread.Start(); + thread.Join(); + + exception?.Throw(); + return result!; + } + private static List GetResource(string resourceName) { using var stream = typeof(ExpressionParserTest).Assembly.GetManifestResourceStream($"Ramstack.Parsing.Data.{resourceName}");