BNSQL

June 23, 2026 · View on GitHub

BNSQL logo

BNSQL

Status: Pre-release Alpha | Platform: Windows only (for now)

SQL interface for Binary Ninja - Query your reverse engineering database using SQL.

Features

  • SQL Queries - Full SQLite syntax for complex analysis
  • 11 Virtual Tables - Functions, strings, imports, xrefs, segments, and more
  • 20+ SQL Functions - disasm(), hex(), func_at(), xrefs_to(), etc.
  • Decompilation - decompile() function, pseudocode, hlil_vars, hlil_calls tables for HLIL analysis
  • MCP Server - Model Context Protocol for AI tool integration
  • Fast Startup - ~5s for pre-analyzed databases (skips re-analysis)
  • Plugin + CLI - Use inside Binary Ninja or from command line

Quick Start

Requirements: Binary Ninja must be in your PATH, or place bnsql.exe in your Binary Ninja installation folder.

# Windows: Add BN to PATH
set PATH=C:\Program Files\Vector35\BinaryNinja;%PATH%

# Or copy bnsql.exe to BN folder
copy bnsql.exe "C:\Program Files\Vector35\BinaryNinja\"
# Interactive SQL mode (existing Binary Ninja database)
bnsql database.bndb

# Raw binary - bnsql triggers BN auto-analysis and auto-saves database.bndb next to source
bnsql sample.exe
bnsql firmware.bin --http 8080

# Single query
bnsql database.bndb -c "SELECT name, size FROM funcs ORDER BY size DESC LIMIT 10"

# MCP server for AI tool integration
bnsql database.bndb --mcp

Input file: bnsql <file> accepts either an existing Binary Ninja database (.bndb) or a raw binary (.exe/.dll/firmware/etc.). Raw binaries trigger fresh Binary Ninja analysis; the resulting .bndb is auto-saved next to the source on clean exit. No need to pre-build a .bndb with binaryninja --headless.

For LLM/AI Agent Integration

If you're building an AI agent or tool that needs to query Binary Ninja databases, use the HTTP REST server:

# Start HTTP server
bnsql database.bndb --http 8080

# Query from your agent (simple curl)
curl -X POST http://localhost:8080/query -d "SELECT name, size FROM funcs LIMIT 10"

See Server Modes for full HTTP API documentation, authentication, and MCP protocol support.

SQL Examples

-- 10 largest functions
SELECT hex(address) as addr, name, size
FROM funcs ORDER BY size DESC LIMIT 10;

-- Find password-related strings
SELECT content, hex(address) as addr
FROM strings WHERE content LIKE '%password%';

-- Import analysis by module
SELECT module, COUNT(*) as count
FROM imports GROUP BY module ORDER BY count DESC;

-- Functions called <= 10 times (uses CTE for performance)
WITH call_counts AS (
    SELECT to_ea, COUNT(1) as cnt
    FROM xrefs WHERE is_code = 1
    GROUP BY to_ea
)
SELECT f.name, COALESCE(c.cnt, 0) as calls
FROM funcs f
LEFT JOIN call_counts c ON c.to_ea = f.address
WHERE COALESCE(c.cnt, 0) <= 10
ORDER BY calls DESC;

-- Security: dangerous function imports
SELECT module, name FROM imports
WHERE name IN ('strcpy', 'strcat', 'sprintf', 'gets')
   OR name LIKE '%Shell%' OR name LIKE '%WinExec%';

Tables

TableDescription
funcsFunctions (address, name, size)
segmentsMemory segments (.text, .data, etc.)
namesAll named locations
entriesEntry points and exports
importsImported functions
stringsString literals
xrefsCross-references (from_ea, to_ea, is_code)
blocksBasic blocks
instructionsDecoded instructions
commentsAddress comments
db_infoDatabase metadata

SQL Functions

FunctionDescription
hex(addr)Format address as hex
disasm(addr)Disassembly at address
bytes(addr, n)Read n bytes as hex
name_at(addr)Name at address
func_at(addr)Function name containing address
func_start(addr)Start of containing function
xrefs_to(addr)JSON array of xrefs to address
xrefs_from(addr)JSON array of xrefs from address
save()Save database to disk

CLI Reference

Input file

bnsql <file> accepts either form:

  • Existing Binary Ninja database (.bndb) — loads directly, ready to query.
  • Raw binary (.exe/.dll/firmware/etc.) — bnsql calls Binary Ninja to analyze it from scratch and auto-saves the resulting .bndb next to the source on clean exit. If a sibling .bndb already exists, that's loaded instead.

