diff --git a/stix2/pattern_visitor.py b/stix2/pattern_visitor.py index 16e4d3c..b2d7a53 100644 --- a/stix2/pattern_visitor.py +++ b/stix2/pattern_visitor.py @@ -2,7 +2,9 @@ import importlib import inspect from antlr4 import CommonTokenStream, InputStream +from antlr4.tree.Trees import Trees import six +from stix2patterns.exceptions import ParseException from stix2patterns.grammars.STIXPatternLexer import STIXPatternLexer from stix2patterns.grammars.STIXPatternParser import ( STIXPatternParser, TerminalNode, @@ -305,7 +307,10 @@ class STIXPatternVisitorForSTIX2(STIXPatternVisitor): elif node.symbol.type == STIXPatternParser.BinaryLiteral: return BinaryConstant(node.getText(), from_parse_tree=True) elif node.symbol.type == STIXPatternParser.StringLiteral: - return StringConstant(node.getText().strip('\''), from_parse_tree=True) + if node.getText()[0] == "'" and node.getText()[-1] == "'": + return StringConstant(node.getText()[1:-1], from_parse_tree=True) + else: + raise ParseException("The pattern does not start and end with a single quote") elif node.symbol.type == STIXPatternParser.BoolLiteral: return BooleanConstant(node.getText()) elif node.symbol.type == STIXPatternParser.TimestampLiteral: @@ -345,6 +350,7 @@ def create_pattern_object(pattern, module_suffix="", module_name=""): stream = CommonTokenStream(lexer) parser = STIXPatternParser(stream) + parser.buildParseTrees = True # it always adds a console listener by default... remove it. parser.removeErrorListeners() diff --git a/stix2/test/v21/test_pattern_expressions.py b/stix2/test/v21/test_pattern_expressions.py index 23a401b..76880be 100644 --- a/stix2/test/v21/test_pattern_expressions.py +++ b/stix2/test/v21/test_pattern_expressions.py @@ -510,3 +510,8 @@ def test_parsing_qualified_expression(): def test_list_constant(): patt_obj = create_pattern_object("[network-traffic:src_ref.value IN ('10.0.0.0', '10.0.0.1', '10.0.0.2')]") assert str(patt_obj) == "[network-traffic:src_ref.value IN ('10.0.0.0', '10.0.0.1', '10.0.0.2')]" + + +def test_parsing_multiple_slashes_quotes(): + patt_obj = create_pattern_object("[ file:name = 'weird_name\\'' ]") + assert str(patt_obj) == "[file:name = 'weird_name\\'']"