Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@

package org.apache.hertzbeat.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* the common function for jexl str equals, match, contains, etc.
* sys:now()
* sys:now()
*/
public class JexlCommonFunction {

Expand Down Expand Up @@ -94,5 +95,27 @@ public boolean matches(String str, String regex) {
}
return Pattern.compile(regex).matcher(str).matches();
}


/**
* Extracting groups from strings using regular expressions
* @param str Input string
* @param regex regular expression pattern
* @param groupIndex The group index to be extracted (0 for the entire match, 1 for the first group)
* @ return The extracted string does not match and returns null
*/
public String group(String str, String regex, int groupIndex) {
if (str == null || regex == null) {
return null;
}
try {
Matcher matcher = Pattern.compile(regex).matcher(str);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prevent ReDoS attacks here !

if (matcher.find() && groupIndex <= matcher.groupCount()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

incomplete boundary checks

return matcher.group(groupIndex);
}
} catch (Exception e) {
// Return null when regular expression is incorrect

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

silent exception?

}
return null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,19 @@ void testMatchesFunctionWithRegexNotMatch() {
Assertions.assertFalse((Boolean) o);
}

@Test
void testGroupFunctionWithRegexWithGroupIndex() {
Map<String, Object> functions = Maps.newLinkedHashMap();
functions.put("sys", new JexlCommonFunction());
jexlBuilder.namespaces(functions);
JexlEngine jexl = jexlBuilder.create();
JexlContext context = new MapContext();
context.set("x", "akka.tcp://flink@hdp-hadoop3:45534/user/rpc/taskmanager_0");
JexlExpression e = jexl.createExpression("sys:group(x, '@([^:]+):',1)");
Object o = e.evaluate(context);
Assertions.assertEquals("hdp-hadoop3", o);
}

@Test
void testMatchesFunctionWithRegexAndSpace() {
Map<String, Object> functions = Maps.newLinkedHashMap();
Expand Down