Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check for web3 private keys #1132

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 7 additions & 0 deletions .pre-commit-hooks.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,13 @@
entry: detect-private-key
language: python
types: [text]
- id: detect-web3-private-key
name: detect web3 private key
description: detects the presence of web3 private keys.
entry: detect-web3-private-key
language: python
types: [file]
additional_dependencies: ['eth-account']
- id: double-quote-string-fixer
name: fix double quoted strings
description: replaces double quoted strings with single quoted strings.
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ The following arguments are available:
#### `detect-private-key`
Checks for the existence of private keys.

#### `detect-web3-private-key`
Checks for the existence of web3 private keys. Add `# web3-private-key-ok` to the end of the line to ignore false positives.

#### `double-quote-string-fixer`
This hook replaces double quoted strings with single quoted strings.

Expand Down
80 changes: 80 additions & 0 deletions pre_commit_hooks/detect_web3_private_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""
This script checks files for potential Web3 private keys.
"""
from __future__ import annotations

import argparse
import os
import re
import sys
from collections.abc import Sequence

from eth_account import Account
from eth_utils import decode_hex

# Regular expression to match Ethereum private keys
KEY_PATTERN = re.compile(r'\b(0x)?[a-fA-F0-9]{64}\b')
IGNORE_COMMENT = '# web3-private-key-ok'


def is_private_key_valid(private_key_hex: str) -> bool:
try:
# Remove hex prefix if present
if private_key_hex.startswith('0x'):
private_key_hex = private_key_hex[2:]

# Decode the hex string to bytes
private_key_bytes = decode_hex(private_key_hex)

# Attempt to create an account object
Account.from_key(private_key_bytes)

return True

except Exception:
return False


def scan_file(file_path: str) -> bool:
"""
Scans a file for potential Web3 private keys.
"""
detected = False
try:
with open(file_path, encoding='utf-8', errors='ignore') as f:
for idx, line in enumerate(f):
match = KEY_PATTERN.search(line)
if match and IGNORE_COMMENT not in line:
private_key_hex = match.group(0)
if is_private_key_valid(private_key_hex):
print(
f"Error: Valid Web3 private key detected in {file_path}:{idx + 1}",
)
detected = True
except Exception as e:
print(f"Warning: Error reading file {file_path}: {e}")
return detected


def main(argv: Sequence[str] | None = None) -> None:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)

files_with_keys = []
for file_path in args.filenames:
if not os.path.isfile(file_path):
continue

if scan_file(file_path):
files_with_keys.append(file_path)

if files_with_keys:
sys.exit(1)
else:
sys.exit(0)


if __name__ == '__main__':
main()
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ console_scripts =
destroyed-symlinks = pre_commit_hooks.destroyed_symlinks:main
detect-aws-credentials = pre_commit_hooks.detect_aws_credentials:main
detect-private-key = pre_commit_hooks.detect_private_key:main
detect-web3-private-key = pre_commit_hooks.detect_web3_private_key:main
double-quote-string-fixer = pre_commit_hooks.string_fixer:main
end-of-file-fixer = pre_commit_hooks.end_of_file_fixer:main
file-contents-sorter = pre_commit_hooks.file_contents_sorter:main
Expand Down
Loading