picklescan

repository·main·Indexed 19 days ago

https://github.com/mmaitre314/picklescan

A security scanner designed to detect malicious Python Pickle files and suspicious actions, such as arbitrary code execution via eval(). It supports scanning local files, directories, URLs, archives (ZIP, 7z), and Hugging Face models. The tool provides a programmatic API via the picklescan.scanner module and a CLI with features including strict mode for default-deny security, regex-based file/directory filtering, and detailed global import analysis.

Tokens
3.1K
Snippets
10
Records
13
Agent score
15%

What's inside picklescan

  1. Install and scan Hugging Face models with picklescan

    main

    To use picklescan, install it via pip. You can scan models directly from Hugging Face by providing the repository name using the --huggingface flag.

    To scan Numpy's .npy files, ensure the numpy package is installed in your environment before running picklescan.

    pip install picklescan
    picklescan --huggingface ykilcher/totally-harmless-model
  2. Set up a development environment for picklescan

    main

    To develop on picklescan, use conda to create the environment from the provided conda.yaml and install the package in editable mode.

    Development Workflow:

    1. Create and activate the environment: conda env create -f conda.yaml && conda activate picklescan
    2. Install in editable mode: python3 -m pip install -e .
    3. Run unit tests: pytest tests
    4. Lint code: Use black and flake8.
    5. Manual testing: Use picklescan -l DEBUG with local or remote files to verify behavior.
    # Environment setup
    conda env create -f conda.yaml
    conda activate picklescan
    
    # Editable install
    python3 -m pip install -e .
    
    # Run tests
    pytest tests
    
    # Linting
    black src tests --line-length 140
    flake8 src tests --count --show-source
  3. Scan local files, directories, URLs, and archives

    main

    The scanner supports multiple input types:

    • Local files: Use --path with the file path.
    • Directories: Use --path with the directory path to scan all eligible files within.
    • URLs: Use --url to scan a remote file.
    • Archives: Supports zip archives (similar to PyTorch loading behavior).

    Note: When scanning directories, you can use filtering options to include or exclude specific files or subdirectories.

    # Scan a local file
    picklescan --path downloads/pytorch_model.bin
    
    # Scan a directory
    picklescan --path downloads
    
    # Scan a remote URL
    picklescan --url https://huggingface.co/sshleifer/tiny-distilbert-base-cased-distilled-squad/resolve/main/pytorch_model.bin
  4. Interpret ScanResult and SafetyLevel

    main

    The ScanResult object contains the aggregated findings of a scan. Each identified global import is assigned a SafetyLevel.

    SafetyLevel

    • Innocuous: The import is known to be safe (e.g., torch.LongStorage).
    • Suspicious: The import is not in the safe list and not explicitly in the dangerous list.
    • Dangerous: The import is explicitly flagged as dangerous (e.g., os.system, eval, subprocess).

    ScanResult Fields

    • globals: A list of Global objects containing module, name, and safety level.
    • scanned_files: Total number of files processed.
    • issues_count: Number of dangerous imports found.
    • infected_files: Number of files containing at least one dangerous import.
    • scan_err: Boolean indicating if a parsing error occurred during the scan.
  5. Use strict mode in scans

    main

    When calling any scanning function (e.g., scan_file_path, scan_bytes, scan_directory_path), you can set the strict parameter to True.

    In strict mode, any global import that is not explicitly found in the _safe_globals list is automatically promoted to SafetyLevel.Dangerous. This is useful for high-security environments where you want to flag anything that isn't explicitly whitelisted.

  6. Configure directory scanning with ScanFilter

    main

    The ScanFilter class allows you to control which files and directories are traversed during a scan_directory_path call. It follows logic similar to ClamAV's clamscan.

    Filter Options

    • exclude: A list of compiled regex patterns. Files matching these are skipped.
    • include: A list of compiled regex patterns. If set, only files matching these are scanned.
    • exclude_dir: A list of compiled regex patterns. Directories matching these are not traversed.
    • include_dir: A list of compiled regex patterns. If set, only matching directories are traversed.

    Note: exclude patterns always take precedence over include patterns. Multiple patterns of the same type are combined using a logical OR.

    import re
    from picklescan import scanner
    
    scan_filter = scanner.ScanFilter(
        exclude=[re.compile(r"\.log$")],
        include=[re.compile(r"\.pt$")],
        exclude_dir=[re.compile(r"tmp/")],
        include_dir=[re.compile(r"weights/")]
    )
  7. Reference: picklescan CLI flags

    main

    The following flags are available for the picklescan command line interface:

    -p, --path             Path to the file or folder to scan
    -u, --url              URL to the file or folder to scan
    -hf, --huggingface     Name of the Hugging Face model to scan
    -g, --globals           list all globals found
    --strict               Promote suspicious globals to dangerous (default-deny mode)
    --exclude               Don't scan file names matching regular expression (can be used multiple times)
    --include              Only scan file names matching regular expression (can be used multiple times)
    --exclude-dir          Don't scan directory names matching regular expression (can be used multiple times)
    --include-dir          Only scan directory names matching regular expression (can be used multiple times)
    -l, --log              level of log messages to display (default: INFO)
                            Choices: CRITICAL, ERROR, WARNING, INFO, DEBUG
  8. Understand picklescan exit codes

    main

    The scanner uses exit status codes to indicate the result of the scan:

    • 0: scan did not find malware
    • 1: scan found malware
    • 2: scan failed
  9. Filter files and directories during scans

    main

    When scanning directories, you can use regular expressions to include or exclude files and directories. These options can be specified multiple times.

    Filtering Rules:

    • Excludes always win over includes: If a path matches both an include and an exclude pattern, it is skipped.
    • Multiple patterns OR together: A file is included if it matches any provided --include pattern.
    • No includes = everything eligible: If no --include patterns are provided, the scanner attempts to scan all eligible files.
    • --exclude-dir prunes traversal: The specified directory and all its contents are skipped entirely.
    # Options Table:
    # --exclude=REGEX          Don't scan files whose path matches the regex
    # --include=REGEX          Only scan files whose path matches the regex
    # --exclude-dir=REGEX      Don't descend into directories whose path matches the regex
    # --include-dir=REGEX     Only descend into directories whose path matches the regex
    
    # Example: Only scan .pkl files, skip the cache/ subdirectory
    picklescan --path models/ --include='\.pkl$' --exclude-dir='cache'
  10. List all globals found during a scan

    main

    By default, picklescan provides a summary of scanned and infected files. To see a detailed list of every global found during the scan, use the -g or --globals flag. This will output the module path, the name of the global, and its safety status.

    picklescan --path ./my_model --globals
  11. Use the picklescan CLI to scan files, directories, URLs, or Hugging Face models

    main

    The picklescan CLI is a security scanner designed to detect Python Pickle files performing suspicious actions. You must provide exactly one target using one of the following mutually exclusive flags:

    • -p, --path: A local path to a file or a directory.
    • -u, --url: A URL pointing to a file or a directory.
    • -hf, --huggingface: The name of a Hugging Face model to scan.

    Exit Codes

    • 0: No issues found.
    • 1: Issues (dangerous globals) were detected.
    • 2: An error occurred during the scan (e.g., path not found, unhandled exception, or scan error).
    # Scan a local directory
    picklescan --path /path/to/directory
    
    # Scan a specific URL
    picklescan --url https://example.com/model.pkl
    
    # Scan a Hugging Face model
    picklescan --huggingface username/model-name
  12. Configure picklescan CLI filtering and strict mode

    main

    You can refine the scan behavior using the following flags:

    Strict Mode

    • --strict: Enables 'default-deny' mode. This promotes suspicious globals to 'dangerous' status.

    File and Directory Filtering

    Filtering uses regular expressions (REGEX). These flags can be used multiple times to provide multiple patterns.

    • --include: Only scan file names matching these regex patterns.
    • --exclude: Don't scan file names matching these regex patterns.
    • --include-dir: Only scan directory names matching these regex patterns.
    • --exclude-dir: Don't scan directory names matching these regex patterns.

    Logging

    • -l, --log: Set the logging level. Options: CRITICAL, ERROR, WARNING, INFO, DEBUG. (Default: INFO)
    # Example: Scan only .pkl files, excluding a 'cache' directory, in strict mode
    picklescan --path ./data --include '.*\.pkl$' --exclude-dir 'cache' --strict