Skip to content

Commit 676ac00

Browse files
authored
[Enhancement] Bound PPL parse/rex regex matching work with a configurable match limit (#5921)
Signed-off-by: Jialiang Liang <jiallian@amazon.com>
1 parent 324971c commit 676ac00

13 files changed

Lines changed: 582 additions & 6 deletions

File tree

‎common/src/main/java/org/opensearch/sql/common/setting/Settings.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ public enum Key {
3232
PATTERN_BUFFER_LIMIT("plugins.ppl.pattern.buffer.limit"),
3333
PATTERN_SHOW_NUMBERED_TOKEN("plugins.ppl.pattern.show.numbered.token"),
3434
PPL_REX_MAX_MATCH_LIMIT("plugins.ppl.rex.max_match.limit"),
35+
PPL_REGEX_MATCH_LIMIT("plugins.ppl.regex.match.limit"),
3536
PPL_VALUES_MAX_LIMIT("plugins.ppl.values.max.limit"),
3637
PPL_SYNTAX_LEGACY_PREFERRED("plugins.ppl.syntax.legacy.preferred"),
3738
PPL_SUBSEARCH_MAXOUT("plugins.ppl.subsearch.maxout"),

‎core/src/main/java/org/opensearch/sql/expression/function/udf/RexExtractFunction.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ private static String executeExtraction(
122122
String text, String pattern, java.util.function.Function<Matcher, String> extractor) {
123123
try {
124124
Pattern compiledPattern = RegexCommonUtils.getCompiledPattern(pattern);
125-
Matcher matcher = compiledPattern.matcher(text);
125+
Matcher matcher = RegexCommonUtils.boundedMatcher(compiledPattern, text);
126126

127127
if (matcher.find()) {
128128
return extractor.apply(matcher);

‎core/src/main/java/org/opensearch/sql/expression/function/udf/RexExtractMultiFunction.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ private static List<String> executeMultipleExtractions(
150150
java.util.function.Function<Matcher, String> extractor) {
151151
try {
152152
Pattern compiledPattern = RegexCommonUtils.getCompiledPattern(pattern);
153-
Matcher matcher = compiledPattern.matcher(text);
153+
Matcher matcher = RegexCommonUtils.boundedMatcher(compiledPattern, text);
154154
List<String> matches = new ArrayList<>();
155155

156156
int matchCount = 0;

‎core/src/main/java/org/opensearch/sql/expression/function/udf/RexOffsetFunction.java‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import org.opensearch.sql.calcite.utils.PPLOperandTypes;
2121
import org.opensearch.sql.expression.function.ImplementorUDF;
2222
import org.opensearch.sql.expression.function.UDFOperandMetadata;
23+
import org.opensearch.sql.expression.parse.RegexCommonUtils;
2324

2425
/** Custom REX_OFFSET function for calculating regex match positions. */
2526
public final class RexOffsetFunction extends ImplementorUDF {
@@ -56,15 +57,17 @@ public static String calculateOffsets(String text, String patternStr) {
5657
}
5758

5859
try {
59-
Pattern pattern = Pattern.compile(patternStr);
60-
Matcher matcher = pattern.matcher(text);
60+
// Bound backtracking work against user text.
61+
Pattern pattern = RegexCommonUtils.getCompiledPattern(patternStr);
62+
Matcher matcher = RegexCommonUtils.boundedMatcher(pattern, text);
6163

6264
if (!matcher.find()) {
6365
return null;
6466
}
6567

6668
List<String> offsetPairs = new java.util.ArrayList<>();
6769

70+
// Fixed internal pattern over the pattern string (enumerates named groups); not user input.
6871
Pattern namedGroupPattern = Pattern.compile("\\(\\?<([^>]+)>");
6972
Matcher namedGroupMatcher = namedGroupPattern.matcher(patternStr);
7073

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.expression.parse;
7+
8+
import java.util.regex.Pattern;
9+
10+
/**
11+
* A {@link CharSequence} that wraps another sequence and caps the total number of {@code charAt}
12+
* accesses a regex engine may perform against it. Once accesses exceed {@code matchLimit} the match
13+
* is aborted with an {@link IllegalArgumentException}, bounding worst-case backtracking work
14+
* without changing the regex engine or affecting normal matches.
15+
*
16+
* <p>The cap is an absolute total (not scaled by input length), analogous to PCRE2's {@code
17+
* match_limit} (and Splunk {@code rex}'s {@code match_limit}, default 100000), which bounds how
18+
* many times the matcher's internal loop runs. A catastrophic pattern re-reads characters far past
19+
* this cap and is aborted in well under a millisecond, regardless of how the attacker sizes the
20+
* input.
21+
*
22+
* <p>Adapted from {@code org.opensearch.painless.api.LimitedCharSequence}; kept plugin-local to
23+
* avoid a {@code lang-painless} dependency.
24+
*/
25+
public final class LimitedCharSequence implements CharSequence {
26+
private final CharSequence wrapped;
27+
private final long matchLimit;
28+
private long count;
29+
30+
// Retained for the error message only.
31+
private final Pattern pattern;
32+
33+
static final int MAX_STR_LENGTH = 64;
34+
private static final String SNIPPET = "...";
35+
36+
/**
37+
* @param wrap the input text the regex engine will read
38+
* @param pattern the pattern being matched (for the error message only; may be null)
39+
* @param matchLimit absolute cap on total charAt reads before the match is aborted; must be
40+
* positive
41+
*/
42+
public LimitedCharSequence(CharSequence wrap, Pattern pattern, long matchLimit) {
43+
if (matchLimit <= 0) {
44+
throw new IllegalArgumentException("matchLimit must be positive");
45+
}
46+
this.wrapped = wrap;
47+
this.matchLimit = matchLimit;
48+
this.pattern = pattern;
49+
}
50+
51+
String details() {
52+
return (pattern != null ? "pattern: [" + pattern.pattern() + "], " : "")
53+
+ "match limit: ["
54+
+ matchLimit
55+
+ "], "
56+
+ "count: ["
57+
+ count
58+
+ "], "
59+
+ "wrapped: ["
60+
+ snippet(MAX_STR_LENGTH)
61+
+ "]";
62+
}
63+
64+
/** Snip a long wrapped CharSequence for error messages. */
65+
String snippet(int maxStrLength) {
66+
if (maxStrLength < SNIPPET.length() * 6) {
67+
throw new IllegalArgumentException(
68+
"max str length must be large enough to include three snippets and three context chars,"
69+
+ " at least ["
70+
+ SNIPPET.length() * 6
71+
+ "], not ["
72+
+ maxStrLength
73+
+ "]");
74+
}
75+
76+
if (wrapped.length() <= maxStrLength) {
77+
return wrapped.toString();
78+
}
79+
80+
return wrapped.subSequence(0, maxStrLength - SNIPPET.length()) + SNIPPET;
81+
}
82+
83+
@Override
84+
public int length() {
85+
return wrapped.length();
86+
}
87+
88+
@Override
89+
public char charAt(int index) {
90+
count++;
91+
if (count > matchLimit) {
92+
throw new IllegalArgumentException(
93+
"Regular expression in PPL parse/rex command considered too many characters, "
94+
+ details()
95+
+ ". The pattern and input combination is too expensive to evaluate (possible"
96+
+ " catastrophic backtracking). This limit can be changed with the"
97+
+ " plugins.ppl.regex.match.limit setting.");
98+
}
99+
return wrapped.charAt(index);
100+
}
101+
102+
@Override
103+
public CharSequence subSequence(int start, int end) {
104+
return wrapped.subSequence(start, end);
105+
}
106+
107+
@Override
108+
public String toString() {
109+
return wrapped.toString();
110+
}
111+
}

‎core/src/main/java/org/opensearch/sql/expression/parse/RegexCommonUtils.java‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818

1919
/**
2020
* Common utilities for regex operations. Provides pattern caching and consistent matching behavior.
21+
*
22+
* <p>Matches against user-supplied text go through {@link #boundedMatcher} to cap backtracking
23+
* work; see {@link LimitedCharSequence}.
2124
*/
2225
public class RegexCommonUtils {
2326

@@ -27,6 +30,35 @@ public class RegexCommonUtils {
2730
// Pattern to extract ANY named group (valid or invalid) for validation
2831
private static final Pattern ANY_NAMED_GROUP_PATTERN = Pattern.compile("\\(\\?<([^>]+)>");
2932

33+
/**
34+
* Default absolute cap on the number of characters the regex engine may read in a single match
35+
* before it is aborted. Mirrors the default of PCRE2's {@code match_limit} as adopted by Splunk
36+
* {@code rex} (100000): high enough never to trip legitimate matches, low enough that a
37+
* catastrophic match aborts in well under a millisecond. Overridable via the {@code
38+
* plugins.ppl.regex.match.limit} setting through {@link #setMatchLimit(long)}.
39+
*/
40+
public static final long DEFAULT_MATCH_LIMIT = 100_000L;
41+
42+
// Node-scoped value, pushed in by the OpenSearch settings layer on register and on dynamic
43+
// change. volatile so updates are visible to matching threads.
44+
private static volatile long matchLimit = DEFAULT_MATCH_LIMIT;
45+
46+
/**
47+
* Set the absolute per-match character-read cap. Called by the OpenSearch settings layer when
48+
* {@code plugins.ppl.regex.match.limit} is registered or changed. Non-positive values are ignored
49+
* (the previous value is kept) so a misconfiguration cannot disable the guard.
50+
*/
51+
public static void setMatchLimit(long limit) {
52+
if (limit > 0) {
53+
matchLimit = limit;
54+
}
55+
}
56+
57+
/** Current absolute per-match character-read cap. */
58+
public static long getMatchLimit() {
59+
return matchLimit;
60+
}
61+
3062
private static final int MAX_CACHE_SIZE = 1000;
3163

3264
private static final Map<String, Pattern> patternCache =
@@ -105,20 +137,33 @@ private static boolean isValidJavaRegexGroupName(String groupName) {
105137
return groupName.matches("^[A-Za-z][A-Za-z0-9]*$");
106138
}
107139

140+
/**
141+
* Create a {@link Matcher} whose backtracking work is bounded by wrapping the input in a {@link
142+
* LimitedCharSequence}. All user-controlled matching (parse and rex) should use this.
143+
*
144+
* @param pattern the compiled pattern
145+
* @param text the input text to match against
146+
* @return a Matcher over a length-bounded view of the text
147+
*/
148+
public static Matcher boundedMatcher(Pattern pattern, String text) {
149+
return pattern.matcher(new LimitedCharSequence(text, pattern, matchLimit));
150+
}
151+
108152
/**
109153
* Match using find() for partial match semantics with string pattern.
110154
*
111155
* @param text The text to match against
112156
* @param patternStr The pattern string
113157
* @return true if pattern is found anywhere in the text
114158
* @throws PatternSyntaxException if the regex is invalid
159+
* @throws IllegalArgumentException if the match exceeds the backtracking bound
115160
*/
116161
public static boolean matchesPartial(String text, String patternStr) {
117162
if (text == null || patternStr == null) {
118163
return false;
119164
}
120165
Pattern pattern = getCompiledPattern(patternStr);
121-
return pattern.matcher(text).find();
166+
return boundedMatcher(pattern, text).find();
122167
}
123168

124169
/**
@@ -128,13 +173,14 @@ public static boolean matchesPartial(String text, String patternStr) {
128173
* @param pattern The compiled pattern with named groups
129174
* @param groupName The name of the group to extract
130175
* @return The extracted value or null if not found
176+
* @throws IllegalArgumentException if the match exceeds the backtracking bound
131177
*/
132178
public static String extractNamedGroup(String text, Pattern pattern, String groupName) {
133179
if (text == null || pattern == null || groupName == null) {
134180
return null;
135181
}
136182

137-
Matcher matcher = pattern.matcher(text);
183+
Matcher matcher = boundedMatcher(pattern, text);
138184

139185
if (matcher.matches()) {
140186
try {
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*
2+
* Copyright OpenSearch Contributors
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package org.opensearch.sql.expression.parse;
7+
8+
import static org.junit.jupiter.api.Assertions.assertEquals;
9+
import static org.junit.jupiter.api.Assertions.assertThrows;
10+
import static org.junit.jupiter.api.Assertions.assertTrue;
11+
12+
import java.util.regex.Pattern;
13+
import org.junit.jupiter.api.Test;
14+
15+
public class LimitedCharSequenceTest {
16+
17+
@Test
18+
public void delegatesLengthAndCharAtAndToString() {
19+
LimitedCharSequence seq = new LimitedCharSequence("abcde", null, 100);
20+
assertEquals(5, seq.length());
21+
assertEquals('a', seq.charAt(0));
22+
assertEquals('e', seq.charAt(4));
23+
assertEquals("abcde", seq.toString());
24+
assertEquals("cd", seq.subSequence(2, 4).toString());
25+
}
26+
27+
@Test
28+
public void rejectsNonPositiveMatchLimit() {
29+
assertThrows(IllegalArgumentException.class, () -> new LimitedCharSequence("abc", null, 0));
30+
assertThrows(IllegalArgumentException.class, () -> new LimitedCharSequence("abc", null, -1));
31+
}
32+
33+
@Test
34+
public void throwsAfterExceedingAbsoluteCap() {
35+
// Absolute cap of 5 charAt reads, independent of input length; the 6th must throw.
36+
LimitedCharSequence seq = new LimitedCharSequence("abc", null, 5);
37+
for (int i = 0; i < 5; i++) {
38+
seq.charAt(0); // 5 reads are allowed (count > limit is the trip condition)
39+
}
40+
assertThrows(IllegalArgumentException.class, () -> seq.charAt(0));
41+
}
42+
43+
@Test
44+
public void capIsAbsoluteNotScaledByLength() {
45+
// A 1000-char input with a cap of 3 still trips on the 4th read — the cap does not scale with
46+
// input length (unlike the old factor model). This is what closes the short-input bypass.
47+
LimitedCharSequence seq = new LimitedCharSequence("x".repeat(1000), null, 3);
48+
seq.charAt(0);
49+
seq.charAt(0);
50+
seq.charAt(0);
51+
assertThrows(IllegalArgumentException.class, () -> seq.charAt(0));
52+
}
53+
54+
@Test
55+
public void errorMessageIncludesPatternAndLimit() {
56+
Pattern pattern = Pattern.compile("(a+)+");
57+
LimitedCharSequence seq = new LimitedCharSequence("ab", pattern, 2);
58+
seq.charAt(0);
59+
seq.charAt(0);
60+
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> seq.charAt(0));
61+
assertTrue(e.getMessage().contains("too many characters"));
62+
assertTrue(e.getMessage().contains("(a+)+"), "should include the offending pattern");
63+
assertTrue(e.getMessage().contains("match limit: [2]"));
64+
assertTrue(e.getMessage().contains("plugins.ppl.regex.match.limit"));
65+
}
66+
67+
@Test
68+
public void snippetTruncatesLongInput() {
69+
String longInput = "x".repeat(200);
70+
LimitedCharSequence seq = new LimitedCharSequence(longInput, null, 1_000_000);
71+
String snippet = seq.snippet(LimitedCharSequence.MAX_STR_LENGTH);
72+
assertTrue(snippet.length() <= LimitedCharSequence.MAX_STR_LENGTH);
73+
assertTrue(snippet.endsWith("..."));
74+
}
75+
76+
@Test
77+
public void snippetReturnsFullShortInput() {
78+
LimitedCharSequence seq = new LimitedCharSequence("short", null, 1_000_000);
79+
assertEquals("short", seq.snippet(LimitedCharSequence.MAX_STR_LENGTH));
80+
}
81+
}

0 commit comments

Comments
 (0)