Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
99f7388
WIP
gwillem Jul 9, 2024
7e4b6c7
Update license to AGPL-3.0, refresh README branding, add project docs
gwillem Feb 13, 2026
9cdbfbb
Restructure into internal packages and cmd/corediff binary
gwillem Feb 13, 2026
da27a21
Replace map-based HashDB with sorted []uint64 + CDDB file format
gwillem Feb 13, 2026
4ab7d1c
Add mmap support for read-only database access
gwillem Feb 13, 2026
f0f7064
Fix db subcommands, add CDC chunking and db info
gwillem Feb 13, 2026
15e9040
Add Packagist git-based indexing for db add
gwillem Feb 13, 2026
71c20fd
Add --composer flag for bulk package indexing from composer.json+lock
gwillem Feb 13, 2026
b76a357
Replace sorted-slice binary search with map-based O(1) lookups in HashDB
gwillem Feb 13, 2026
353ce1c
Update TODO.md and PLAN.md to reflect current state
gwillem Feb 13, 2026
6a429fd
Simplify HashDB: remove mmap, Compact, Close, and dual Open methods
gwillem Feb 14, 2026
2a20416
Add manifest for incremental indexing and --update mode
gwillem Feb 14, 2026
3f44020
Skip unchanged files across versions using git blob hash dedup
gwillem Feb 14, 2026
d09d194
Add composer replace support to skip monorepo sub-packages
gwillem Feb 14, 2026
4af593c
Add legacy format support to HashDB and update PLAN.md
gwillem Feb 14, 2026
9252142
Add direct git URL indexing support
gwillem Feb 14, 2026
dea07d6
Add config.json repo support, git URL updates, and architecture doc
gwillem Feb 14, 2026
cb26d17
Detect monorepo sub-packages and use canonical vendor paths
gwillem Feb 14, 2026
8b40b0e
Log count of embedded packages found during git indexing
gwillem Feb 14, 2026
053e05a
Follow composer.lock deps during git URL indexing
gwillem Feb 14, 2026
380ee69
Add concurrency documentation and analysis
gwillem Feb 14, 2026
88567bd
Add tracked packages in manifest for selective --update
gwillem Feb 15, 2026
657449c
Cache zip downloads to --cache-dir
gwillem Feb 15, 2026
5db6f31
Update TODO with open issues
gwillem Feb 15, 2026
fdef4f3
Log cloning vs fetching accurately for cached git repos
gwillem Feb 15, 2026
d793307
Update TODO checklist and add justfile
gwillem Feb 15, 2026
0372706
Rename "db add" command to "db index"
gwillem Feb 15, 2026
1f5b9c5
Optimize normalize pipeline: 86 ns → 25 ns/line, zero allocs
gwillem Feb 15, 2026
0116cfa
Reuse 10 MB scanner buffer across files instead of allocating per call
gwillem Feb 15, 2026
32b4428
Support legacy xxhash64 databases: auto-detect format and switch hash…
gwillem Feb 15, 2026
fdad9da
Port noisy glob exclude patterns from origin/main
gwillem Feb 15, 2026
cee3246
Tune chunker for precise change detection: comma-aware boundaries, ch…
gwillem Feb 15, 2026
253deef
Show repo URL in indexed-version log lines when package name is empty
gwillem Feb 15, 2026
39d50e4
Drop legacy xxhash64 support, simplify hash plumbing
gwillem Feb 15, 2026
1ec82df
Clean up code review nice-to-haves: fix anti-patterns, remove dead co…
gwillem Feb 15, 2026
c012b05
Add Magento platform notes: generated code structure and validation s…
gwillem Feb 15, 2026
e1a9b88
refactor: consolidate file-walk filtering into shared walkFiles helper
gwillem Feb 16, 2026
94e7b53
refactor: rename internal/gitindex package to internal/indexer
gwillem Feb 16, 2026
7b6ca85
refactor: rebrand to sansecio, add update subcommand and --version flag
gwillem Feb 16, 2026
e4db520
fix: handle urlfilecache API change, parallelize release, tidy TODO
gwillem Feb 16, 2026
372c1fe
feat: add --parallel flag for configurable worker count in indexing a…
gwillem Feb 16, 2026
426de8e
feat: incremental hashdb writes with Ctrl-C safety for indexing
gwillem Feb 17, 2026
04a8590
feat: change --packagist to bool flag accepting multiple positional args
gwillem Feb 17, 2026
d26e9e6
fix: use non-restarting selfupdate, print pre/post version on update
gwillem Feb 17, 2026
f932fc1
docs: update README to match current subcommand CLI
gwillem Feb 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .envrc

This file was deleted.

9 changes: 3 additions & 6 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,12 @@ jobs:

steps:
- name: Checkout code
uses: actions/checkout@v2
uses: actions/checkout@v4

- name: Set up Go
uses: actions/setup-go@v2
uses: actions/setup-go@v5
with:
go-version: '1.20'

- name: Install dependencies
run: go mod download
go-version: '1.24'

- name: Run tests
run: go test -v ./...
44 changes: 44 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Corediff

Forensic tool to detect unauthorized code modifications in open-source codebases (Magento, WordPress). Compares lines of code against a database of legitimate code hashes to identify tampering or malware.

## Project structure

- `cmd/` — All Go source: CLI entry point, scanning, database I/O, highlighting, path utils
- `internal/` — Internal packages (hashdb, normalize, gitindex, composer, manifest, etc.)
- `db/` — Pre-computed Magento version hash databases (.db files)
- `doc/` — Architecture documentation and design docs
- `fixture/` — Test fixtures (sample docroot, sample/empty databases)
- `build/` — Pre-built binaries (darwin/linux, amd64/arm64)

## Commands

- `go test ./...` — Build and run all tests (never use `go build`)
- CI runs `go test -v ./...` on ubuntu with Go 1.20

## Architecture

- Single `main` package in `cmd/`
- CLI: `go-flags` with subcommands (scan, db index, db merge, db info)
- Hash format: binary little-endian uint64, type `hashDB = map[uint64]struct{}`
- Hash algorithm: XXH3 for new databases (CDDB v2), xxhash64 for legacy/v1 databases (auto-detected on load)
- Normalization: strips whitespace, comments, applies regex filters before hashing
- Self-update via `go-selfupdate`

## Path handling

The hash DB stores both line hashes and path hashes. In default scan mode, only files whose path is in the DB are checked — unknown paths are skipped as "custom code." This focuses output on official platform files where tampering matters most.

- `--ignore-paths` — Skip path checking entirely. Scan all files regardless of whether their path is in the DB. Useful for scanning non-standard installs or third-party code.
- `--no-platform` — Skip platform root detection (normally corediff requires the target to look like a Magento/WordPress root). When adding hashes, don't store file paths in the DB — only store line hashes.

When adding hashes with `index`, paths from `excludePaths` (e.g. `generated/**`, `var/**`) are never stored in the DB, but their line contents are still hashed.

## Key dependencies

- `zeebo/xxh3` — Fast hashing for new databases (XXH3)
- `cespare/xxhash/v2` — Legacy hashing for old databases (xxhash64)
- `jessevdk/go-flags` — CLI parsing
- `fatih/color` — Terminal colors
- `gobwas/glob` — Path pattern matching
- `stretchr/testify` — Test assertions
846 changes: 661 additions & 185 deletions LICENSE

Large diffs are not rendered by default.

100 changes: 100 additions & 0 deletions PLAN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Corediff v3 — Implementation Plan

## Current architecture

```
corediff/
├── cmd/corediff/
│ ├── main.go # CLI entry point: scan (default) and db subcommands
│ ├── scan.go # corediff scan: walk, scan, display
│ ├── scan_test.go
│ ├── output.go # Color helpers, verbose logging
│ ├── db.go # corediff db: parent for db subcommands
│ ├── db_index.go # corediff db add: local paths, --packagist, --composer, --update
│ ├── db_merge.go # corediff db merge: combine databases
│ ├── db_info.go # corediff db info: print DB stats
│ └── db_test.go
├── internal/
│ ├── hashdb/ # Map-based HashDB + CDDB binary format (with legacy support)
│ ├── normalize/ # NormalizeLine, Hash, PathHash, HasValidExt, IsValidUtf8
│ ├── path/ # IsExcluded, IsAppRoot, appRootPaths, excludePaths
│ ├── highlight/ # ShouldHighlight (suspect pattern detection)
│ ├── chunker/ # CDC: content-defined chunking for minified files
│ ├── gitindex/ # Git clone + tree walk, zip fallback, blob dedup across versions
│ ├── manifest/ # Append-only manifest tracking indexed package@version pairs
│ ├── composer/ # Parse composer.json/lock, auth.json
│ └── packagist/ # Packagist/Composer repository API client
├── fixture/
├── db/ # Pre-computed Magento hash databases
└── go.mod / go.sum
```


---

## Step 8 — Scanner improvements

**`corediff scan` enhancements:**
- Default DB: `$XDG_DATA_HOME/corediff/default.db`. Override with `-d <path>`.
- Error on first run if no DB exists.
- Single file argument: auto-skip app root check.
- Exit codes: 0=clean, 1=unrecognized lines, 2=suspect lines, >2=error.
- Parallel file scanning (worker pool).

---

## Step 9 — Release infrastructure

**`Justfile`:**
```just
version := `git describe --tags --always`
ldflags := "-X main.version=" + version

build:
go build -ldflags '{{ldflags}}' -o dist/corediff ./cmd/corediff

release:
#!/usr/bin/env bash
for platform in darwin/amd64 darwin/arm64 linux/amd64 linux/arm64; do
os="${platform%/*}"; arch="${platform#*/}"
GOOS=$os GOARCH=$arch go build -ldflags '{{ldflags}}' \
-o dist/corediff-$os-$arch ./cmd/corediff
done

upload: release
gh release create v{{version}} dist/corediff-*
```

**`corediff update` subcommand:**
- Check GitHub releases for newer version, download matching binary.
- No auto-update. User must explicitly run `corediff update`.

**DB version gate:**
- If DB version > compiled-in max supported version, exit with error:
`"Database requires corediff vX.Y+. Run: corediff update"`.

**Remove:** `go-selfupdate` and `go-buildversion` dependencies. Replace with `-ldflags` version injection.

---

## Step 10 — LLM triage (`cdsummary`)

Separate tool that pipes corediff output through an LLM for risk prioritization.

- Two-pass approach: corediff filters locally first, only sends ambiguous files to LLM
- Skip files that are >80% unrecognized (custom code, not tampered — no LLM needed)
- Send top N suspicious files as plain `path:line content` — no JSON/markup overhead
- LLM classifies per file: high risk / suspicious / likely benign, with brief explanation
- Cluster related changes ("these 40 lines across 8 files are one custom module")

---

## Risks & mitigations

| # | Risk | Mitigation | Step |
|---|------|------------|------|
| 1 | Dependency recursion crawls all of Packagist | Depth limit (default 3). Parse `composer.lock` when available. | 7b |
| 2 | Packagist rate limiting / bans | Honor `Retry-After` on 429, `User-Agent` with mailto. | 7b |
| 3 | Zip bombs / oversized packages | Cap download at 100MB, validate `Content-Length`. | — |
| 4 | Single file scan requires `--ignore-paths` | Auto-skip app root check when argument is a file. | 8 |
| 5 | No exit codes for CI usage | 0=clean, 1=unrecognized, 2=suspect, >2=error. | 8 |
99 changes: 69 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,77 @@

