|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +This script checks files for potential Web3 private keys. |
| 4 | +""" |
| 5 | + |
| 6 | +import argparse |
| 7 | +import os |
| 8 | +import re |
| 9 | +import sys |
| 10 | +from typing import Sequence |
| 11 | + |
| 12 | +from eth_account import Account |
| 13 | +from eth_utils import decode_hex |
| 14 | + |
| 15 | +# Regular expression to match Ethereum private keys |
| 16 | +KEY_PATTERN = re.compile(r"\b(0x)?[a-fA-F0-9]{64}\b") |
| 17 | +IGNORE_COMMENT = "# web3-private-key-ok" |
| 18 | + |
| 19 | + |
| 20 | +def is_private_key_valid(private_key_hex: str) -> bool: |
| 21 | + try: |
| 22 | + # Remove hex prefix if present |
| 23 | + if private_key_hex.startswith("0x"): |
| 24 | + private_key_hex = private_key_hex[2:] |
| 25 | + |
| 26 | + # Decode the hex string to bytes |
| 27 | + private_key_bytes = decode_hex(private_key_hex) |
| 28 | + |
| 29 | + # Attempt to create an account object |
| 30 | + Account.from_key(private_key_bytes) |
| 31 | + |
| 32 | + return True |
| 33 | + |
| 34 | + except Exception: |
| 35 | + return False |
| 36 | + |
| 37 | + |
| 38 | +def scan_file(file_path: str) -> bool: |
| 39 | + """ |
| 40 | + Scans a file for potential Web3 private keys. |
| 41 | + """ |
| 42 | + detected = False |
| 43 | + try: |
| 44 | + with open(file_path, "r", encoding="utf-8", errors="ignore") as f: |
| 45 | + for idx, line in enumerate(f): |
| 46 | + match = KEY_PATTERN.search(line) |
| 47 | + if match and IGNORE_COMMENT not in line: |
| 48 | + private_key_hex = match.group(0) |
| 49 | + if is_private_key_valid(private_key_hex): |
| 50 | + print( |
| 51 | + f"Error: Valid Web3 private key detected in {file_path}:{idx + 1}" |
| 52 | + ) |
| 53 | + detected = True |
| 54 | + except Exception as e: |
| 55 | + print(f"Warning: Error reading file {file_path}: {e}") |
| 56 | + return detected |
| 57 | + |
| 58 | + |
| 59 | +def main(argv: Sequence[str] | None = None) -> None: |
| 60 | + parser = argparse.ArgumentParser() |
| 61 | + parser.add_argument("filenames", nargs="*", help="Filenames to check") |
| 62 | + args = parser.parse_args(argv) |
| 63 | + |
| 64 | + files_with_keys = [] |
| 65 | + for file_path in args.filenames: |
| 66 | + if not os.path.isfile(file_path): |
| 67 | + continue |
| 68 | + |
| 69 | + if scan_file(file_path): |
| 70 | + files_with_keys.append(file_path) |
| 71 | + |
| 72 | + if files_with_keys: |
| 73 | + sys.exit(1) |
| 74 | + else: |
| 75 | + sys.exit(0) |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + main() |
0 commit comments