Modes

# Interactive SQL mode (default)
bnsql database.bndb
bnsql sample.exe                # raw binary: BN auto-analyzes on open

# One-shot SQL query
bnsql database.bndb -c "SELECT name, size FROM funcs ORDER BY size DESC LIMIT 10"
bnsql sample.exe -c "SELECT * FROM funcs LIMIT 5"

# Execute SQL file
bnsql database.bndb -f queries.sql

# MCP server for AI tool integration
bnsql database.bndb --mcp

Interactive Commands

bnsql> .help               Show help
bnsql> .tables             List tables
bnsql> .schema funcs       Show table schema
bnsql> .clear              Clear session
bnsql> .http start         Start HTTP server
bnsql> .quit               Exit

Server Modes

BNSQL supports two server protocols: HTTP REST (recommended) and raw TCP.

Standard REST API that works with curl, Postman, and any HTTP client:

# Start HTTP server (default port 8080)
bnsql database.bndb --http

# Custom port and bind address
bnsql database.bndb --http 9000 --bind 0.0.0.0

# With authentication
bnsql database.bndb --http 8080 --token mysecret

Endpoints:

EndpointMethodDescription
/helpGETAPI documentation (for LLM discovery)
/queryPOSTExecute SQL (body = raw SQL)
/statusGETHealth check
/shutdownPOSTStop server

Example with curl:

# Get API help
curl http://localhost:8080/help

# Execute SQL query
curl -X POST http://localhost:8080/query -d "SELECT name, size FROM funcs LIMIT 5"

# With authentication
curl -X POST http://localhost:8080/query \
     -H "Authorization: Bearer mysecret" \
     -d "SELECT * FROM funcs"

# Check status
curl http://localhost:8080/status

# Plain-text / CSV / TSV output for terminals and unix pipes
curl -X POST "http://localhost:8080/query?format=text" -d "SELECT name, size FROM funcs LIMIT 5"
curl -X POST "http://localhost:8080/query?format=csv"  -d "SELECT name, size FROM funcs LIMIT 5"

Response Format: JSON by default — a script envelope (single statement = array of one):

{"success": true, "statement_count": 1,
 "results": [{"statement_index": 0, "success": true,
   "columns": ["name", "size"], "rows": [["_main", "2851"]],
   "row_count": 1, "elapsed_ms": 8, "error": null}],
 "row_count_total": 1, "elapsed_ms_total": 8, "first_error_index": null}

Output formats (query-string format=, default json):

formatContent-TypeUse
json (default)application/jsonProgrammatic use — agents should consume this, not a reformatted view
texttext/plainReady-to-read ASCII table for terminals
csvtext/csvSpreadsheets / RFC-4180 CSV
tsvtext/tab-separated-valuesUnix pipes (cut/awk/sort)

MCP Server (Model Context Protocol)

For integration with Claude Desktop, Cursor, and other MCP-compatible AI tools:

# Start MCP server (default port 9998)
bnsql database.bndb --mcp

# Custom port
bnsql database.bndb --mcp 9999

MCP Tools Exposed:

ToolDescription
sql_queryExecute SQL query, returns results

Usage: Start the MCP server, then configure your MCP client to connect to http://localhost:9998/sse.

The server uses HTTP/SSE transport. For Claude Desktop or other MCP clients, add the server URL to your MCP configuration after starting bnsql.

Building with HTTP Support

HTTP mode requires the thinclient component:

cmake -B build -DBNSQL_WITH_HTTP=ON ...

The server can also be started from the Binary Ninja plugin:

  • Menu: BNSQL > HTTP Server > Start HTTP Server...

Building

cmake -B build -DBUILD_WITH_BNSQL=ON \
      -DBN_INSTALL_DIR=/path/to/binaryninja
cmake --build build --config Release

Matching the Binary Ninja API to your install

The external/binaryninja-api submodule should be compatible with the version of Binary Ninja you link against — the API and the installed binaryninjacore share a core ABI (BN_CURRENT_CORE_ABI_VERSION) that only changes on breaking releases. The submodule is pinned to one revision, so if your installed Binary Ninja is a different build, the configure step warns. The check compares the commit (the only signal the install exposes statically, in api_REVISION.txt), so a same-series difference may still build fine — the warning is advisory:

bnsql: Binary Ninja API submodule (<have>) does not match your installed Binary Ninja (<want>).

Each install records the exact API commit it was built from in <BN_INSTALL_DIR>/api_REVISION.txt. To sync automatically, configure with:

