Created
July 12, 2013 14:02
-
-
Save ptman/5984691 to your computer and use it in GitHub Desktop.
Usage: ./ssh_scan_keys.py /home /export/home
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
# vim: set ts=4 sts=4 sw=4 si ai et ft=python: | |
# author: Paul Tötterman <[email protected]> | |
# | |
# Copyright (c) 2013, ZenRobotics Ltd. | |
# | |
# Permission to use, copy, modify, and/or distribute this software for any | |
# purpose with or without fee is hereby granted, provided that the above | |
# copyright notice and this permission notice appear in all copies. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES | |
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | |
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR | |
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES | |
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN | |
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF | |
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | |
"""Scan for unencrypted SSH private keys.""" | |
import os | |
import socket | |
import stat | |
import sys | |
HEADER = '-----BEGIN RSA PRIVATE KEY-----' | |
HOSTNAME = socket.gethostname() | |
def is_encrypted(filename): | |
"""Return true if the file contains an encrypted SSH private key.""" | |
with open(filename, 'rb') as infile: | |
lines = infile.readlines() | |
enc_lines = [line for line in lines if 'ENCRYPTED' in line] | |
return bool(enc_lines) | |
def detect_rsa_pem(filename): | |
"""Return true if the file beings with a RSA private key header.""" | |
with open(filename, 'rb') as infile: | |
start = infile.read(len(HEADER)) | |
if start == HEADER: | |
return True | |
return False | |
def main(args): | |
"""Main function.""" | |
for path in args[1:]: | |
for root, _, files in os.walk(path): | |
for filename in files: | |
try: | |
abspath = os.path.join(root, filename) | |
if os.path.islink(abspath): | |
continue | |
mode = os.stat(abspath).st_mode | |
if not stat.S_ISREG(mode): | |
continue | |
if detect_rsa_pem(abspath): | |
if not is_encrypted(abspath): | |
print 'Unencrypted rsa pem file: %s:%s' % (HOSTNAME, | |
abspath) | |
except IOError: | |
continue | |
if __name__ == '__main__': | |
main(sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment