def cmdline(version): parser = argparse.ArgumentParser(description='Gather listening ports') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('--no-udp', dest="no_udp", action='store_true', default=False, help="No UDP ports") parser.add_argument('--no-local', dest="no_local", action='store_true', default=False, help="Don't include services listening locally (127.0.0.0/24)") parser.add_argument('--no-verified', dest="no_verified", action='store_true', default=False, help="Don't include verified port") args = parser.parse_args() common.configure_logger(args.debug) results = gather(no_udp=args.no_udp, no_local=args.no_local, no_verified=args.no_verified, annotate=args.annotate) sys.stdout.write(json.dumps({"listenports": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser( description='Output SSL / TLS protocol and ciphers for ports') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('--ports', dest="ports", type=str, default=[443], help="Port(s) to scan in nmap format. Defaults to 443") parser.add_argument('targets', metavar='target', type=str, nargs='+', help='Target hosts to scan') args = parser.parse_args() common.configure_logger(args.debug) if args.targets is None: sys.stderr.write("Please specify one or more targets\n") sys.exit(1) if shutil.which("nmap") is None: sys.stderr.write("nmap not found. Please install it.\n") sys.exit(1) for target in args.targets: if target.lower().startswith("http"): sys.stderr.write( "Please specify an IP or hostname, not http:// or https:// ({})\n" .format(target)) sys.exit(1) results = gather(args.targets, args.ports, args.annotate) sys.stdout.write(json.dumps({"sslscan": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser(description='Output unix login sessions') common.arg_add_defaults(parser, version=version, annotate=True) args = parser.parse_args() common.configure_logger(args.debug) results = gather() sys.stdout.write(json.dumps({"unixsessions": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser( description='Gather iptables firewall status') common.arg_add_defaults(parser, version=version) args = parser.parse_args() common.configure_logger(args.debug) verify_root() results = gather() sys.stdout.write(json.dumps({"iptables": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser(description='Gather unix users') common.arg_add_defaults(parser, version=version, annotate=False) parser.add_argument('easyrsa_index', metavar='EASYRSA_INDEX', type=str, help='Path to the EasyRSA index.txt') args = parser.parse_args() common.configure_logger(args.debug) results = gather(args.easyrsa_index) sys.stdout.write( json.dumps({"openvpnusers": results}, indent=4, default=json_serial))
def cmdline(version): parser = argparse.ArgumentParser(description='Scan for http security headers on URLs') common.arg_add_defaults(parser, version=version) parser.add_argument('urls', metavar='urls', type=str, nargs='+', help='Target URLs to scan') args = parser.parse_args() common.configure_logger(args.debug) results = gather(args.urls) sys.stdout.write(json.dumps({"http_headers": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser(description='Gather unix users') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('--not-empty', dest="not_empty", action='store_true', default=True, help="Only groups that are not empty") args = parser.parse_args() common.configure_logger(args.debug) results = gather(not_empty=args.not_empty) sys.stdout.write(json.dumps({"unixgroups": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser( description='Output unix users and their details') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('--login', dest="login", action='store_true', default=False, help="Only users that can log in") args = parser.parse_args() common.configure_logger(args.debug) results = gather(login=args.login) sys.stdout.write(json.dumps({"unixusers": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser( description='Output files and dirs with dangerous permissions') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('dir', metavar='DIR', type=str, nargs='+', help='Dir to scan') args = parser.parse_args() common.configure_logger(args.debug) results = [] for dir in args.dir: results.extend(gather(dir)) sys.stdout.write(json.dumps({"perms": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser(description='Scan for open ports on machine') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('--ports', dest="ports", type=str, default=None, help="Port range to scan (nmap format)") parser.add_argument('--all', dest="all", action='store_true', default=False, help="Report all ports, not just 'open' states.") parser.add_argument('--ports-exclude', dest="ports_exclude", type=str, default=None, help="Port range(s) to skip") parser.add_argument('targets', metavar='target', type=str, nargs='+', help='Target(s) to scan') args = parser.parse_args() common.configure_logger(args.debug) if args.targets is None: sys.stderr.write("Please specify one or more targets\n") sys.exit(1) if shutil.which("nmap") is None: sys.stderr.write("nmap not found. Please install it.\n") sys.exit(1) ports_exclude = None if args.ports_exclude is not None: ports_exclude = expand_range(args.ports_exclude) verify_root() results = gather(args.targets, args.annotate, args.ports, args.all, ports_exclude) sys.stdout.write(json.dumps({"portscan": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser(description='Gather mysql users') common.arg_add_defaults(parser, version=version, annotate=False) parser.add_argument( '--no-conn-error', dest="no_conn_error", action="store_true", default=False, help="If cannot connect to mysql, return empty response") args = parser.parse_args() common.configure_logger(args.debug) # Try MySQL connection if args.no_conn_error is True: cmd_status = morestd.shell.cmd('mysql -N -B -e "SELECT 1"', raise_err=False) if cmd_status['exitcode'] != 0: sys.exit(1) results = gather() sys.stdout.write(json.dumps({"mysqlusers": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser(description='Gather misconfigurations') common.arg_add_defaults(parser, version=version, annotate=False) parser.add_argument('--skip-passed', dest='skip_passed', action='store_true', default=False, help="Don't include passed tests") parser.add_argument('--config', dest='config', action='store', type=str, default=None, help='Configuration file for tests') parser.add_argument('--limit', dest='limit', action='store', type=str, default=None, help='Limit which tests are executed') args = parser.parse_args() common.configure_logger(args.debug) # Parse limit if args.limit is not None: args.limit = args.limit.split(',') # Read configuration config = {} if args.config is not None: logging.info("Reading config {}".format(args.config)) config = ast.literal_eval(open(args.config, 'r').read()) # Run tests results = gather(config=config, skip_passed=args.skip_passed, limit=args.limit, debug=args.debug) sys.stdout.write(json.dumps({"misconfigs": results}, indent=4))
def cmdline(version): parser = argparse.ArgumentParser( description='Scan for open ports on machine') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('--ports', dest="ports", type=str, default=[443], help="Port(s) to scan (nmap format)") parser.add_argument('targets', metavar='target', type=str, nargs='+', help='Target(s) to scan') args = parser.parse_args() common.configure_logger(args.debug) if args.targets is None: sys.stderr.write("Please specify one or more targets\n") sys.exit(1) results = gather(args.targets, args.ports, args.annotate) sys.stdout.write(json.dumps({"portprotos": results}, indent=4))
#!/usr/bin/env python3 from os import chdir from time import sleep # Where the magic happens import common if __name__ == '__main__': # Grab the command line args and calculated verbosity (args, verbosity) = common.parse_args() # Set up the fancy logger, with optional file logging common.configure_logger(verbosity, args.logfile) # We're calling this a lot, so let's make it shorter logger = common.logger # And let's load the config file into common-space common.load_configuration(args.configfile) # For simplicity, shift to the repo root path = common.get_path() chdir(path) # Load checks and actions into the common-space # Sources are loaded by the checks themselves # Likewise, filters are loaded by actions common.get_thing('checks', common.checks) common.get_thing('actions', common.actions) while True: messages = [] now = common.now(update=True)
import os import zmq import json import copy import base64 import logging from peer import Peer from common import context, configure_logger logger = logging.getLogger(__name__) configure_logger(logger) class SemosancusControl: def control_address(self): if self.directory[0] == '/': directory = self.directory else: directory = os.path.join(os.getcwd(), self.directory) return 'ipc://' + os.path.join(directory, 'control') def bind_control(self): socket = context.socket(zmq.REP) socket.bind(self.control_address()) return socket def handle_control(self, envelope): contents = envelope.get('Message') messageType = contents and contents.get('Message Type') normalizedType = messageType.lower().replace(' ', '_') logger.debug(self.address + ' handle_control_' + normalizedType)
def cmdline(version): formats = ['json', 'text', 'html'] parser = argparse.ArgumentParser( description='Diff JSON from stdin against JSON from file.') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('--format', dest="format", choices=formats, type=str, default="text", help="Output format") parser.add_argument('--exclude', dest="exclude", type=str, help="Exclude keys") parser.add_argument('--include-init', dest="include_init", action="store_true", default=False, help="Output initial results as 'added'") parser.add_argument('statefile', metavar='STATEFILE', type=str, help='File on disk to check stdin against.') args = parser.parse_args() common.configure_logger(args.debug) if not os.path.exists(args.statefile) and \ args.include_init is False: # First time diff, write previous scan to disk with open(args.statefile, 'w') as f: f.write(sys.stdin.read()) sys.exit(0) # Compare old from disk with new from stdin try: old_c = json.load(open(args.statefile, 'r')) except FileNotFoundError: if args.include_init is True: old_c = {} else: raise except ValueError as err: sys.stderr.write("Invalid state file '{}': {}\n".format( args.statefile, err)) sys.exit(1) new_c = json.load(sys.stdin) changes = diff(old_c, new_c) # filter out changes if args.exclude: # build a list of exclude paths exclude_paths = [] filtered_changed = [] for exclude in args.exclude.split(','): exclude_path = exclude.split('.') exclude_paths.append(exclude_path) # Test each change to see if its path (e.g. listenports -> 53 -> proto) # is in the exclude list. Replaces original `changes` list. filtered_changes = [] for change in changes: if not exclude_list(change, exclude_paths): filtered_changes.append(change) changes = filtered_changes if args.format == 'json': sys.stdout.write(json.dumps(changes)) sys.stdout.write("\n") elif args.format == 'text': sys.stdout.write( tools.tpl_str(text_tpl, changes=changes, format_value=format_value)) elif args.format == 'html': sys.stdout.write(tools.tpl_str(html_tpl, changes=changes)) # Write new contents to key file. with open(args.statefile, 'w') as f: json.dump(new_c, f, indent=4)
def cmdline(version): parser = argparse.ArgumentParser(description='Generate reports') common.arg_add_defaults(parser, version=version, annotate=True) parser.add_argument('--tpl-dirs', dest="tpl_dirs", action='store', default=None, help="Extra template dirs") parser.add_argument('--title', dest="title", action='store', default=None, help="Title for the report") parser.add_argument('--hostname', dest="hostname", action='store', default=None, help="Hostname the report is about") parser.add_argument('report', metavar='REPORT', type=str, help='Mako report template') parser.add_argument('assets', metavar='ASSETS', type=str, default=None, nargs='*', help='JSON files to be made accessible to the report.') args = parser.parse_args() common.configure_logger(args.debug) # data will hold all collected data (stdin, assets) data = {} # Check whether there is data on stdin if not sys.stdin.isatty(): morestd.data.deepupdate(data, json.load(sys.stdin)) # Load any data from assets provided for asset in args.assets: try: morestd.data.deepupdate(data, json.load(open(asset, 'r'))) except ValueError as err: sys.stderr.write("Error loading asset '{}': {}\n".format( asset, err)) if args.debug is True: raise sys.exit(1) # Set hostname to current host if not specified if args.hostname is None: args.hostname = socket.getfqdn() # Construct additional template lookup dirs tpl_dirs = get_tpl_dirs(args) logging.info("Extra template lookup dirs: {}".format(tpl_dirs)) # User-provided dirs if args.tpl_dirs is not None: tpl_dirs.extend(args.tpl_dirs.split(',')) # Render and output template sys.stdout.write( tools.tpl_file(args.report, extra_tpl_dirs=tpl_dirs, data=data, title=args.title, hostname=args.hostname))