pre-commit-hooks/pre_commit_hooks/detect_private_key.py

43 lines
1.1 KiB
Python
Raw Normal View History

from __future__ import annotations
import argparse
from collections.abc import Sequence
2015-03-07 04:45:32 +08:00
BLACKLIST = [
b'BEGIN RSA PRIVATE KEY',
b'BEGIN DSA PRIVATE KEY',
b'BEGIN EC PRIVATE KEY',
2016-12-27 06:51:26 +08:00
b'BEGIN OPENSSH PRIVATE KEY',
2018-01-14 09:16:50 +08:00
b'BEGIN PRIVATE KEY',
2018-05-19 07:31:16 +08:00
b'PuTTY-User-Key-File-2',
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
2018-10-23 03:11:59 +08:00
b'BEGIN PGP PRIVATE KEY BLOCK',
b'BEGIN ENCRYPTED PRIVATE KEY',
b'BEGIN OpenVPN Static key V1',
]
2015-03-07 04:45:32 +08:00
def main(argv: Sequence[str] | None = None) -> int:
2015-03-07 04:45:32 +08:00
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
private_key_files = []
for filename in args.filenames:
with open(filename, 'rb') as f:
content = f.read()
if any(line in content for line in BLACKLIST):
private_key_files.append(filename)
2015-03-07 04:45:32 +08:00
if private_key_files:
for private_key_file in private_key_files:
2020-02-06 03:10:42 +08:00
print(f'Private key found: {private_key_file}')
2015-03-07 04:45:32 +08:00
return 1
else:
return 0
if __name__ == '__main__':
raise SystemExit(main())