CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-stix2-validator

APIs and scripts for validating STIX 2.x documents against specification requirements and best practices.

Overview
Eval results
Files

core-validation.mddocs/

Core Validation Functions

Main validation entry points for different input types including files, strings, Python dictionaries, and parsed JSON objects. These functions provide flexible validation capabilities for STIX documents from various sources and formats.

Capabilities

File Validation

Validates STIX JSON documents from files on the filesystem, handling file I/O, JSON parsing, and comprehensive validation reporting.

def validate_file(fn, options=None):
    """
    Validate the input document according to the options passed in.
    
    Parameters:
    - fn (str): The filename of the JSON file to be validated
    - options (ValidationOptions, optional): An instance of ValidationOptions
    
    Returns:
    FileValidationResults: An instance of FileValidationResults
    
    Raises:
    NoJSONFileFoundError: If the file cannot be found or read
    ValidationError: If validation cannot be completed due to system errors
    """

Example Usage:

from stix2validator import validate_file, ValidationOptions

# Basic file validation
results = validate_file("threat_report.json")

# File validation with custom options
options = ValidationOptions(version="2.1", strict=True)
results = validate_file("indicators.json", options)

# Check results
if results.is_valid:
    print(f"File {results.filepath} is valid")
else:
    print(f"Validation failed for {results.filepath}")
    for obj_result in results.object_results:
        for error in obj_result.errors:
            print(f"  Error in object {obj_result.object_id}: {error}")

String Validation

Validates STIX JSON content from string input, useful for processing JSON received from APIs, generated dynamically, or stored in variables.

def validate_string(string, options=None):
    """
    Validate the input string according to the options passed in.
    
    Parameters:
    - string (str): The string containing the JSON to be validated
    - options (ValidationOptions, optional): An instance of ValidationOptions
    
    Returns:
    Union[ObjectValidationResults, List[ObjectValidationResults]]: Single result for single object, list for multiple objects
    
    Raises:
    ValidationError: If the string cannot be parsed or validated
    """

Example Usage:

from stix2validator import validate_string

# Single STIX object validation
stix_indicator = '''
{
    "type": "indicator",
    "spec_version": "2.1",
    "id": "indicator--12345678-1234-1234-1234-123456789012",
    "created": "2023-01-01T00:00:00.000Z",
    "modified": "2023-01-01T00:00:00.000Z",
    "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']",
    "labels": ["malicious-activity"]
}
'''

result = validate_string(stix_indicator)
print(f"Indicator valid: {result.is_valid}")

# Bundle validation (multiple objects)
stix_bundle = '''
{
    "type": "bundle",
    "id": "bundle--12345678-1234-1234-1234-123456789012",
    "objects": [...]
}
'''

results = validate_string(stix_bundle)
if isinstance(results, list):
    for result in results:
        print(f"Object {result.object_id}: {result.is_valid}")

Instance Validation

Validates Python dictionaries representing STIX objects, enabling validation of programmatically constructed STIX data without serialization.

def validate_instance(instance, options=None):
    """
    Perform STIX JSON Schema validation against STIX input.
    
    Parameters:
    - instance (dict): A Python dictionary representing a STIX object with a 'type' property
    - options (ValidationOptions, optional): Validation options for this validation run
    
    Returns:
    ObjectValidationResults: An instance of ObjectValidationResults
    
    Raises:
    ValidationError: If the instance cannot be validated
    """

Example Usage:

from stix2validator import validate_instance, ValidationOptions

# Validate a Python dictionary
stix_object = {
    "type": "malware",
    "spec_version": "2.1",
    "id": "malware--12345678-1234-1234-1234-123456789012",
    "created": "2023-01-01T00:00:00.000Z",
    "modified": "2023-01-01T00:00:00.000Z",
    "name": "BadMalware",
    "labels": ["trojan"]
}

# Validate with strict checking
options = ValidationOptions(strict=True, strict_types=True)
result = validate_instance(stix_object, options)

print(f"Malware object valid: {result.is_valid}")
if not result.is_valid:
    for error in result.errors:
        print(f"Error: {error}")

Parsed JSON Validation

