Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integer overflow and missing checks when parsing bounds #55

Closed
Sjlver opened this issue Mar 17, 2017 · 0 comments · Fixed by #97
Closed

Integer overflow and missing checks when parsing bounds #55

Sjlver opened this issue Mar 17, 2017 · 0 comments · Fixed by #97

Comments

@Sjlver
Copy link

Sjlver commented Mar 17, 2017

Expressions like x{9999999999999999,3} cause an integer overflow in tre_parse_int. This is undefined behavior in C. The following patch prevents this from happening. The overflow check is a bit conservative, but I don't think this matters.

diff --git a/lib/tre-parse.c b/lib/tre-parse.c
index e113896..4705795 100644
--- a/lib/tre-parse.c
+++ b/lib/tre-parse.c
@@ -588,16 +588,23 @@ static int
 tre_parse_int(const tre_char_t **regex, const tre_char_t *regex_end)
 {
   int num = -1;
+  int overflow = 0;
   const tre_char_t *r = *regex;
   while (r < regex_end && *r >= L'0' && *r <= L'9')
     {
       if (num < 0)
        num = 0;
-      num = num * 10 + *r - L'0';
+      if (num <= (INT_MAX - 9) / 10) {
+        num = num * 10 + *r - L'0';
+      } else {
+        /* This digit could cause an integer overflow. We do not return
+         * directly; instead, consume all remaining digits. */
+        overflow = 1;
+      }
       r++;
     }
   *regex = r;
-  return num;
+  return overflow ? -1 : num;
 }

 

When parsing bounds, the minimum repeat count is not checked if no maximum repeat count is given. For instance, the expression x{999999999,} is accepted by TRE. The following patch fixes this:

diff --git a/lib/tre-parse.c b/lib/tre-parse.c
index 4705795..ebc4856 100644
--- a/lib/tre-parse.c
+++ b/lib/tre-parse.c
@@ -641,7 +641,7 @@ tre_parse_bound(tre_parse_ctx_t *ctx, tre_ast_node_t **result)
     }
 
   /* Check that the repeat counts are sane. */
-  if ((max >= 0 && min > max) || max > RE_DUP_MAX)
+  if ((max >= 0 && min > max) || max > RE_DUP_MAX || min > RE_DUP_MAX)
     return REG_BADBR;
 
 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant