git-ward 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Cargo.toml +21 -0
- package/LICENSE +21 -0
- package/README.md +81 -0
- package/bin/ward.js +30 -0
- package/package.json +37 -0
- package/src/config.rs +48 -0
- package/src/git.rs +96 -0
- package/src/main.rs +91 -0
- package/src/scanner.rs +129 -0
package/Cargo.toml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "ward"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
edition = "2021"
|
|
5
|
+
authors = ["awixor"]
|
|
6
|
+
description = "Local-First Git Guard for preventing secret leaks"
|
|
7
|
+
repository = "https://github.com/awixor/ward"
|
|
8
|
+
license = "MIT"
|
|
9
|
+
keywords = ["git", "secret-scanning", "security", "cli"]
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
[dependencies]
|
|
12
|
+
clap = { version = "4.4", features = ["derive"] }
|
|
13
|
+
regex = "1.10"
|
|
14
|
+
serde = { version = "1.0", features = ["derive"] }
|
|
15
|
+
toml = "0.8"
|
|
16
|
+
ignore = "0.4"
|
|
17
|
+
globset = "0.4"
|
|
18
|
+
colored = "2.1"
|
|
19
|
+
|
|
20
|
+
anyhow = "1.0"
|
|
21
|
+
thiserror = "1.0"
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Elhoucine Aouassar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Ward (Local-First Git Guard)
|
|
2
|
+
|
|
3
|
+
**Ward** is a high-performance, zero-server CLI tool and Git hook designed to prevent developers from accidentally pushing sensitive data (Private Keys, Mnemonics, API Keys) to GitHub.
|
|
4
|
+
|
|
5
|
+
## 🚀 Features
|
|
6
|
+
|
|
7
|
+
- **Zero Friction:** Scans staged files in < 50ms.
|
|
8
|
+
- **Privacy First:** All scanning happens locally. No data leaves your machine.
|
|
9
|
+
- **Smart Detection:**
|
|
10
|
+
- **Ethereum Private Keys**
|
|
11
|
+
- **BIP-39 Mnemonics**
|
|
12
|
+
- **Generic API Keys**
|
|
13
|
+
- **High Entropy Strings** (with false positive filtering)
|
|
14
|
+
- **Configurable:** Ignore specific files or patterns via `ward.toml`.
|
|
15
|
+
|
|
16
|
+
## 📦 Installation
|
|
17
|
+
|
|
18
|
+
### fast way (npx)
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
# Initialize Ward in your current repository
|
|
22
|
+
npx git-ward init
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### From Source (Rust)
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
cargo install --path .
|
|
29
|
+
ward init
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## 🛠 Usage
|
|
33
|
+
|
|
34
|
+
Once initialized, Ward runs automatically as a `pre-commit` hook.
|
|
35
|
+
|
|
36
|
+
### Automatic Scanning
|
|
37
|
+
|
|
38
|
+
Just use `git commit` as normal. If you try to commit a secret:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
git commit -m "oops"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
**Output:**
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
Ward detected sensitive data in your commit:
|
|
48
|
+
✖ secret.key:1: Ethereum Private Key
|
|
49
|
+
Code: 0x12...cdef
|
|
50
|
+
✖ secret.key:1: High Entropy (4.05)
|
|
51
|
+
Code: 0x12...cdef
|
|
52
|
+
|
|
53
|
+
Commit blocked. Remove the secrets or use 'git commit --no-verify' to bypass.
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Manual Scan
|
|
57
|
+
|
|
58
|
+
You can also run a scan manually without committing:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
ward scan
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## ⚙️ Configuration (`ward.toml`)
|
|
65
|
+
|
|
66
|
+
Create a `ward.toml` in your project root to customize behavior:
|
|
67
|
+
|
|
68
|
+
```toml
|
|
69
|
+
# ward.toml
|
|
70
|
+
exclude = ["secrets.txt", "*.lock"]
|
|
71
|
+
skip_entropy_checks = ["*.min.js", "node_modules/"]
|
|
72
|
+
threshold = 4.5
|
|
73
|
+
|
|
74
|
+
[[rules]]
|
|
75
|
+
name = "My Custom Token"
|
|
76
|
+
regex = "MYTOKEN-[0-9]{5}"
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## License
|
|
80
|
+
|
|
81
|
+
MIT
|
package/bin/ward.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
const { spawn } = require("child_process");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
|
|
6
|
+
// Point to the package's Cargo.toml so we can run from anywhere
|
|
7
|
+
const projectRoot = path.join(__dirname, "..");
|
|
8
|
+
const manifestPath = path.join(projectRoot, "Cargo.toml");
|
|
9
|
+
|
|
10
|
+
const args = process.argv.slice(2);
|
|
11
|
+
const command = "cargo";
|
|
12
|
+
// Use --release for production speed
|
|
13
|
+
const runArgs = [
|
|
14
|
+
"run",
|
|
15
|
+
"--release",
|
|
16
|
+
"--quiet",
|
|
17
|
+
"--manifest-path",
|
|
18
|
+
manifestPath,
|
|
19
|
+
"--",
|
|
20
|
+
...args,
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
const child = spawn(command, runArgs, {
|
|
24
|
+
stdio: "inherit",
|
|
25
|
+
shell: true,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
child.on("exit", (code) => {
|
|
29
|
+
process.exit(code);
|
|
30
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "git-ward",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Local-First Git Guard for preventing secret leaks",
|
|
5
|
+
"bin": {
|
|
6
|
+
"ward": "./bin/ward.js"
|
|
7
|
+
},
|
|
8
|
+
"scripts": {
|
|
9
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
10
|
+
"postinstall": "cargo build --release"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"git",
|
|
14
|
+
"secret-scanning",
|
|
15
|
+
"security",
|
|
16
|
+
"cli",
|
|
17
|
+
"pre-commit",
|
|
18
|
+
"ward"
|
|
19
|
+
],
|
|
20
|
+
"author": "awixor",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/awixor/ward.git"
|
|
25
|
+
},
|
|
26
|
+
"bugs": {
|
|
27
|
+
"url": "https://github.com/awixor/ward/issues"
|
|
28
|
+
},
|
|
29
|
+
"homepage": "https://github.com/awixor/ward#readme",
|
|
30
|
+
"files": [
|
|
31
|
+
"bin",
|
|
32
|
+
"src",
|
|
33
|
+
"Cargo.toml",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE"
|
|
36
|
+
]
|
|
37
|
+
}
|
package/src/config.rs
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
use serde::{Deserialize, Serialize};
|
|
2
|
+
use std::fs;
|
|
3
|
+
use std::path::Path;
|
|
4
|
+
use anyhow::{Result, Context};
|
|
5
|
+
|
|
6
|
+
#[derive(Debug, Deserialize, Serialize, Clone)]
|
|
7
|
+
pub struct Config {
|
|
8
|
+
#[serde(default)]
|
|
9
|
+
pub exclude: Vec<String>,
|
|
10
|
+
#[serde(default)]
|
|
11
|
+
pub skip_entropy_checks: Vec<String>,
|
|
12
|
+
#[serde(default = "default_threshold")]
|
|
13
|
+
pub threshold: f32,
|
|
14
|
+
#[serde(default)]
|
|
15
|
+
pub rules: Vec<CustomRule>,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
#[derive(Debug, Deserialize, Serialize, Clone)]
|
|
19
|
+
pub struct CustomRule {
|
|
20
|
+
pub name: String,
|
|
21
|
+
pub regex: String,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
fn default_threshold() -> f32 {
|
|
25
|
+
4.5
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
impl Default for Config {
|
|
29
|
+
fn default() -> Self {
|
|
30
|
+
Self {
|
|
31
|
+
exclude: vec!["*.lock".to_string(), "package-lock.json".to_string(), "yarn.lock".to_string()],
|
|
32
|
+
skip_entropy_checks: vec!["*.min.js".to_string(), "*.svg".to_string()],
|
|
33
|
+
threshold: 4.5,
|
|
34
|
+
rules: vec![],
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
pub fn load_config() -> Result<Config> {
|
|
40
|
+
let config_path = Path::new("ward.toml");
|
|
41
|
+
if config_path.exists() {
|
|
42
|
+
let content = fs::read_to_string(config_path).context("Failed to read ward.toml")?;
|
|
43
|
+
let config: Config = toml::from_str(&content).context("Failed to parse ward.toml")?;
|
|
44
|
+
Ok(config)
|
|
45
|
+
} else {
|
|
46
|
+
Ok(Config::default())
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/git.rs
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
use anyhow::{Result, Context};
|
|
2
|
+
use std::process::Command;
|
|
3
|
+
use std::path::{Path, PathBuf};
|
|
4
|
+
use std::fs;
|
|
5
|
+
use std::os::unix::fs::PermissionsExt;
|
|
6
|
+
use colored::*;
|
|
7
|
+
|
|
8
|
+
const HOOK_SCRIPT: &str = r#"
|
|
9
|
+
# Ward - Local-First Git Guard
|
|
10
|
+
# This hook was automatically installed by Ward.
|
|
11
|
+
if command -v ward >/dev/null 2>&1; then
|
|
12
|
+
ward scan
|
|
13
|
+
else
|
|
14
|
+
# Fallback to local npx if global command not found
|
|
15
|
+
if [ -f "node_modules/.bin/ward" ]; then
|
|
16
|
+
./node_modules/.bin/ward scan
|
|
17
|
+
else
|
|
18
|
+
echo "Ward not found in path or node_modules. Skipping scan."
|
|
19
|
+
fi
|
|
20
|
+
fi
|
|
21
|
+
"#;
|
|
22
|
+
|
|
23
|
+
pub fn install_hook() -> Result<()> {
|
|
24
|
+
// 1. Check if .git exists
|
|
25
|
+
let git_dir = Path::new(".git");
|
|
26
|
+
if !git_dir.exists() {
|
|
27
|
+
println!("{}", "Error: Not a git repository. Run 'git init' first.".red());
|
|
28
|
+
return Ok(());
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let hooks_dir = git_dir.join("hooks");
|
|
32
|
+
if !hooks_dir.exists() {
|
|
33
|
+
fs::create_dir(&hooks_dir).context("Failed to create hooks directory")?;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let pre_commit_path = hooks_dir.join("pre-commit");
|
|
37
|
+
|
|
38
|
+
// 2. Read existing hook or create new
|
|
39
|
+
let mut hook_content = if pre_commit_path.exists() {
|
|
40
|
+
fs::read_to_string(&pre_commit_path).context("Failed to read existing pre-commit hook")?
|
|
41
|
+
} else {
|
|
42
|
+
String::from("#!/bin/sh\n")
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// 3. Simple prepend logic (naive for MVP, improves robust parsing later)
|
|
46
|
+
if !hook_content.contains("ward scan") {
|
|
47
|
+
// Insert after shebang if present
|
|
48
|
+
if hook_content.starts_with("#!") {
|
|
49
|
+
match hook_content.find('\n') {
|
|
50
|
+
Some(idx) => {
|
|
51
|
+
hook_content.insert_str(idx + 1, HOOK_SCRIPT);
|
|
52
|
+
}
|
|
53
|
+
None => {
|
|
54
|
+
hook_content.push_str(HOOK_SCRIPT);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
} else {
|
|
58
|
+
// No shebang? Prepend one + script
|
|
59
|
+
hook_content = format!("#!/bin/sh\n{}{}", HOOK_SCRIPT, hook_content);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
fs::write(&pre_commit_path, &hook_content).context("Failed to write pre-commit hook")?;
|
|
63
|
+
|
|
64
|
+
// Make executable
|
|
65
|
+
let mut perms = fs::metadata(&pre_commit_path)?.permissions();
|
|
66
|
+
perms.set_mode(0o755);
|
|
67
|
+
fs::set_permissions(&pre_commit_path, perms)?;
|
|
68
|
+
|
|
69
|
+
println!("{}", "✓ Ward pre-commit hook installed successfully.".green());
|
|
70
|
+
} else {
|
|
71
|
+
println!("{}", "ℹ Ward hook already exists.".yellow());
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
Ok(())
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
pub fn get_staged_files() -> Result<Vec<PathBuf>> {
|
|
78
|
+
let output = Command::new("git")
|
|
79
|
+
.args(&["diff", "--cached", "--name-only", "--diff-filter=ACM"])
|
|
80
|
+
.output()
|
|
81
|
+
.context("Failed to execute git diff")?;
|
|
82
|
+
|
|
83
|
+
if !output.status.success() {
|
|
84
|
+
// Handle case where no commit yet?
|
|
85
|
+
return Ok(vec![]);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
let output_str = String::from_utf8(output.stdout)?;
|
|
89
|
+
let files = output_str
|
|
90
|
+
.lines()
|
|
91
|
+
.map(|s| PathBuf::from(s.trim()))
|
|
92
|
+
.filter(|p| p.exists()) // Verify file exists on disk
|
|
93
|
+
.collect();
|
|
94
|
+
|
|
95
|
+
Ok(files)
|
|
96
|
+
}
|
package/src/main.rs
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
use clap::{Parser, Subcommand};
|
|
2
|
+
use colored::*;
|
|
3
|
+
use anyhow::Result;
|
|
4
|
+
use std::process::exit;
|
|
5
|
+
|
|
6
|
+
mod config;
|
|
7
|
+
mod git;
|
|
8
|
+
mod scanner;
|
|
9
|
+
|
|
10
|
+
#[derive(Parser)]
|
|
11
|
+
#[command(author, version, about, long_about = None)]
|
|
12
|
+
#[command(propagate_version = true)]
|
|
13
|
+
struct Cli {
|
|
14
|
+
#[command(subcommand)]
|
|
15
|
+
command: Commands,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
#[derive(Subcommand)]
|
|
19
|
+
enum Commands {
|
|
20
|
+
/// Initialize Ward in the current repository
|
|
21
|
+
Init,
|
|
22
|
+
/// Scan staged files for secrets
|
|
23
|
+
Scan,
|
|
24
|
+
/// Check for updates (stub)
|
|
25
|
+
CheckUpdates,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
fn main() -> Result<()> {
|
|
29
|
+
let cli = Cli::parse();
|
|
30
|
+
|
|
31
|
+
match &cli.command {
|
|
32
|
+
Commands::Init => {
|
|
33
|
+
println!("{}", "Initializing Ward...".blue());
|
|
34
|
+
git::install_hook()?;
|
|
35
|
+
}
|
|
36
|
+
Commands::Scan => {
|
|
37
|
+
// 1. Load Config
|
|
38
|
+
let config = config::load_config().unwrap_or_else(|e| {
|
|
39
|
+
println!("{}", format!("Warning: Failed to load config: {}", e).yellow());
|
|
40
|
+
config::Config::default()
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// 2. Get Staged Files
|
|
44
|
+
let files = git::get_staged_files()?;
|
|
45
|
+
if files.is_empty() {
|
|
46
|
+
return Ok(());
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 3. Scan
|
|
50
|
+
let scanner = scanner::Scanner::new(config);
|
|
51
|
+
let mut all_violations = vec![];
|
|
52
|
+
|
|
53
|
+
for file in files {
|
|
54
|
+
match scanner.scan_file(&file) {
|
|
55
|
+
Ok(mut v) => all_violations.append(&mut v),
|
|
56
|
+
Err(e) => eprintln!("Error scanning {:?}: {}", file, e),
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 4. Report
|
|
61
|
+
if !all_violations.is_empty() {
|
|
62
|
+
println!("\n{}", "Ward detected sensitive data in your commit:".red().bold());
|
|
63
|
+
for v in all_violations {
|
|
64
|
+
let masked_snippet = if v.snippet.len() <= 8 {
|
|
65
|
+
"[REDACTED]".to_string()
|
|
66
|
+
} else {
|
|
67
|
+
format!("{}...{}", &v.snippet[..4], &v.snippet[v.snippet.len()-4..])
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
println!(
|
|
71
|
+
" {} {}:{}: {}",
|
|
72
|
+
"✖".red(),
|
|
73
|
+
v.file.display(),
|
|
74
|
+
v.line.to_string().cyan(),
|
|
75
|
+
v.rule.yellow()
|
|
76
|
+
);
|
|
77
|
+
println!(" Code: {}", masked_snippet.dimmed());
|
|
78
|
+
}
|
|
79
|
+
println!("\n{}", "Commit blocked. Remove the secrets or use 'git commit --no-verify' to bypass.".red());
|
|
80
|
+
exit(1);
|
|
81
|
+
} else {
|
|
82
|
+
println!("{}", "✓ Ward scan clean".green());
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
Commands::CheckUpdates => {
|
|
86
|
+
println!("You are running the latest version of Ward.");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
Ok(())
|
|
91
|
+
}
|
package/src/scanner.rs
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
use crate::config::Config;
|
|
2
|
+
use regex::Regex;
|
|
3
|
+
use globset::{Glob, GlobSet, GlobSetBuilder};
|
|
4
|
+
use std::fs;
|
|
5
|
+
use std::path::{Path, PathBuf};
|
|
6
|
+
use std::collections::HashMap;
|
|
7
|
+
use anyhow::Result;
|
|
8
|
+
|
|
9
|
+
#[derive(Debug)]
|
|
10
|
+
pub struct Violation {
|
|
11
|
+
pub file: PathBuf,
|
|
12
|
+
pub line: usize,
|
|
13
|
+
pub rule: String,
|
|
14
|
+
pub snippet: String,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
pub struct Scanner {
|
|
18
|
+
config: Config,
|
|
19
|
+
patterns: Vec<(String, Regex)>,
|
|
20
|
+
exclude_globnet: GlobSet,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
fn shannon_entropy(s: &str) -> f32 {
|
|
24
|
+
let mut map = HashMap::new();
|
|
25
|
+
let len = s.len() as f32;
|
|
26
|
+
|
|
27
|
+
for c in s.chars() {
|
|
28
|
+
*map.entry(c).or_insert(0.0) += 1.0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
map.values().fold(0.0, |acc, &count| {
|
|
32
|
+
let p = count / len;
|
|
33
|
+
acc - p * p.log2()
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
impl Scanner {
|
|
38
|
+
pub fn new(config: Config) -> Self {
|
|
39
|
+
let mut patterns = vec![
|
|
40
|
+
("Ethereum Private Key".to_string(), Regex::new(r"(?i)0x[a-fA-F0-9]{64}").unwrap()),
|
|
41
|
+
("BIP-39 Mnemonic".to_string(), Regex::new(r"(?i)(\b[a-z]{3,}\b\s){11,}\b[a-z]{3,}\b").unwrap()),
|
|
42
|
+
("Generic API Key".to_string(), Regex::new(r#"(?i)(api_key|access_token|secret_key)[\s:=]+['""]?[a-zA-Z0-9_\-]{20,}"#).unwrap()),
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
// Add custom rules
|
|
46
|
+
for rule in &config.rules {
|
|
47
|
+
if let Ok(re) = Regex::new(&rule.regex) {
|
|
48
|
+
patterns.push((rule.name.clone(), re));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Build GlobSet for excludes
|
|
53
|
+
let mut builder = GlobSetBuilder::new();
|
|
54
|
+
for pattern in &config.exclude {
|
|
55
|
+
if let Ok(glob) = Glob::new(pattern) {
|
|
56
|
+
builder.add(glob);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
let exclude_globnet = builder.build().unwrap_or_else(|_| GlobSet::empty());
|
|
60
|
+
|
|
61
|
+
Self { config, patterns, exclude_globnet }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
pub fn scan_file(&self, path: &Path) -> Result<Vec<Violation>> {
|
|
65
|
+
if self.exclude_globnet.is_match(path) {
|
|
66
|
+
return Ok(vec![]);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
let mut violations = vec![];
|
|
70
|
+
|
|
71
|
+
// Skip binary check (basic)
|
|
72
|
+
// In a real impl, we'd read first 1024 bytes to check for nulls
|
|
73
|
+
let content = match fs::read_to_string(path) {
|
|
74
|
+
Ok(c) => c,
|
|
75
|
+
Err(_) => return Ok(vec![]), // Skip binary or unreadable
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
for (i, line) in content.lines().enumerate() {
|
|
79
|
+
let line_idx = i + 1;
|
|
80
|
+
|
|
81
|
+
// 1. Regex Check
|
|
82
|
+
for (name, re) in &self.patterns {
|
|
83
|
+
if re.is_match(line) {
|
|
84
|
+
violations.push(Violation {
|
|
85
|
+
file: path.to_path_buf(),
|
|
86
|
+
line: line_idx,
|
|
87
|
+
rule: name.clone(),
|
|
88
|
+
snippet: line.trim().chars().take(50).collect(),
|
|
89
|
+
});
|
|
90
|
+
continue; // Detected, move to next line
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 2. Entropy Check
|
|
95
|
+
// Verify if we should skip this file for entropy
|
|
96
|
+
let skip_entropy = self.config.skip_entropy_checks.iter().any(|pattern| {
|
|
97
|
+
// Simple contains check for MVP, glob matching TODO
|
|
98
|
+
path.to_string_lossy().contains(pattern.trim_start_matches('*'))
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
if !skip_entropy {
|
|
102
|
+
// Only check words/tokens > 20 chars
|
|
103
|
+
for word in line.split_whitespace() {
|
|
104
|
+
// Clean common wrapping punctuation from the word
|
|
105
|
+
let clean_word = word.trim_matches(|c| "()[]{}\";',".contains(c));
|
|
106
|
+
|
|
107
|
+
if clean_word.len() > 20 {
|
|
108
|
+
// Skip if it looks like code function calls or paths
|
|
109
|
+
if clean_word.contains("::") || clean_word.contains("->") {
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
let entropy = shannon_entropy(clean_word);
|
|
114
|
+
if entropy > self.config.threshold {
|
|
115
|
+
violations.push(Violation {
|
|
116
|
+
file: path.to_path_buf(),
|
|
117
|
+
line: line_idx,
|
|
118
|
+
rule: format!("High Entropy ({:.2})", entropy),
|
|
119
|
+
snippet: clean_word.chars().take(20).collect(), // truncated
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
Ok(violations)
|
|
128
|
+
}
|
|
129
|
+
}
|