Implementation:0xSteph Pentest ai agents Db Common Library
| Knowledge Sources | |
|---|---|
| Domains | Security, Data_Storage, Library |
| Last Updated | 2026-10-22 12:00 GMT |
Overview
Concrete shared library for SQLite database access and query helpers provided by the pentest-ai-agents toolkit.
Description
The db/lib/common.sh library is sourced by all database scripts in the pentest-ai-agents toolkit. It provides the dual-backend abstraction layer (sqlite3 CLI or python3 stdlib), SQL escaping, engagement validation, and ID lookup helpers. It is sourced at the top of `findings.sh` and `handoff.sh` and is never invoked standalone.
The library auto-detects the SQLite backend at source time via `check_sqlite()`, setting `USE_PYTHON_SQLITE` accordingly. All `db_exec*` functions branch on this flag to route through either the `sqlite3` binary or an inline `python3 -c` script.
Usage
- Sourcing: Source this library from any script that needs database access: `source "$SCRIPT_DIR/lib/common.sh"`
- Database creation: Call `ensure_db()` before any write to create the database and schema if missing.
- Query execution: Use `db_exec()` for raw queries, `db_exec_csv()` for TSV with headers, `db_exec_json()` for JSON output.
- Engagement validation: Call `require_engagement()` to get the active engagement ID or exit with an error.
- SQL safety: Wrap all user-provided values with `escape_sql()` before interpolation into SQL strings.
- ID lookups: Use `get_host_id()` and `get_service_id()` to resolve foreign key relationships.
Code Reference
Source Location
- Repository: pentest-ai-agents
- File: db/lib/common.sh
Signature
# Configuration (module-level variables)
DB_DIR="${PENTEST_AI_HOME:-$HOME/.pentest-ai}"
DB_PATH="${PENTEST_AI_DB:-$DB_DIR/findings.db}"
ENGAGEMENT="${PENTEST_AI_ENGAGEMENT:-default}"
USE_PYTHON_SQLITE=false
# Backend detection
check_sqlite() # Detects sqlite3 or python3 sqlite3 module; exits if neither found
# Database lifecycle
ensure_dir() # Creates $DB_DIR if missing
ensure_db() # Creates DB file + schema if missing (runs db/schema.sql)
# Query execution (dual-backend)
db_exec(sql: str) -> str # Raw query, tab-separated output
db_insert(sql: str) -> int # Insert + return last_insert_rowid
db_exec_csv(sql: str) -> str # Query with header row, tab-separated
db_exec_json(sql: str) -> str # Query as JSON array
# Python fallback backend
_py_sqlite(mode: str, sql: str) # Internal: mode = tab|header|json
_py_sqlite_script(script_file: str) # Internal: executes SQL script file
# Engagement management
require_engagement() -> str # Returns active engagement ID or exits
# ID lookups
get_host_id(ip: str, eng: str) -> str # Returns host.id or empty
get_service_id(host_id: int, port: int, proto: str) -> str # Returns service.id or empty
# SQL safety
escape_sql(val: str) -> str # Doubles single quotes for SQL escaping
Import
# Source from any script that needs DB access:
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/common.sh"
# Or when installed:
source "$HOME/.pentest-ai/bin/lib/common.sh"
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| sql | str | Yes | SQL query string for db_exec, db_exec_csv, db_exec_json, db_insert |
| ip | str | Yes | Host IP for get_host_id |
| eng | str | Yes | Engagement ID for get_host_id |
| host_id | int | Yes | Host record ID for get_service_id |
| port | int | Yes | Port number for get_service_id |
| val | str | Yes | String to escape for escape_sql |
| PENTEST_AI_DB | env | No | Database path override |
| PENTEST_AI_ENGAGEMENT | env | No | Active engagement (default: "default") |
Outputs
| Name | Type | Description |
|---|---|---|
| db_exec returns | str | Tab-separated query results |
| db_insert returns | int | Last inserted row ID |
| db_exec_csv returns | str | Header + tab-separated rows |
| db_exec_json returns | str | JSON array of row objects |
| require_engagement returns | str | Active engagement ID string |
| get_host_id returns | str | Host record ID or empty string |
| escape_sql returns | str | SQL-safe escaped string |
Usage Examples
Basic Query Execution
source "$SCRIPT_DIR/lib/common.sh"
# Ensure database exists
ensure_db
# Execute a query
local count
count=$(db_exec "SELECT COUNT(*) FROM hosts WHERE engagement_id='$(escape_sql "$ENGAGEMENT")';")
echo "Hosts found: $count"
Insert and Get ID
# Insert a record and get its ID
local new_id
new_id=$(db_insert "INSERT INTO chains (engagement_id, name, score) VALUES ('$eng', 'Test Chain', 75);")
echo "New chain ID: $new_id"
Query with Headers (CSV/TSV)
# Get formatted output with column headers
db_exec_csv "SELECT id, ip, hostname, os, role FROM hosts WHERE engagement_id='$eng' ORDER BY ip;"
JSON Export
# Export query results as JSON
db_exec_json "SELECT * FROM vulns WHERE engagement_id='$eng' AND severity='critical';"
Safe Value Escaping
# Escape user input before SQL interpolation
local safe_name
safe_name=$(escape_sql "$user_input")
db_exec "INSERT INTO hosts (engagement_id, ip, hostname) VALUES ('$eng', '$ip', '$safe_name');"
Engagement Validation
# Get active engagement or exit with error
local eng
eng=$(require_engagement)
echo "Working on engagement: $eng"
Related Pages
Implements Principles
Requires Environment
Related Implementations
- Implementation:0xSteph_Pentest_ai_agents_Findings_CLI sources this library for all database operations
- Implementation:0xSteph_Pentest_ai_agents_Handoff_Report_Generator sources this library for handoff report queries