|
| 1 | +#!/usr/bin/env python |
| 2 | +from __future__ import print_function |
| 3 | + |
| 4 | +import argparse |
| 5 | +import re |
| 6 | +import sys |
| 7 | + |
| 8 | + |
| 9 | +def detect_aws_access_key(line): |
| 10 | + match = re.search(r"(?<![A-Z0-9])[A-Z0-9]{20}(?![A-Z0-9])", line) |
| 11 | + return match, "AWS access key" |
| 12 | + |
| 13 | + |
| 14 | +def detect_aws_secret_key(line): |
| 15 | + match = re.search(r"(?<![A-Za-z0-9/+=])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])", line) |
| 16 | + return match, "AWS secret key" |
| 17 | + |
| 18 | + |
| 19 | +def detect_dd_api_key(line): |
| 20 | + match = re.search(r"(?<![a-fA-F0-9])[a-fA-F0-9]{32}(?![a-fA-F0-9])", line) |
| 21 | + return match, "Datadog API key" |
| 22 | + |
| 23 | + |
| 24 | +def detect_dd_app_key(line): |
| 25 | + match = re.search(r"(?<![a-fA-F0-9])[a-fA-F0-9]{40}(?![a-fA-F0-9])", line) |
| 26 | + return match, "Datadog app key" |
| 27 | + |
| 28 | + |
| 29 | +def key_found_message(args): |
| 30 | + return ( |
| 31 | + "\033[91m" |
| 32 | + "Potential {} found in {} at line {} and column {}. " |
| 33 | + "Please remove the key before committing these changes." |
| 34 | + "\033[0m".format(*args) |
| 35 | + ) |
| 36 | + |
| 37 | + |
| 38 | +def main(argv=None): |
| 39 | + parser = argparse.ArgumentParser() |
| 40 | + parser.add_argument("filenames", nargs="*", help="Filenames to check.") |
| 41 | + args = parser.parse_args(argv) |
| 42 | + |
| 43 | + # add or remove functions here |
| 44 | + functions_to_run = [ |
| 45 | + detect_aws_access_key, |
| 46 | + detect_aws_secret_key, |
| 47 | + detect_dd_api_key, |
| 48 | + detect_dd_app_key, |
| 49 | + ] |
| 50 | + |
| 51 | + files_with_key = [] |
| 52 | + |
| 53 | + for filename in args.filenames: |
| 54 | + with open(filename, "r") as f: |
| 55 | + content = f.readlines() |
| 56 | + f.close() |
| 57 | + |
| 58 | + for i, line in enumerate(content): |
| 59 | + for func in functions_to_run: |
| 60 | + match, name = func(line) |
| 61 | + if match != None: |
| 62 | + files_with_key.append((name, filename, i + 1, match.end())) |
| 63 | + |
| 64 | + if files_with_key: |
| 65 | + for file in files_with_key: |
| 66 | + print(key_found_message(file)) |
| 67 | + return 1 |
| 68 | + else: |
| 69 | + return 0 |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + sys.exit(main()) |
0 commit comments