cmake -B build -DBN_INSTALL_DIR=/path/to/binaryninja -DBNSQL_SYNC_BN_API=ON

or do it by hand using the commit from the warning:

git -C external/binaryninja-api fetch origin <want>
git -C external/binaryninja-api checkout <want>

Performance Tips

  1. Instructions table: Always filter by func_addr - never scan full table
  2. Xref counting: Use CTEs to pre-aggregate, not correlated subqueries
  3. Pre-analyzed databases: ~5s startup vs 15s+ for fresh analysis

Library Examples

Use BNSQL as a library in your own C++ tools. See examples/ for complete code:

#include <bnsql/bnsql.hpp>

int main(int argc, char* argv[]) {
    SetBundledPluginDirectory(GetBundledPluginDirectory());
    InitPlugins();

    // Load binary (auto-creates .bndb if needed)
    auto loaded = bnsql::loader::load_binary("program.exe");
    if (!loaded) return 1;

    // Create SQL query engine
    bnsql::QueryEngine qe(loaded.bv);

    // Get single value
    std::string count = qe.scalar("SELECT COUNT(*) FROM funcs");

    // Query with results
    auto result = qe.query("SELECT name, size FROM funcs ORDER BY size DESC LIMIT 5");
    for (const auto& row : result) {
        std::cout << row[0] << ": " << row[1] << " bytes\n";
    }
}

Available Examples

ExampleDescription
example_basic.cppQueryEngine basics, scalar queries, iteration
example_functions.cppFunction analysis, xrefs, call graphs
example_strings.cppString searching, pattern matching, statistics
example_decompiler.cppHLIL analysis, pseudocode, variables, calls

Build examples:

cd examples
cmake -B build -DBN_INSTALL_DIR=/path/to/binaryninja
cmake --build build --config Release

Screenshots

Coding Agent Plugins

BNSQL skills give your coding agent full control over Binary Ninja databases through natural language. The skills are packaged at 0xeb/bnsql-skills.

  • Claude Code — full plugin with 9 topic-focused skills, installed from the 0xeb/bnsql-skills marketplace.
  • GitHub Copilot CLI — also supports BNSQL skills via the same plugin.
  • Codex (OpenAI) — supports skills via the same plugin packaging. See the bnsql-skills README for the Codex install steps.

Prerequisites

  1. Binary Ninja installed with its DLL directory in your PATH (or set BN_INSTALL_DIR)
  2. bnsql.exe in your PATH (from Releases or built locally)
  3. Verify setup: bnsql --version should work from command line

Install (Claude Code)

Inside Claude Code, run:

/plugin marketplace add 0xeb/bnsql-skills

then install the bnsql plugin from that marketplace. See the bnsql-skills README for Codex and other install paths.

Skills

SkillDescription
connectConnect to Binary Ninja databases: CLI, HTTP server, session bootstrap.
disassemblyQuery Binary Ninja disassembly: functions, segments, instructions, blocks, operands.
dataQuery strings, bytes, binary data: search, byte patterns.
xrefsAnalyze cross-references: callers, callees, imports, data refs.
decompilerDecompile functions: pseudocode, HLIL/MLIL, variables, labels.
annotationsEdit databases: comments, renames, types, function signatures.
typesType system: create/modify/apply structs, unions, enums, typedefs.
functionsComplete bnsql SQL function reference catalog.
analysisAnalyze binaries: triage, security audit, crypto/network detection, multi-table queries.

Example Prompts

"Using bnsql, count functions in malware.bndb"
"Using bnsql, find strings containing 'error' in malware.bndb"
"/bnsql:analysis triage this binary; tell me the most called functions."
"/bnsql:xrefs show callers of CreateFileW and summarize error handling."

Updating

/plugin update bnsql

The xsql family

BNSQL is part of a family of tools that expose different binary-analysis and debug-information platforms through the same SQL surface, all built on the shared libxsql virtual-table framework. A query you learn against one tool largely carries over to the others.

Reverse-engineering platforms

  • idasql — IDA Pro databases as SQL.
  • ghidrasql — Ghidra databases as SQL.

Debug info & compiler data

  • pdbsql — Windows PDB symbol files as SQL.
  • dwarfsql — DWARF debug information as SQL.
  • clangsql — Clang AST as SQL.

Core

  • libxsql — the C++ SQLite virtual-table framework every tool above is built on.

Author

Elias Bachaalany (@0xeb)

License

This project is licensed under the Mozilla Public License 2.0.