libsast - Generic SAST Library

3.1.6 · active · verified Thu Apr 16

libsast is a Python library providing generic Static Application Security Testing (SAST) capabilities, built upon Semgrep and regex patterns. It allows users to define custom rules and scan codebases for security vulnerabilities. The library is actively maintained with frequent patch and minor releases, with the current version being 3.1.6.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a custom regex rule and use `libsast` to scan a temporary file. It initializes `Scan` with a target directory and a list of rules, then runs the scan and prints any found vulnerabilities. It also highlights the option to switch multiprocessing executors for compatibility.

import os
import tempfile
import shutil
from libsast.core.scan import Scan
from libsast.core.rule import Rule

# Create a dummy directory and file for scanning
temp_dir = tempfile.mkdtemp()
temp_file_path = os.path.join(temp_dir, "test_code.py")
try:
    with open(temp_file_path, "w") as f:
        f.write("password = 'mysecretpassword'\n")
        f.write("API_KEY = 'YOUR_API_KEY_HERE'\n")
        f.write("def my_func():\n    print('Hello')\n")

    # Define a simple regex rule
    my_rule = Rule(
        rule_id="HARDCODED_SECRET",
        description="Detects hardcoded sensitive keywords like 'password' or 'API_KEY'",
        severity="high",
        patterns=[
            {"regex": r"(password\s*=|API_KEY\s*=)", "confidence": "high", "message": "Hardcoded secret found."}
        ],
        metadata={
            "cwe": "CWE-798",
            "owasp": "A07:2021-Identification and Authentication Failures"
        }
    )

    # Initialize the scanner
    # In environments like AWS Lambda or Celery, consider `multiprocessing_executor="thread"` or "billiard"
    scanner = Scan(
        target=temp_dir, # Scan the entire directory
        rules=[my_rule],
        enable_default_rules=False, # Set to True to include libsast's built-in rules
        multiprocessing_executor="process" # Options: "process", "thread", "billiard"
    )

    # Run the scan
    results = scanner.run()

    # Process results
    if results:
        print(f"Found {len(results)} vulnerabilities:")
        for result in results:
            print(f"- Rule ID: {result.rule_id}")
            print(f"  File: {result.file_path}")
            print(f"  Line: {result.line_number}")
            print(f"  Match: '{result.match_string}'")
            if result.message:
                print(f"  Message: {result.message}")
    else:
        print("No vulnerabilities found.")

finally:
    # Clean up the temporary directory
    shutil.rmtree(temp_dir)

view raw JSON →