![](https://buq.eu/screenshots/6595XfnX5wwUPzbFQGkU0GgN.png)

A forensic tool to quickly find unauthorized modifications in an open source code base, such as Magento. Corediff compares each line of code with a database of 1.7M legitimate code hashes and shows you the lines that have not been seen before. A bit like [@NYT_first_said](https://maxbittker.github.io/clear-pipes/).
A forensic tool to quickly find unauthorized modifications in an open source code base, such as Magento. Corediff compares each line of code with a database of 4.3M legitimate code hashes and shows you the lines that have not been seen before. A bit like [@NYT_first_said](https://maxbittker.github.io/clear-pipes/).

> _"Corediff saved us countless hours"_

> _"Very useful to gauge foreign codebases"_

Corediff was created by [Sansec](https://sansec.io/?corediff), specialists in Magento security and digital forensics since 2010. Corediff analysis helped us to uncover numerous cases of server side payment skimming that would otherwise have gone undetected.
Corediff was created by Sansec, specialist in Magento security and digital forensics since 2010. Corediff analysis helped to uncover numerous cases of server side payment skimming that would otherwise have gone undetected.

# Usage

## Scanning

```
Usage:
corediff [OPTIONS] <path>...

Application Options:
-d, --database= Hash database path (default: download Sansec database)
-a, --add Add new hashes to DB, do not check
-m, --merge Merge databases
-i, --ignore-paths Scan everything, not just core paths.
--no-cms Don't check for CMS root when adding hashes. Do add file paths.
-v, --verbose Show what is going on
corediff [OPTIONS] <path>...
```

Scan a codebase against the hash database. In default mode, only official platform paths are checked. Use `--ignore-paths` to scan all files.

| Flag | Description |
|------|-------------|
| `-d, --database` | Hash database path (default: download Sansec database) |
| `-i, --ignore-paths` | Scan everything, not just core paths |
| `-s, --suspect` | Show suspect code lines only |
| `-t, --text` | Scan all valid UTF-8 text files |
| `--no-platform` | Don't check for app root |
| `-f, --path-filter` | Filter paths before diffing (e.g. `vendor/magento`) |
| `-v, --verbose` | Verbose output (`-vv` for per-file details) |

In the following example, Corediff reports a malicious backdoor in `cron.php`:

![](https://buq.eu/screenshots/y76R3uN9CrCFN6GEji4uSPtM.png)

In default mode, Corediff will only check official Magento paths. In order to find these, you should point Corediff to the root of a Magento installation.
## Database management

### Index local paths

```bash
corediff db index -d custom.db <path>...
```

### Index Packagist packages

```bash
corediff db index -d m2.db -p brick/math composer/ca-bundle guzzlehttp/guzzle
```

The `-p` / `--packagist` flag treats positional arguments as Packagist package names. Supports version pinning with `vendor/pkg:1.2.3` or `vendor/pkg@1.2.3`.

### Index from composer.json

```bash
corediff db index -d m2.db --composer /path/to/composer.json
```

### Update previously indexed packages

```bash
corediff db index -d m2.db --update
```

### Merge databases

Alternatively you can scan all files with the `--ignore-paths` option. NB this will produce more output and requires more interpretation by a developer or forensic analyst.
```bash
corediff db merge -d all.db magento1.db magento2.db *.db
```

### Self-update

```bash
corediff update
```

# Installation

Expand All @@ -47,41 +88,39 @@ chmod 755 corediff
Or compile from source (requires recent Go version):

```sh
git clone https://github.com/sansecio/corediff.git
cd corediff
go run . <store-path>
go install github.com/sansecio/corediff/cmd/corediff@latest
corediff <store-path>
```

At the first run, `corediff` will automatically download the Sansec hash database.
At the first run, `corediff` will automatically download the hash database.

# Community contributed datasets

[@fros_it](https://twitter.com/fros_it) has kindly contributed hashes for his collection of Magento Connect extensions, including all available historical copies. Download the [extension hash database](https://sansec.io/downloads/corediff-db/m1ext.db) here (62MB) and use it like this:

![](https://buq.eu/screenshots/RXdQ1Mmg5KliivMtK6DlHTcP.png)

# Todo

- [ ] Compression of hash db? Eg https://github.com/Smerity/govarint, https://github.com/bits-and-blooms/bloom

# Contributing

Adding or maintaining hashes?

```bash
# Create or update custom.db with all hashes from `<path>`.
corediff --database=custom.db --add <path>
# Index a local path
corediff db index -d custom.db <path>

# Index Packagist packages
corediff db index -d custom.db -p vendor/package

# Merge databases for release
corediff --database=all.db --merge magento1.db magento2.db *.db
corediff db merge -d all.db magento1.db magento2.db *.db
```

In some cases, it is better to not add file paths to the hash database. All paths found in the database will be examined and reported in default mode. Should many varieties exist for a particular file (such as in DI/compiled code), we would rather exclude its scanning from default output, until we can be reasonably certain to have coverage for 99%+ versions out there. So for volatile paths, use the `--add --ignore-paths` options.
In some cases, it is better to not add file paths to the hash database. All paths found in the database will be examined and reported in default mode. Should many varieties exist for a particular file (such as in DI/compiled code), we would rather exclude its scanning from default output, until we can be reasonably certain to have coverage for 99%+ versions out there. So for volatile paths, use the `--ignore-paths` flag when indexing.

Contributions welcome! Naturally, we only accept hashes from trusted sources. [Contact us to discuss your contribution](mailto:info@sansec.io).
Contributions welcome! Naturally, we only accept hashes from trusted sources.

# About Sansec
# About

Sansec's flagship software [eComscan](https://sansec.io/?corediff) is used by ecommerce agencies, law enforcement and PCI forensic investigators. We are proud to open source many of our internal tools and hope that it will benefit our partners and customers. Malware contributions welcome.
Created by Willem de Groot. Malware contributions welcome.

(C) 2023 [Sansec BV](https://sansec.io/?corediff) // info@sansec.io
(C) 2023-2026 Sansec BV
Loading
Loading