import json import sys from os import path, listdir SCRIPT_VERSION = 0.1 # script to discover keychain corruption KEYCHAIN_PATH = "/Users/{0}/Library/Keychains" def get_keychain_paths(): users = listdir("/Users/") keychain_paths = [] for user in users: keychain_path = KEYCHAIN_PATH.format(user) if path.exists(keychain_path): keychain_paths.append(keychain_path) return keychain_paths def is_corrupt(keychain_path, keychain): # (1) Filename fits the profile: login.keychain-db.sb-xxxxxxxx-xxxxxx-db # (2) Filesize is 0 if not keychain.startswith('login.keychain-db.sb-'): return False if not keychain.endswith('-db'): return False if path.getsize(path.join(keychain_path, keychain)) > 0: return False return True def get_keychains(): keychain_paths = get_keychain_paths() filtered_keychains = [] for keychain_path in keychain_paths: all_keychains = listdir(keychain_path) filtered_keychains = filtered_keychains + [keychain for keychain in all_keychains if is_corrupt(keychain_path, keychain)] return filtered_keychains def construct_output(data): return { 'script_version' : SCRIPT_VERSION, 'corrupt_keychains' : data, 'count': len(data) } if sys.platform == 'darwin': corrupt_keychains = get_keychains() output = construct_output(corrupt_keychains) sys.stdout.write(json.dumps(output))