binsleuth 0.4.0

ELF/PE binary security hardening checker and section-level entropy analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
<div align="center">

# πŸ” BinSleuth

**A fast, zero-dependency CLI tool for static binary security analysis.**
Inspect ELF & PE binaries for hardening flags and detect packed/encrypted sections β€” in milliseconds.

![BinSleuth social preview](https://repository-images.githubusercontent.com/1174345949/ddfc9174-be34-4b79-931d-1b8d3e71fcdf)

[![Crates.io](https://img.shields.io/crates/v/binsleuth.svg)](https://crates.io/crates/binsleuth)
[![Downloads](https://img.shields.io/crates/d/binsleuth.svg)](https://crates.io/crates/binsleuth)
[![docs.rs](https://docs.rs/binsleuth/badge.svg)](https://docs.rs/binsleuth)
[![CI](https://github.com/long-910/BinSleuth/actions/workflows/ci.yml/badge.svg)](https://github.com/long-910/BinSleuth/actions/workflows/ci.yml)
[![Release](https://github.com/long-910/BinSleuth/actions/workflows/release.yml/badge.svg)](https://github.com/long-910/BinSleuth/actions/workflows/release.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![MSRV](https://img.shields.io/badge/rustc-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![Tests](https://img.shields.io/badge/tests-85%20passing-brightgreen.svg)](#)
[![GitHub Sponsors](https://img.shields.io/github/sponsors/long-910?label=Sponsor&logo=githubsponsors&color=EA4AAA)](https://github.com/sponsors/long-910)
[![Ko-fi](https://img.shields.io/badge/Ko--fi-Support-FF5E5B?logo=ko-fi&logoColor=white)](https://ko-fi.com/long910)

**Language / 言θͺž / 语言:**
[English](README.md) Β· [ζ—₯本θͺž](README.ja.md) Β· [δΈ­ζ–‡](README.zh.md)

</div>

---

## What is BinSleuth?

BinSleuth is a **security-focused static binary analyzer** written in Rust.
It acts as a quick health-check for compiled executables β€” answering:

- *"Does this binary have modern security protections enabled?"*
- *"Could this section be packed or encrypted malware?"*
- *"Does this binary import dangerous OS-level functions?"*

It is designed for **security engineers, malware researchers, and developers** who need instant answers without launching a full reverse-engineering suite.

---

## Features

### 1. Security Hardening Checks

| Flag | Description | ELF | PE |
|------|-------------|-----|----|
| **NX** | Non-executable stack/data β€” prevents code injection | `PT_GNU_STACK` | `NX_COMPAT` |
| **PIE** | Position-Independent Executable β€” enables ASLR | `ET_DYN` | `DYNAMIC_BASE` |
| **RELRO** | Read-Only Relocations β€” prevents GOT overwrite | `PT_GNU_RELRO` + `BIND_NOW` | N/A |
| **Stack Canary** | Buffer-overflow tripwire symbol present | `__stack_chk_fail` | `__security_cookie` |
| **FORTIFY_SOURCE** | Fortified libc wrappers (`__*_chk`) β€” compile-time bounds checks on unsafe string/memory calls | `__memcpy_chk`, … | `__memcpy_chk`, … |
| **No RPATH/RUNPATH** | Absence of embedded library search paths β€” prevents library-injection via writable/relative RPATH | `DT_RPATH` / `DT_RUNPATH` | N/A |
| **Stripped** | Debug symbols / DWARF info absent β€” limits reverse-engineering | `.debug_*` sections | Debug directory |

Each check reports one of: **Enabled** / **Partial** / **Disabled** / **N/A**

### 2. Section Entropy Analysis

BinSleuth computes the [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) of every section:

```
H = -Ξ£ P(x) Β· logβ‚‚(P(x))       range: [0.0 – 8.0]
```

| Entropy Range | Interpretation |
|---------------|----------------|
| 0.0 – 4.0 | Normal code / data |
| 4.0 – 7.0 | Compressed resources (normal) |
| **> 7.0** | **⚠ Packed / Encrypted β€” investigate** |

### 3. Dangerous Symbol Detection

BinSleuth flags symbols that commonly appear in malicious or insecure binaries, and reports each one with a **category**:

| Category | JSON value | Examples |
|----------|-----------|---------|
| **Code execution** | `exec` | `system`, `execve`, `popen`, `WinExec`, `CreateProcess` |
| **Network** | `net` | `connect`, `socket`, `gethostbyname`, `WinHttpOpen` |
| **Memory manipulation** | `mem` | `mprotect`, `mmap`, `VirtualAlloc`, `VirtualProtect` |

### 4. Security Score

Every report includes a numeric **security score from 0 to 100**, computed from the weighted hardening results:

| Check | Points |
|-------|--------|
| NX | 20 |
| PIE | 20 |
| RELRO (Full) | 15 Β· Partial: 7 Β· N/A: 15 |
| Stack Canary | 15 |
| FORTIFY_SOURCE | 10 |
| No RPATH/RUNPATH | 10 |
| Stripped | 5 |
| No dangerous symbols | 5 (βˆ’1 per symbol) |

---

## Installation

### From crates.io (recommended)

```bash
cargo install binsleuth
```

### From source

```bash
git clone https://github.com/long-910/BinSleuth.git
cd BinSleuth
cargo build --release
# Binary output: ./target/release/binsleuth
```

### Requirements

- Rust **1.85** or later
- No system libraries required β€” pure Rust

---

## Usage

```
binsleuth [OPTIONS] <FILE>

Arguments:
  <FILE>  Path to the ELF or PE binary to analyze

Options:
  -v, --verbose  Show all sections, even those with normal entropy
      --json     Output results as JSON instead of the colored terminal report
      --strict   Exit with code 2 if any hardening protection is missing or
                 dangerous symbols are found (useful in CI pipelines)
  -h, --help     Print help
  -V, --version  Print version
```

### Basic analysis

```bash
binsleuth /usr/bin/ls
binsleuth ./myapp.exe
binsleuth ./suspicious_binary
```

### Show all sections (including low-entropy ones)

```bash
binsleuth --verbose /usr/bin/python3
```

### JSON output (for scripting / CI integration)

```bash
binsleuth --json /usr/bin/ls | jq '.hardening.nx'
```

### CI pipeline β€” fail if hardening issues are found

```bash
binsleuth --strict ./myapp && echo "Hardening OK" || echo "Hardening FAILED"
# Exit 0 = all good, Exit 2 = hardening issues found, Exit 1 = parse error
```

### Example output β€” hardened binary

```
╔══════════════════════════════════════════════════════╗
β•‘              BinSleuth β€” Binary Analyzer             β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

  File:    /usr/bin/ls
  Format:  ELF
  Arch:    X86_64

  ── Security Hardening ──────────────────────────────────

  [ ENABLED  ]  NX (Non-Executable Stack)
  [ ENABLED  ]  PIE (ASLR-compatible)
  [ ENABLED  ]  RELRO (Read-Only Relocations)
  [ ENABLED  ]  Stack Canary
  [ ENABLED  ]  FORTIFY_SOURCE
  [ ENABLED  ]  No RPATH/RUNPATH
  [ ENABLED  ]  Debug Symbols Stripped

  ── Section Entropy ─────────────────────────────────────

  Section                      Size (B)     Entropy  Status
  ──────────────────────────────────────────────────────────────────────
  All sections within normal entropy range.
  (run with --verbose to show all sections)

  ── Dangerous Symbol Usage ──────────────────────────────

  No dangerous symbols detected.

  ────────────────────────────────────────────────────────
  Analysis complete.
```

### Example output β€” suspicious / packed binary

```
  ── Section Entropy ─────────────────────────────────────

  Section                      Size (B)     Entropy  Status
  ──────────────────────────────────────────────────────────────────────
  UPX0                           491520       7.9981  ⚠  Packed/Encrypted suspected
  UPX1                            32768       7.9912  ⚠  Packed/Encrypted suspected

  2 section(s) with entropy > 7.0 detected!

  ── Dangerous Symbol Usage ──────────────────────────────

  3 dangerous symbol(s) found:
    β–Ά  execve    [exec]
    β–Ά  mprotect  [mem]
    β–Ά  socket    [net]
```

---

## Library Usage

`binsleuth` can be used as a Rust library crate in addition to the CLI β€” for example as the core analysis engine of a VS Code extension.

Add to your `Cargo.toml`:

```toml
[dependencies]
binsleuth = "0.4"
```

### Unified API (recommended)

```rust
// Single call β€” returns hardening, sections, and security score together
let data = std::fs::read("path/to/binary")?;
let report = binsleuth::analyze(&data)?;

println!("Score: {}/100", report.security_score);
println!("PIE:   {:?}", report.hardening.pie);

for sec in &report.sections {
    println!("{}: va={:#x} entropy={:.4} rwx={}{}{}",
        sec.name, sec.virtual_address, sec.entropy,
        if sec.permissions.read  { 'r' } else { '-' },
        if sec.permissions.write { 'w' } else { '-' },
        if sec.permissions.execute { 'x' } else { '-' },
    );
}

for sym in &report.hardening.dangerous_symbols {
    println!("  {:?}  {}", sym.category, sym.name);
}

// Serialize to JSON string (no stdout side-effect)
let json: String = report.to_json_pretty();
```

### Lower-level API

```rust
use binsleuth::analyzer::hardening::HardeningInfo;
use binsleuth::analyzer::entropy::SectionEntropy;

let hardening = HardeningInfo::analyze(&data)?;
let sections  = SectionEntropy::analyze(&data)?;
```

See the [API documentation on docs.rs](https://docs.rs/binsleuth) and [`examples/basic.rs`](examples/basic.rs) for a complete runnable example.

---

## Project Structure

```
BinSleuth/
β”œβ”€β”€ Cargo.toml
β”œβ”€β”€ README.md              ← English (default)
β”œβ”€β”€ README.ja.md           ← Japanese
β”œβ”€β”€ README.zh.md           ← Chinese (Simplified)
β”œβ”€β”€ CHANGELOG.md
β”œβ”€β”€ LICENSE
β”œβ”€β”€ examples/
β”‚   └── basic.rs           # Library usage example
└── src/
    β”œβ”€β”€ lib.rs             # Library crate root (public API)
    β”œβ”€β”€ main.rs            # CLI entry point (clap)
    β”œβ”€β”€ analyzer/
    β”‚   β”œβ”€β”€ mod.rs
    β”‚   β”œβ”€β”€ entropy.rs     # Shannon entropy + SectionEntropy
    β”‚   └── hardening.rs   # NX / PIE / RELRO / Canary / symbols
    └── report/
        β”œβ”€β”€ mod.rs
        β”œβ”€β”€ terminal.rs    # Colored terminal renderer
        └── json.rs        # JSON output serializer
```

### Key types

| Type | Location | Role |
|------|----------|------|
| `AnalysisReport` | `analyzer/mod.rs` | Unified result: hardening + sections + security score |
| `HardeningInfo` | `analyzer/hardening.rs` | Aggregated hardening check results |
| `CheckResult` | `analyzer/hardening.rs` | `Enabled` / `Partial(msg)` / `Disabled` / `N/A` |
| `DangerousSymbol` | `analyzer/hardening.rs` | Symbol name + `SymbolCategory` (Exec / Net / Mem) |
| `SectionEntropy` | `analyzer/entropy.rs` | Section name, virtual address, file offset, size, entropy, permissions |
| `SectionPermissions` | `analyzer/entropy.rs` | `read`, `write`, `execute` bool flags |
| `TerminalReporter` | `report/terminal.rs` | Colored terminal output renderer |

---

## Supported Formats

| Format | Architectures | NX | PIE | RELRO | Canary | FORTIFY | RPATH |
|--------|---------------|----|-----|-------|--------|---------|-------|
| ELF 32-bit | x86, ARM, MIPS, … | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… |
| ELF 64-bit | x86-64, AArch64, … | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… |
| PE 32-bit (PE32) | x86 | βœ… | βœ… | N/A | βœ… | βœ… | N/A |
| PE 64-bit (PE32+) | x86-64 | βœ… | βœ… | N/A | βœ… | βœ… | N/A |

---

## Exit Codes

| Code | Meaning |
|------|---------|
| `0` | Analysis completed successfully |
| `1` | File not found, parse error, or unsupported format |
| `2` | `--strict` mode: analysis succeeded but hardening issues were found |

---

## Testing

```bash
# All tests (unit + integration)
cargo test

# Unit tests only
cargo test --lib

# Integration tests only (requires compiled binary)
cargo test --test cli

# Lint
cargo clippy -- -D warnings

# Format check
cargo fmt --check
```

The test suite includes **56 unit tests**, **26 integration tests**, and **3 doc tests** (85 total):

| Module | Tests | Coverage |
|--------|-------|---------|
| `analyzer::entropy` | 17 | Shannon formula, edge cases, monotonicity, `extract_permissions` (ELF/COFF flags), section metadata |
| `analyzer::hardening` | 23 | PE header parsing, RELRO states, FORTIFY_SOURCE, RPATH, ELF self-analysis, dangerous symbol categorization |
| `analyzer` (mod) | 16 | `compute_score` boundary values and per-check deductions, `AnalysisReport` API, JSON serialization |
| `tests::cli` | 26 | CLI flags, JSON output, strict mode, stripped detection, error handling, `security_score`, section metadata, dangerous symbol categories |
| doc tests | 3 | Library API smoke tests |

---

## Contributing

Contributions are welcome!

1. Fork the repository
2. Create a feature branch: `git checkout -b feat/your-feature`
3. Write tests where applicable
4. Run `cargo test && cargo clippy -- -D warnings` before submitting
5. Open a Pull Request

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details *(coming soon)*.

---

## Roadmap

- [x] JSON output mode (`--json`)
- [x] DWARF / PDB debug-info / stripped detection
- [x] Strict mode for CI pipelines (`--strict`, exit code 2)
- [x] FORTIFY_SOURCE detection (`__*_chk` symbol scan)
- [x] RPATH/RUNPATH detection (library-injection risk)
- [x] Library API β€” `AnalysisReport::analyze()` unified entry point
- [x] Security score (0–100) for dashboard/badge display
- [x] Per-section virtual address, file offset, and rwx permissions
- [x] Dangerous symbol categories (Exec / Net / Mem) for colour-coded visualisation
- [ ] VS Code extension (visualisation front-end)
- [ ] SARIF output format
- [ ] macOS Mach-O support
- [ ] Import table diff between two binaries (`binsleuth diff a.out b.out`)
- [ ] Yara-rule-style byte-pattern matching

---

## License

This project is licensed under the **MIT License** β€” see [LICENSE](LICENSE) for details.

---

## Acknowledgements

- [object]https://crates.io/crates/object β€” cross-platform binary parsing
- [clap]https://crates.io/crates/clap β€” CLI argument parsing
- [anyhow]https://crates.io/crates/anyhow β€” ergonomic error handling
- [colored]https://crates.io/crates/colored β€” terminal color output

---

<div align="center">
Made with ❀️ and Rust
</div>