Validates already parsed JSON objects or lists, useful when working with JSON data that has already been loaded by other parts of your application.

def validate_parsed_json(obj_json, options=None):
    """
    Validate objects from parsed JSON.
    
    Parameters:
    - obj_json: The parsed json (dict or list)
    - options (ValidationOptions, optional): Validation options
    
    Returns:
    Union[ObjectValidationResults, List[ObjectValidationResults]]: Single result or list based on input
    
    Raises:
    ValidationError: If validation cannot be completed
    """

Example Usage:

import json
from stix2validator import validate_parsed_json

# Load JSON from various sources
with open("stix_data.json") as f:
    parsed_json = json.load(f)

# Validate the parsed data
results = validate_parsed_json(parsed_json)

# Handle single object or list of objects
if isinstance(results, list):
    for result in results:
        print(f"Object {result.object_id}: {'VALID' if result.is_valid else 'INVALID'}")
else:
    print(f"Object {results.object_id}: {'VALID' if results.is_valid else 'INVALID'}")

Stream Validation

Validates STIX JSON content from a textual stream, useful for processing data from stdin or file-like objects.

def validate(in_, options=None):
    """
    Validate objects from JSON data in a textual stream.
    
    Parameters:
    - in_: A textual stream of JSON data
    - options (ValidationOptions, optional): Validation options
    
    Returns:
    Union[ObjectValidationResults, List[ObjectValidationResults]]: Single result or list based on content
    
    Raises:
    ValidationError: If validation cannot be completed
    """

Example Usage:

import sys
from stix2validator import validate

# Validate from stdin
if not sys.stdin.isatty():
    results = validate(sys.stdin)
    if isinstance(results, list):
        for result in results:
            print(f"Object {result.object_id}: {'VALID' if result.is_valid else 'INVALID'}")
    else:
        print(f"Object {results.object_id}: {'VALID' if results.is_valid else 'INVALID'}")

# Validate from any file-like object
from io import StringIO
stix_stream = StringIO('{"type": "indicator", ...}')
result = validate(stix_stream)
print(f"Stream validation: {result.is_valid}")

Batch Validation

Runs validation based on command line options, processing multiple files and directories with comprehensive reporting.

def run_validation(options):
    """
    Validate files based on command line options.
    
    Parameters:
    - options (ValidationOptions): An instance of ValidationOptions containing options for this validation run
    
    Returns:
    List[FileValidationResults]: List of validation results for all processed files
    
    Raises:
    ValidationError: If validation cannot be completed
    NoJSONFileFoundError: If specified files cannot be found
    """

Example Usage:

from stix2validator import run_validation, ValidationOptions

# Configure batch validation options
options = ValidationOptions(
    files=["stix_files/", "single_file.json"],
    recursive=True,
    version="2.1",
    verbose=True,
    strict=False
)

# Run batch validation
results = run_validation(options)

# Process results
valid_count = sum(1 for result in results if result.is_valid)
total_count = len(results)

print(f"Validation complete: {valid_count}/{total_count} files valid")

for result in results:
    if not result.is_valid:
        print(f"FAILED: {result.filepath}")
        for obj_result in result.object_results:
            for error in obj_result.errors:
                print(f"  - {error}")

Utility Functions

File Discovery

def is_json(fn):
    """
    Check if file has JSON extension.
    
    Parameters:
    - fn (str): Filename to check
    
    Returns:
    bool: True if file has .json extension
    """

def list_json_files(directory, recursive=False):
    """
    List JSON files in directory.
    
    Parameters:
    - directory (str): Directory path to search
    - recursive (bool): Whether to search subdirectories
    
    Returns:
    List[str]: List of JSON file paths
    """

def get_json_files(files, recursive=False):
    """
    Get JSON files from file list or directories.
    
    Parameters:
    - files (List[str]): List of files and/or directories
    - recursive (bool): Whether to search directories recursively
    
    Returns:
    List[str]: List of JSON file paths
    """

Install with Tessl CLI

npx tessl i tessl/pypi-stix2-validator

docs

cli-utilities.md

configuration.md

core-validation.md

exception-handling.md

index.md

results-output.md

tile.json