jruizgit / rules

Durable Rules Engine
MIT License
1.14k stars 209 forks source link

Bugfix/out of bounds in reduce expression sequence #386

Open meigelb opened 2 years ago

meigelb commented 2 years ago

Bugfix

An issue is fixed which occurs while reducing sequences of expressions in beta nodes involving binary logical operators. This fixes jruizgit/rules#381.

Description

The issue is caused by a missing update of currentExpression in reduceExpressionSequence() after index i, which refers to the current expression, and currentExpression became inconsistent:

  1. If the currentExpression (e1) represents a binary logical operator (OP_AND, OP_OR), it will increment i to the next expression (e2) and call reduceExpressionSequence() recursively.
  2. If e2 does not represent a binary logical operator, it calls reduceExpression() and will increment i again to the next expression (e3). This invalidates currentExpression which still refers to e2.
  3. In the following it is checked, whether further expressions can be skipped as a shortcut since the result of the binary logical operator is already clear. Therefore, it loops until an expression with operator OP_END is found.
  4. The bug is caused by starting at currentExpression, which still refers to e2 instead of e3. Then it increments i to next expression (e4) and checks its operator to be different from OP_END. It continues with e5, e6 and so on. In case e3 - which has never been checked - was OP_END, the loop did not terminate. Incrementing i further can lead to out-of-bounds access in array exprs->expressions[].

Please note: The issue will also occur, if two subsequent expressions with binary logical operators exist (maybe from nesting?). This case is even worse, since recursive call of reduceExpressionSequence() may increment i even further (and i is a pointer in the argument of this function).

Solution

After i increments, currentExpression must be updated consistently. In cases without binary logical operators, this is done right at the beginning of the loop. An additional update in the next statement after the increment would cause only additional runtime without benefit. Hence, the fix updates currentExpression only in the special case of the binary logical operators, just before it is accessed. This does not cost any additional runtime for all other cases.