Skip to content

Commit

Permalink
Merge pull request #64 from squioc/fix/ValidatorErrorOnMisPlacedWhite…
Browse files Browse the repository at this point in the history
…space

Strip whitespace characters from leading characters
  • Loading branch information
clenk authored Sep 3, 2019
2 parents 825558d + 54cad4b commit 908424e
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 3 deletions.
22 changes: 22 additions & 0 deletions stix2patterns/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import string


def leading_characters(s, length):
"""
Returns non-whitespace leading characters
:param str s: The string to process
:param int length: The number of characters to return
:return: The non-whitespace leading characters
:rtype: str or None
"""
if s is None:
return None

stripped = []
for char in s:
if char not in string.whitespace:
stripped.append(char)

upper_bound = min(length, len(stripped))
return ''.join(stripped[:upper_bound])
14 changes: 14 additions & 0 deletions stix2patterns/test/test_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""
Test cases for stix2patterns/helpers.py.
"""

from stix2patterns.helpers import leading_characters


def test_leading_characters():

assert leading_characters('[file:size = 1280]', 2) == '[f'
assert leading_characters(' [file:size = 1280]', 2) == '[f'
assert leading_characters('( [file:size = 1280])', 2) == '(['
assert leading_characters('[', 2) == '['
assert leading_characters(None, 2) is None
3 changes: 2 additions & 1 deletion stix2patterns/test/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ def test_fail_patterns(test_input, test_output):
"[x_whatever:detected == t'2018-03-22T12:11:14.1Z']",
"[artifact:payload_bin = b'dGhpcyBpcyBhIHRlc3Q=']",
"[foo:bar=1] REPEATS 9 TIMES",
"[network-traffic:start = '2018-04-20T12:36:24.558Z']"
"[network-traffic:start = '2018-04-20T12:36:24.558Z']",
"( [(network-traffic:dst_port IN(443,6443,8443) AND network-traffic:src_packets != 0) ])", # Misplaced whitespace
]


Expand Down
5 changes: 3 additions & 2 deletions stix2patterns/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from . import object_validator
from .grammars.STIXPatternLexer import STIXPatternLexer
from .grammars.STIXPatternParser import STIXPatternParser
from .helpers import leading_characters
from .inspector import InspectionListener


Expand All @@ -37,11 +38,11 @@ def run_validator(pattern):
"""
start = ''
if isinstance(pattern, six.string_types):
start = pattern[:2]
start = leading_characters(pattern, 2)
pattern = InputStream(pattern)

if not start:
start = pattern.readline()[:2]
start = leading_characters(pattern.readline(), 2)
pattern.seek(0)

parseErrListener = STIXPatternErrorListener()
Expand Down

0 comments on commit 908424e

Please sign in to comment.