STIX 2 Patterns Validator
The `stix2-patterns` library provides a software tool for checking the syntax of Cyber Threat Intelligence (CTI) STIX Pattern expressions, used within STIX Indicators to describe conditions indicating cyber threat activity. It is currently at version 2.1.2 and actively maintained with regular updates addressing bug fixes and improvements.
Warnings
- breaking Python 3.10 or newer is now required. Older versions of the library supported Python versions as low as 3.5 (for `stix2` core library) or older (pre-v1.0.0). Ensure your environment meets the `>=3.10` requirement.
- breaking Version 2.0.0 updated the underlying ANTLR grammar to ANTLR 4.9 (from 4.8 in v1.3.0). This change, along with the dependency on `antlr4-python3-runtime~=4.13.0`, might introduce subtle differences in how patterns are parsed or validated, potentially breaking previously valid complex patterns due to updated grammar rules or stricter enforcement.
- gotcha As of v2.0.0, the validator defaults to supporting STIX 2.1 patterns. While it can still parse many 2.0 patterns, subtle differences in the 2.1 specification may cause some 2.0-specific patterns to be flagged as invalid if not strictly compliant with 2.1 rules.
- gotcha This library (`stix2-patterns`) is a *pattern validator*; it only checks the syntax of STIX patterns. It does *not* evaluate or match STIX patterns against actual STIX Observed Data. For pattern matching/evaluation functionality, you need a separate library like `cti-pattern-matcher` (or `stix2-matcher`).
Install
-
pip install stix2-patterns
Imports
- run_validator
from stix2patterns.validator import run_validator
Quickstart
from stix2patterns.validator import run_validator
# A valid STIX 2.1 pattern
pattern_valid = "[file-object:hashes.md5 = '79054025255fb1a26e4bc422aef54eb4']"
errors_valid = run_validator(pattern_valid)
if not errors_valid:
print(f"Pattern '{pattern_valid}' is valid.")
else:
print(f"Pattern '{pattern_valid}' has errors: {errors_valid}")
# An invalid STIX pattern
pattern_invalid = "[file-object:hashes.md5 = 'bad_hash']"
errors_invalid = run_validator(pattern_invalid)
if not errors_invalid:
print(f"Pattern '{pattern_invalid}' is valid.")
else:
print(f"Pattern '{pattern_invalid}' has errors: {errors_invalid}")
# Example of STIX 2.0 pattern (might be considered invalid under 2.1 strictness, but syntax for this is okay)
pattern_stix20 = "[file:hashes.'MD5' = 'd41d8cd98f00b204e9800998ecf8427e']"
errors_stix20 = run_validator(pattern_stix20)
if not errors_stix20:
print(f"Pattern '{pattern_stix20}' is valid.")
else:
print(f"Pattern '{pattern_stix20}' has errors: {errors_stix20}")