# shellcheck shell=sh# lib/db.sh — sole gateway to the SQLCipher database.# Depends on: config.sh (paths), lib/ui.sh (pe_err/pe_die/pe_need).# Public API: db_key db_init db_exec db_query db_insert db_integrity# db_exists db_require db_genkey db_quote# --- key resolution ---------------------------------------------------------# Order: $PENTEST_DB_KEY env -> GPG-wrapped keyfile -> interactive prompt.# Result is cached in the non-exported var PE__KEY for the life of the process# (inherited by command-substitution subshells, NOT by exec'd child binaries).db_key(){[ -n "${PE__KEY:-}"]&&{printf'%s'"$PE__KEY"; return0; }if[ -n "${PENTEST_DB_KEY:-}"]; thenPE__KEY=$PENTEST_DB_KEYelif[ -f "$PE_KEYFILE"]; thenPE__KEY=$("$PE_GPG" --quiet --batch --decrypt "$PE_KEYFILE"2>/dev/null)\||{ pe_err "could not decrypt key: $PE_KEYFILE"; return1; }elseprintf'SQLCipher key: ' >&2 stty -echo 2>/dev/null
read -r PE__KEY </dev/tty ||{ stty echo2>/dev/null; return1; } stty echo2>/dev/null
printf'\n' >&2fiprintf'%s'"$PE__KEY"}# db_quote 'str' -> SQL-safe single-quoted literal ('' escaping). Use for ALL# user-supplied values to prevent SQL injection.db_quote(){printf"'%s'""$(printf'%s'"$1" | sed "s/'/''/g")"}# db__pipe [sqlite-cli-opts...] < SQL-on-stdin# Prepends the key + session pragmas, then streams the caller's SQL in.## Some SQLCipher builds print "ok" in response to `PRAGMA key` (and may emit# other setup noise). To stay build-independent we print a unique sentinel# after the setup pragmas and delete every line up to and including it, so the# caller only ever sees the output of its own SQL.db__pipe(){_k=$(db_key)||return1_ek=$(printf'%s'"$_k" | sed "s/'/''/g")_raw=$({printf"PRAGMA key = '%s';\n""$_ek"printf'PRAGMA cipher_compatibility = 4;\n'printf'PRAGMA foreign_keys = ON;\n'printf"SELECT '<<<PE_BEGIN>>>';\n" cat
} | "$PE_SQLCIPHER" -batch "$@""$PE_DB")||return1printf'%s\n'"$_raw" | sed '1,/^<<<PE_BEGIN>>>$/d'}# db_exec ["sql"] -> run statement(s); literal arg OR stdin. No formatted output.db_exec(){if[$# -gt 0]; thenprintf'%s\n'"$1" | db__pipe ||{ pe_err "database command failed"; return1; }else db__pipe ||{ pe_err "database command failed"; return1; }fi}# db_query "sql" -> rows as pipe('|')-delimited fields, no header row.db_query(){printf'%s\n'"$1" | db__pipe -noheader -list -separator '|'\||{ pe_err "database query failed"; return1; }}# db_insert "INSERT ..." -> echoes the new rowid (same connection).db_insert(){_result=$(printf'%s\nSELECT last_insert_rowid();\n'"$1"\ | db__pipe -noheader -list -separator '|')\||{ pe_err "database insert failed"; return1; }_rowid=$(printf'%s\n'"$_result" | tail -n1)case$_rowidin''|*[!0-9]*) pe_err "database insert returned no row id"; return1 ;;
esacprintf'%s\n'"$_rowid"}# db_exists -> 0 if the DB file is present.db_exists(){[ -f "$PE_DB"]; }# db_require -> die with a helpful hint if the DB is missing.db_require(){ db_exists || pe_die "no database at $PE_DB — run 'pe init' first"}# db_integrity -> 0 if SQLCipher reports 'ok' (also validates the key).db_integrity(){["$(printf'PRAGMA integrity_check;\n' | db__pipe -noheader -list 2>/dev/null)"= ok ]}# db_init -> create dirs and apply schema.sql to a (possibly new) encrypted DB.db_init(){ pe_need "$PE_SQLCIPHER" pe_dirs_ensure || pe_die "could not create data/state dirs"[ -f "$PE_SCHEMA"]|| pe_die "schema not found: $PE_SCHEMA" db__pipe < "$PE_SCHEMA"|| pe_die "schema initialization failed" chmod 600"$PE_DB"2>/dev/null ||true pe_ok "database ready: $PE_DB"}# db_genkey -> generate a random 256-bit key, GPG-symmetric-wrap it to PE_KEYFILE.# Prompts (via gpg-agent) for the passphrase that protects the keyfile.db_genkey(){ pe_need "$PE_GPG" od
pe_dirs_ensure
if[ -f "$PE_KEYFILE"]; then pe_warn "keyfile already exists: $PE_KEYFILE (keeping it)"return0fi_k=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')printf'%s'"$_k"\ | "$PE_GPG" --symmetric --cipher-algo AES256 --quiet --batch --yes \ -o "$PE_KEYFILE" - \|| pe_die "gpg key-wrap failed" chmod 600"$PE_KEYFILE"PE__KEY=$_k pe_ok "generated GPG-wrapped DB key: $PE_KEYFILE"}