Esempio n. 1
0
def parse_program_arguments(arguments):
    parser = ArgumentParser(prog='check_soti', description='performs some checks for SOTI')
    parser.add_argument('-c', '--containers', dest='containers', help='look for SOTI containers', action='store_true')
    parser.add_argument('-g', '--get8k', dest='get8k', help='gets the first 8k bytes from target boot drive', action='store_true')
    parser.add_argument('-l', '--localhash', dest='localhash', help='locally hashes first 8k bytes from target', action='store_true')
    parser.add_argument('-q', '--quiet', dest='quiet', help='one line output, intended for survey', action='store_true')
    options = parser.parse_args()
    if (options.localhash and (options.get8k is not True)):
        if options.containers:
            containers()
        localhash(None)
        printlog(options.quiet)
        return
    if operator.xor(options.containers, options.get8k):
        if options.containers:
            containers()
        if options.get8k:
            get8k()
            if options.localhash:
                log('  not running -l since -g ran', '-g ran -> no -l')
    else:
        containers()
        get8k()
        if options.localhash:
            log('  not running -l since -g ran', '-g ran -> no -l')
    printlog(options.quiet)
Esempio n. 2
0
def main(args=[]):
    flags = dsz.control.Method()
    if ((__name__ == '__main__') and (dsz.script.Env['script_parent_echo_disabled'].lower() == 'true')):
        dsz.control.quiet.On()
    parser = ArgumentParser(prog='prettych', add_help=False)
    cmdopts = parser.add_argument_group(title='commands options')
    cmdopts.add_argument('--all', action='store_true', help='Also display finished commands')
    cmdopts.add_argument('--any', action='store_true', help='Display commands from any address')
    locationgrp = cmdopts.add_mutually_exclusive_group()
    locationgrp.add_argument('--local', dest='location', default=LOCATION_LOCAL, const=LOCATION_LOCAL, action='store_const', help='List local commands (default)')
    locationgrp.add_argument('--remote', dest='location', const=LOCATION_REMOTE, action='store_const', help='List remote commands')
    cmdopts.add_argument('--astyped', action='store_true', help='Show commands as typed (rather than displaying expanded aliases)')
    cmdopts.add_argument('--verbose', action='store_true', help='Show additional command information')
    parser.add_argument('--echo', dest='dszquiet', default=True, action='store_false', help='Echo out the raw DSZ commands output in addition to pretty printing.')
    options = parser.parse_args(args)
    commands = ops.cmd.getDszCommand('commands', prefixes=['stopaliasing'], all=options.all, any=options.any, astyped=options.astyped, verbose=options.verbose, dszquiet=options.dszquiet)
    if (options.location == LOCATION_LOCAL):
        header = []
        fields = []
        if options.all:
            header.append('Status')
            fields.append('status')
        header.extend(['ID', 'Target'])
        fields.extend(['id', 'targetaddress'])
        if (options.astyped or options.verbose):
            header.append('Command (as-typed)')
            fields.append('commandastyped')
        if ((not options.astyped) or options.verbose):
            header.append('Full Command')
            fields.append('fullcommand')
        header.extend(['Sent', 'Received'])
        fields.extend(['bytessent', 'bytesreceived'])
    elif (options.location == LOCATION_REMOTE):
        commands.remote = True
        header = ['ID', 'Command']
        fields = ['id', 'name']
    else:
        print 'You win a prize! Also, you fail.'
        sys.exit((-1))
    result = commands.execute()
    if (__name__ == '__main__'):
        ops.data.script_export(result)
    if (__name__ == '__main__'):
        for i in xrange(len(result.command)):
            if (result.command[i].id == int(dsz.script.Env['script_command_id'])):
                del result.command[i]
                break
    pprint(result.command, header=header, dictorder=fields)
    del flags
    return True
Esempio n. 3
0
def get_parser():
    parser = ArgumentParser(
        version='1.0.0',
        description=
        'usb_monitor.py should be run in the background.  It runs the Drives command at a given interval (default = 300) and monitors if removable media is plugged in or removed.  It will run until killed.'
    )
    group_types = parser.add_argument_group('usb_monitor.py Arguments')
    group_types.add_argument(
        '--interval',
        dest='interval',
        type=int,
        action='store',
        nargs=1,
        help=
        'The interval in SECONDS at which to run the Drives command.  Default = 300'
    )
    return parser
Esempio n. 4
0
def main():
    assert is_forking(sys.argv), "This is only called as the bootstrapper for a child script process"
    
    # This is where we'll do the hackery
    # we'll have to get ops.parseargs integrated into the core as well... for now this'll do.
    # it's just like Python's ArgumentParser (in fact, it's a very tiny sub class), but enables consistency
    # with the DSZ interface while providing the same API and features.
    from ops.parseargs import ArgumentParser
    
    parser = ArgumentParser()
    parser.add_argument('--pipe', dest='pipe', type=int, required=True, help='Name of LP environment variable used to pass pickled data structures.')
    parser.add_argument('--multiprocessingfork', dest='multiproc', action='store_true', default=False, help='Used to flag and detect forks for internal logic purposes.')
    
    options = parser.parse_args()
    
    fd = msvcrt.open_osfhandle(options.pipe, os.O_RDONLY)
    from_parent = os.fdopen(fd, 'rb')
    
    process.current_process()._inheriting = True
    preparation_data = load(from_parent)
    prepare(preparation_data)
    self = load(from_parent)
    process.current_process()._inheriting = False
    
    from_parent.close()
    
    if self._bootstrap() != 0:
        sys.exit()
Esempio n. 5
0
 def scansweep_argparser(self):
     parser = ArgumentParser(version=self.toolversion, description='scansweep does automated scanning through DSZ')
     group_types = parser.add_argument_group('Type flags', 'These flags determine what job types scansweep executes')
     group_types.add_argument('--type', action='store', dest='type', nargs='+', help='Type of scan to conduct, or a queue file containing line seperated (job ip,ip,ip,...) entries')
     group_types.add_argument('--escalate', action='store', dest='escalate', nargs='*', help='Escalate when a arp/ping is found, [rule] replaces this and can be a list of rules or a file')
     group_types.add_argument('--monitor', action='store', dest='monitor', nargs='+', help='Type of monitors to parse, then apply escalation rules, if there are any defined.')
     group_target = parser.add_argument_group('Target input flags', 'These flags determine what targets scansweep executes against')
     group_target.add_argument('--target', action='store', dest='target', nargs='+', metavar='ip,ip-ip,ip/net,ip/netmask,file,host', help='Specification of targets to scan')
     group_target.add_argument('--exclude', action='store', dest='exclude', nargs='+', metavar='ip,ip-ip,ip/net,ip/netmask,file,host', help='Specification of targets NOT to scan')
     group_target.add_argument('--cidroverride', action='store_true', dest='cidroverride', default=False, help='Override the safety restriction of maximum of 255 hosts')
     group_target.add_argument('--internaloverride', action='store_true', dest='internaloverride', default=False, help='Override the safety restriction for monitor tasking, which by default disallows escalating outside our current subnet')
     group_time = parser.add_argument_group('Timing flags', 'These flags adjust how fast or slow scansweep executes')
     group_time.add_argument('--period', action='store', dest='period', default='15s-45s', type=ops.timehelper.parse_interval_string, metavar='Xs-Xm', help='Period at which to run the command (ex. 30s 10-20m) (default: 15s-45s)')
     group_time.add_argument('--maxtime', action='store', dest='maxtime', default='4h', type=ops.timehelper.parse_interval_string, metavar='Xh', help='Maximum time for the command to run (ex. 30s 10-20m) (default: 4h)')
     group_time.add_argument('--nowait', action='store_true', dest='nowait', default=False, help='Toggles counting since beginning of last scan rather then the end of last scan')
     group_time.add_argument('--timeout', action='store', dest='timeout', type=int, metavar='XX', help='Sets the timeout in seconds to pass to a command (used in ping, banner, rpctouch, smbtouch, rpc2)')
     group_time.add_argument('--override', action='store_true', dest='override', default=False, help='Override the safety restriction of 15s minimum scan range on ping and netbios')
     group_database = parser.add_argument_group('Database flags', 'These advanced flags allow you to work with the database')
     group_database.add_argument('--database', action='store', dest='database', choices=['sessions', 'jobs', 'results', 'dump', 'reset', 'kill', 'rules', 'excludes', 'create', 'reescalate'], help='Allows dumping of database info')
     group_database.add_argument('--session', action='store', dest='session', metavar='scansweep_YYYY_MM_DD_HHhMMmSSs.XXX', help='Allows you to re-use an old incomplete scan or to "join" another scan')
     group_database.add_argument('--update', action='store', dest='update', metavar='updatefile.txt', help='Allows updating a currently running session by adding/removing jobs and rules')
     group_misc = parser.add_argument_group('Misc flags', 'Flags that have no home')
     group_misc.add_argument('--verbose', action='store_true', dest='verbose', default=False, help='Enables output of the commands run to the screen')
     return parser
Esempio n. 6
0
 def scansweep_argparser(self):
     parser = ArgumentParser(version=self.toolversion, description='scansweep does automated scanning through DSZ')
     group_types = parser.add_argument_group('Type flags', 'These flags determine what job types scansweep executes')
     group_types.add_argument('--type', action='store', dest='type', nargs='+', help='Type of scan to conduct, or a queue file containing line seperated (job ip,ip,ip,...) entries')
     group_types.add_argument('--escalate', action='store', dest='escalate', nargs='*', help='Escalate when a arp/ping is found, [rule] replaces this and can be a list of rules or a file')
     group_types.add_argument('--monitor', action='store', dest='monitor', nargs='+', help='Type of monitors to parse, then apply escalation rules, if there are any defined.')
     group_target = parser.add_argument_group('Target input flags', 'These flags determine what targets scansweep executes against')
     group_target.add_argument('--target', action='store', dest='target', nargs='+', metavar='ip,ip-ip,ip/net,ip/netmask,file,host', help='Specification of targets to scan')
     group_target.add_argument('--exclude', action='store', dest='exclude', nargs='+', metavar='ip,ip-ip,ip/net,ip/netmask,file,host', help='Specification of targets NOT to scan')
     group_target.add_argument('--cidroverride', action='store_true', dest='cidroverride', default=False, help='Override the safety restriction of maximum of 255 hosts')
     group_target.add_argument('--internaloverride', action='store_true', dest='internaloverride', default=False, help='Override the safety restriction for monitor tasking, which by default disallows escalating outside our current subnet')
     group_time = parser.add_argument_group('Timing flags', 'These flags adjust how fast or slow scansweep executes')
     group_time.add_argument('--period', action='store', dest='period', default='15s-45s', type=ops.timehelper.parse_interval_string, metavar='Xs-Xm', help='Period at which to run the command (ex. 30s 10-20m) (default: 15s-45s)')
     group_time.add_argument('--maxtime', action='store', dest='maxtime', default='4h', type=ops.timehelper.parse_interval_string, metavar='Xh', help='Maximum time for the command to run (ex. 30s 10-20m) (default: 4h)')
     group_time.add_argument('--nowait', action='store_true', dest='nowait', default=False, help='Toggles counting since beginning of last scan rather then the end of last scan')
     group_time.add_argument('--timeout', action='store', dest='timeout', type=int, metavar='XX', help='Sets the timeout in seconds to pass to a command (used in ping, banner, rpctouch, smbtouch, rpc2)')
     group_time.add_argument('--override', action='store_true', dest='override', default=False, help='Override the safety restriction of 15s minimum scan range on ping and netbios')
     group_database = parser.add_argument_group('Database flags', 'These advanced flags allow you to work with the database')
     group_database.add_argument('--database', action='store', dest='database', choices=['sessions', 'jobs', 'results', 'dump', 'reset', 'kill', 'rules', 'excludes', 'create', 'reescalate'], help='Allows dumping of database info')
     group_database.add_argument('--session', action='store', dest='session', metavar='scansweep_YYYY_MM_DD_HHhMMmSSs.XXX', help='Allows you to re-use an old incomplete scan or to "join" another scan')
     group_database.add_argument('--update', action='store', dest='update', metavar='updatefile.txt', help='Allows updating a currently running session by adding/removing jobs and rules')
     group_misc = parser.add_argument_group('Misc flags', 'Flags that have no home')
     group_misc.add_argument('--verbose', action='store_true', dest='verbose', default=False, help='Enables output of the commands run to the screen')
     return parser
Esempio n. 7
0
def parse_redirect_args(arg_list=None, random=False):
    assert (type(random) == type(False)), 'Random must be a Boolean'
    assert (type(arg_list) == type([])), 'Your arg_list must be a list'
    parser = ArgumentParser()
    group_listentype = parser.add_mutually_exclusive_group(required=True)
    group_listentype.add_argument('--tcp', action='store_const', dest='protocol', const='tcp', help='Use TCP/IP as the redirection protocol')
    group_listentype.add_argument('--udp', action='store_const', dest='protocol', const='udp', help='Use UDP/IP as the redirection protocol')
    group_listenLocation = parser.add_mutually_exclusive_group(required=True)
    if random:
        group_listenLocation.add_argument('--lplisten', action='store', dest='lplisten', nargs='*', default=None, help='Listen for new connections on the LP-side (default bind=0.0.0.0).')
        group_listenLocation.add_argument('--implantlisten', action='store', dest='implantlisten', nargs='*', default=None, help='Listen for new connections on the Implant-side (default bind=0.0.0.0).')
    elif (not random):
        group_listenLocation.add_argument('--lplisten', action='store', dest='lplisten', nargs='+', default=None, help='Listen for new connections on the LP-side (default bind=0.0.0.0).')
        group_listenLocation.add_argument('--implantlisten', action='store', dest='implantlisten', nargs='+', default=None, help='Listen for new connections on the Implant-side (default bind=0.0.0.0).')
    parser.add_argument('--target', action='store', dest='target', required=True, nargs='*', help='The address / port to which data should be forwarded. NOTE: Data is always forwarded to the side opposite where the listening port is.')
    parser.add_argument('--portsharing', action='store', dest='portsharing', nargs=2, default=None, help='For use with FLAV')
    parser.add_argument('--connections', action='store', dest='connections', default=0, type=int, help='Sets the maximum number of concurrent connections allowed.(Default=0 / 0=Unlimited)')
    parser.add_argument('--limitconnections', action='store', dest='limitconnections', nargs=2, default=None, help='Limit connections to listen address to a specified IP range.')
    parser.add_argument('--sendnotify', action='store_true', dest='sendnotify', default=False, help='Send notification of target connection success / failure to connecting sockets.')
    parser.add_argument('--packetsize', action='store', dest='packetsize', default=8192, type=int, help='Sets the maximum size (in bytes) for recv/send calls.  This is of particular interest for datagram (ie, UDP) redirection (default=8192).')
    options = parser.parse_args(arg_list)
    if (options.portsharing is not None):
        assert util.ip.validate_port(options.portsharing[0]), 'clientSrcPort in portsharing must be a valid port'
        assert util.ip.validate(options.portsharing[1]), 'clientSrcAddr in portsharing must be a valid IP address'
    if (options.limitconnections is not None):
        assert util.ip.validate(options.limitconnections[0]), 'addr in limitconnections must be a valid IP address'
        assert util.ip.validate(options.limitconnections[1]), 'mask in limitconnections must be a valid IP address'
    if random:
        assert (len(options.target) in range(0, 5)), 'Target must be a list with 0-4 elements when using random.'
        for item in options.target:
            assert (util.ip.validate(item) or util.ip.validate_port(item)), 'Target items must be either a valid IP address or valid port when using random.'
    elif (not random):
        assert (len(options.target) in range(2, 5)), 'Target must be a list with 2-4 elements when not using random.'
        assert util.ip.validate(options.target[0]), 'addr in target must be a valid IP address'
        assert util.ip.validate_port(options.target[1]), 'destPort in target must be a valid IP address'
        if (len(options.target) == 3):
            assert util.ip.validate(options.target[2]), 'srcAddr in target must be a valid IP address'
        if (len(options.target) == 4):
            assert util.ip.validate_port(options.target[3]), 'srcPort in target must be a valid IP address'
    return options
Esempio n. 8
0
def main():
    parser = ArgumentParser(
        prog='paperfind',
        description=
        '\nProvides grep-like functionality for the \'handles\' command.\n\nRelative paths will (probably) never match. Use absolute or partial\npaths as though you are grepping. For full featured pattern matching,\nconsider the --regex option.\n\nIf the pattern you\'re searching for starts with a "-" character, place\na "-" by itself before beginning the pattern.\n\n e.g. %(prog)s -any - -filethatstartswithadash\n  or  %(prog)s - -filethatstartswithadash -any\n'
    )
    parser.add_argument('pattern', help='Pattern or regular expression.')
    parser.add_argument(
        '--regex',
        dest='regex',
        action='store_true',
        help=
        'Treat the input pattern as a user-supplied regular expression instead of a simple string pattern.'
    )
    parser.add_argument(
        '--any',
        dest='any',
        action='store_true',
        default=False,
        help='Search all handle types instead of only file handles.')
    parser.add_argument(
        '--data',
        dest='data_age',
        metavar='AGE',
        type=delta,
        default=datetime.timedelta(minutes=10),
        help=
        'How old cached data can be before re-querying target. Use #d#h#m#s format. (Default 10m if unspecified).'
    )
    handles_group = parser.add_argument_group(
        title='handles',
        description='Options that control how the handles command is run.')
    handles_group.add_argument(
        '--id',
        dest='id',
        type=int10or16,
        help='Limit returned handle search to a particular process ID.')
    handles_group.add_argument(
        '--all',
        dest='all',
        action='store_true',
        default=False,
        help=
        'Search all available handle information. (Not recommended with this script; provides no benefit)'
    )
    handles_group.add_argument(
        '--memory',
        dest='memory',
        type=int10or16,
        help=
        'Number of bytes to use for open handle list (defaults to handles default).'
    )
    options = parser.parse_args()
    if options.regex:
        ops.info(('Searching using regex: %s' % options.pattern))
    else:
        ops.info(('Searching for "%s"...' % options.pattern))
    found = ops.system.handles.grep_handles(pattern=ntpath.normpath(
        options.pattern),
                                            id=options.id,
                                            all=options.all,
                                            memory=options.memory,
                                            regex=options.regex,
                                            any=options.any,
                                            maxage=options.data_age)
    if (int is type(found)):
        ops.error(
            ('Error running handles command. Check logs for command ID %d.' %
             found))
        sys.exit((-1))
    elif (found is None):
        ops.error(
            'Error running handles; command may not have been attempted.')
        sys.exit((-1))
    elif (not found):
        ops.warn('No matches.')
        sys.exit((-1))
    elif options.any:
        pprint(found,
               header=['PID', 'Handle', 'Type', 'Full Path'],
               dictorder=['process', 'handle', 'type', 'name'])
    else:
        pprint(found,
               header=['PID', 'Handle', 'Full Path'],
               dictorder=['process', 'handle', 'name'])
Esempio n. 9
0
def parse_program_arguments(arguments):
    parser = ArgumentParser(prog='check_soti',
                            description='performs some checks for SOTI')
    parser.add_argument('-c',
                        '--containers',
                        dest='containers',
                        help='look for SOTI containers',
                        action='store_true')
    parser.add_argument('-g',
                        '--get8k',
                        dest='get8k',
                        help='gets the first 8k bytes from target boot drive',
                        action='store_true')
    parser.add_argument('-l',
                        '--localhash',
                        dest='localhash',
                        help='locally hashes first 8k bytes from target',
                        action='store_true')
    parser.add_argument('-q',
                        '--quiet',
                        dest='quiet',
                        help='one line output, intended for survey',
                        action='store_true')
    options = parser.parse_args()
    if (options.localhash and (options.get8k is not True)):
        if options.containers:
            containers()
        localhash(None)
        printlog(options.quiet)
        return
    if operator.xor(options.containers, options.get8k):
        if options.containers:
            containers()
        if options.get8k:
            get8k()
            if options.localhash:
                log('  not running -l since -g ran', '-g ran -> no -l')
    else:
        containers()
        get8k()
        if options.localhash:
            log('  not running -l since -g ran', '-g ran -> no -l')
    printlog(options.quiet)
def main(args):
    parser = ArgumentParser()
    group_target = parser.add_argument_group(
        'Target', 'Options that describe the event log to query')
    group_target.add_argument(
        '--log',
        action='store',
        dest='log',
        default='security',
        help='The event log to search. Default = Security')
    group_target.add_argument('--target',
                              action='store',
                              dest='target',
                              help='Remote machine to query')
    group_limiters = parser.add_argument_group(
        'Limiters', 'Options that limit the range over which we are searching')
    group_limiters.add_argument(
        '--num',
        action='store',
        dest='num',
        default=1000,
        type=int,
        help=
        "The number of entries to parse. A value of zero will result in all entries being parsed. Parsing will cease once the first 1000 records are found unless the 'max' keyword is used."
    )
    group_limiters.add_argument(
        '--max',
        action='store',
        dest='max',
        default=100,
        type=int,
        help=
        'Maximum entries returned from the target. Default=1000. A value of 0 will result in all possible entries returned. It is recommended that a value of 0 not be used due to the fact that a large database could result in an excessive number of entries being parsed and cause a slowdown in the speed and memory usage of the LP.'
    )
    group_limiters.add_argument(
        '--startrecord',
        action='store',
        dest='startrecord',
        help=
        'Record with which to begin filtering. Default = Most recent record.')
    group_filters = parser.add_argument_group(
        'Filters', 'Options that describe what we are looking for')
    group_filters.add_argument(
        '--id',
        action='store',
        dest='id',
        help='The Event ID on which to filter. Default = No filtering.')
    group_filters.add_argument(
        '--logons',
        action='store_true',
        dest='logons',
        default=False,
        help='Eventlogfilter for common authentication logs')
    group_filters.add_argument(
        '--string',
        action='store',
        dest='string_opt',
        help='String in entry on which to filter.  Default = No filtering.')
    group_filters.add_argument(
        '--sid',
        action='store',
        dest='sid',
        help='Username on which to filter.  Default = No filtering.')
    group_filters.add_argument('--xpath',
                               action='store',
                               dest='xpath',
                               help='XPath expression for search.')
    group_output = parser.add_argument_group('Output',
                                             'Options that change the output')
    group_output.add_argument(
        '--summary',
        action='store_true',
        dest='summary',
        default=False,
        help='Display a list of the strings associated with each event record')
    group_monitor = parser.add_argument_group(
        'Monitor', 'Options that deal with monitoring')
    group_monitor.add_argument(
        '--monitor',
        action='store_true',
        dest='monitor',
        default=False,
        help=
        'Execute the eventlogfilter command at a given interval and display any new results'
    )
    group_monitor.add_argument('--interval',
                               action='store',
                               dest='interval',
                               default='5m',
                               type=ops.timehelper.get_seconds_from_age,
                               help='Interval at which to monitor')
    options = parser.parse_args()
    last_record = 0
    newest_record = 0
    querymax = options.max
    querynum = options.num
    startrecord = options.startrecord
    while True:
        if options.monitor:
            newest_record = getmostrecentrecordnum(eventlog=options.log)
            if (not (last_record == 0)):
                querynum = (newest_record - last_record)
                startrecord = newest_record
            querymax = querynum
            if (querymax == 0):
                dsz.ui.Echo(('[%s] No new records' % ops.timestamp()),
                            dsz.WARNING)
                dsz.Sleep((options.interval * 1000))
                continue
        dsz.ui.Echo(('=' * 80), dsz.GOOD)
        eventlogtime(log=options.log,
                     max=querymax,
                     num=querynum,
                     id_list=options.id,
                     sid=options.sid,
                     string_opt_list=options.string_opt,
                     startrecord=startrecord,
                     xpath=options.xpath,
                     target=options.target,
                     summary=options.summary,
                     logons=options.logons)
        last_record = newest_record
        if (not options.monitor):
            return
        dsz.Sleep((options.interval * 1000))
Esempio n. 11
0
def main():
    parser = ArgumentParser()
    parser.add_argument('--maxage', action='store', dest='maxage', default='1h', type=ops.timehelper.get_seconds_from_age, help='Default age is 1h. Accepts seconds, minutes, hours, days, weeks, years. (Ex: 2h10m50s)')
    parser.add_argument('--nominimal', action='store_false', dest='minimal', default=True, help='Do not use -minimal when running the drivers -list (dangerous)')
    parser.add_argument('--nohashes', action='store_false', dest='grabhashes', default=True, help='Do not run the hashing functions to get our wonderful hashes')
    parser.add_argument('--showall', action='store_true', dest='showall', default=False, help='Show all drivers. By default, ISO_HASH items are excluded')
    parser.add_argument('--autofreshscan', action='store', dest='autofreshscan', default=False, type=int, help='Automatically freshscan UNIDENTIFIED drivers. Requires userid')
    parser.add_argument('--nofreshscan', action='store_false', dest='dofreshscan', default=True, help='Disable the freshscan prompt for UNIDENTIFIED drivers at the end of the script')
    parser.add_argument('--verbose', action='store_false', dest='quiet', default=True, help='Enable helpful output messages that state the progress of the script')
    parser.add_argument('--wait', action='store_true', dest='wait', default=False, help="Instead of running hashhunter, run the dir's from within the script")
    parser.add_argument('--grdo', action='store_true', dest='grdo', default=False, help='Run GRDO_FILESCANNER to get some extra information')
    parser.add_argument('--gath', action='store_true', dest='gath', default=False, help='Use GANGSTERTHIEF where we can (for grdo_filescanner and for freshscan)')
    options = parser.parse_args()
    if (options.autofreshscan is not False):
        re_out = re.search('^[0-9]{5}$', options.autofreshscan)
        if (re_out is None):
            dsz.ui.Echo('Invalid user id for autofreshscan, must be five digits', dsz.ERROR)
            return False
    if ((options.autofreshscan is not False) and (dofreshscan == False)):
        dsz.ui.Echo('You cannot enable autofreshscan and disable freshscan', dsz.ERROR)
        return False
    driverlist(wait=options.wait, quiet=options.quiet, maxage=options.maxage, minimal=options.minimal, grabhashes=options.grabhashes, showall=options.showall, autofreshscan=options.autofreshscan, dofreshscan=options.dofreshscan, gath=options.gath, grdo=options.grdo)
Esempio n. 12
0
def main():
    usage = 'Usage: python windows\\vget.py -args "-F [Full Path to File] -p [path to file] -m [mask] Optional: -t [bytes] -hex -nosend"\n\nOptions:\n-t [bytes] : grab last x bytes of file (tail)\n-nosend : move file to nosend dir\n-hex : open file in hex editor\n\nEx. python windows\\vget.py -args "-m connections.log -p C:\\Documents and Settings\\user\\logs -t 10000 -nosend"\nEx. python windows\\vget.py -args "-F C:\\Documents and Settings\\user\\logs\\connections.log -t 10000 -nosend -hex"'
    parser = ArgumentParser(usage=usage)
    parser.add_argument('-p', dest='path', nargs='+', action='store', default=False)
    parser.add_argument('-m', dest='mask', action='store', default=False)
    parser.add_argument('-F', dest='full_path', nargs='+', action='store', default=False)
    parser.add_argument('-t', dest='tail', type=int, action='store', default=False)
    parser.add_argument('--nosend', dest='nosend', action='store_true', default=False)
    parser.add_argument('--hex', dest='hex', action='store_true', default=False)
    options = parser.parse_args()
    if (len(sys.argv) == 1):
        print usage
        sys.exit(0)
    if (options.full_path == options.mask == False):
        ops.warn('No mask or full path specified! Need one or the other to execute.')
        sys.exit(0)
    mask = options.mask
    tail = options.tail
    nosend = options.nosend
    hex = options.hex
    getCmd = ops.cmd.getDszCommand('get')
    if options.full_path:
        full_path = ' '.join(options.full_path)
        getCmd.arglist.append(('"%s"' % full_path))
    else:
        if options.path:
            path = ' '.join(options.path)
            getCmd.optdict['path'] = ('"%s"' % path)
        getCmd.optdict['mask'] = mask
    if tail:
        getCmd.arglist.append(('-tail %s' % tail))
    getCmd.dszquiet = False
    getCmd.execute()
    getResult = getCmd.result
    id = getResult.cmdid
    for n in getResult.filestop:
        if (n.successful != 1):
            ops.error(('Get Failed; see cmdid %s or above output for more info' % id))
            sys.exit(0)
    localName = ''
    for n in getResult.filelocalname:
        localName = n.localname
    fullLocalPath = os.path.join(dsz.env.Get('_LOGPATH'), 'GetFiles', localName)
    if (nosend == True):
        movePath = os.path.join(dsz.env.Get('_LOGPATH'), 'GetFiles\\NoSend', localName)
        moveCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c move %s %s"' % (fullLocalPath, movePath)))
        moveCmd.execute()
        fullLocalPath = movePath
        ops.info(('File moved to %s' % movePath))
    if (hex == False):
        ops.info('Opening file with notepad++')
        showCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c C:\\progra~1\\notepad++\\notepad++.exe %s"' % fullLocalPath))
    else:
        ops.info('Opening file with hex editor')
        showCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c C:\\Progra~1\\BreakP~1\\HexWor~1.2\\hworks32.exe %s"' % fullLocalPath))
    showCmd.execute()
Esempio n. 13
0
def parse_program_arguments(arguments):
    parser = ArgumentParser(
        prog='ripper',
        description='collects files from predetermined locations')
    parser.add_argument('-l',
                        '--list',
                        dest='list',
                        help='list available plugins',
                        action='store_true')
    parser.add_argument('-p',
                        '--plugins',
                        dest='plugins',
                        help='plugins to run, comma separated')
    parser.add_argument('-m',
                        '--maxsize',
                        dest='maxsize',
                        default=(256 * 1024),
                        help='max file size to automatically get, in bytes')
    parser.add_argument('-u',
                        '--users',
                        dest='users',
                        help='users to collect against, comma separated')
    options = parser.parse_args()
    if ((options.plugins == None) and (options.list != True)):
        parser.print_help()
        print ''
        example()
        print ''
        listplugins()
        return
    if (options.list == True):
        listplugins()
        return
    if options.plugins:
        global __PLUGINS
        for plugin in options.plugins.split(','):
            __PLUGINS.append(plugin)
    if options.maxsize:
        global __MAXSIZE
        __MAXSIZE = options.maxsize
    if options.users:
        global __COLLECTUSERS
        for user in options.users.split(','):
            __COLLECTUSERS.append(user)
Esempio n. 14
0
def main():
    parser = ArgumentParser()
    parser.add_argument(
        '--maxage',
        action='store',
        dest='maxage',
        default='1h',
        type=ops.timehelper.get_seconds_from_age,
        help=
        'Default age is 1h. Accepts seconds, minutes, hours, days, weeks, years. (Ex: 2h10m50s)'
    )
    parser.add_argument(
        '--nominimal',
        action='store_false',
        dest='minimal',
        default=True,
        help='Do not use -minimal when running the drivers -list (dangerous)')
    parser.add_argument(
        '--nohashes',
        action='store_false',
        dest='grabhashes',
        default=True,
        help='Do not run the hashing functions to get our wonderful hashes')
    parser.add_argument(
        '--showall',
        action='store_true',
        dest='showall',
        default=False,
        help='Show all drivers. By default, ISO_HASH items are excluded')
    parser.add_argument(
        '--autofreshscan',
        action='store',
        dest='autofreshscan',
        default=False,
        type=int,
        help='Automatically freshscan UNIDENTIFIED drivers. Requires userid')
    parser.add_argument(
        '--nofreshscan',
        action='store_false',
        dest='dofreshscan',
        default=True,
        help=
        'Disable the freshscan prompt for UNIDENTIFIED drivers at the end of the script'
    )
    parser.add_argument(
        '--verbose',
        action='store_false',
        dest='quiet',
        default=True,
        help=
        'Enable helpful output messages that state the progress of the script')
    parser.add_argument(
        '--wait',
        action='store_true',
        dest='wait',
        default=False,
        help=
        "Instead of running hashhunter, run the dir's from within the script")
    parser.add_argument(
        '--grdo',
        action='store_true',
        dest='grdo',
        default=False,
        help='Run GRDO_FILESCANNER to get some extra information')
    parser.add_argument(
        '--gath',
        action='store_true',
        dest='gath',
        default=False,
        help=
        'Use GANGSTERTHIEF where we can (for grdo_filescanner and for freshscan)'
    )
    options = parser.parse_args()
    if (options.autofreshscan is not False):
        re_out = re.search('^[0-9]{5}$', options.autofreshscan)
        if (re_out is None):
            dsz.ui.Echo(
                'Invalid user id for autofreshscan, must be five digits',
                dsz.ERROR)
            return False
    if ((options.autofreshscan is not False) and (dofreshscan == False)):
        dsz.ui.Echo('You cannot enable autofreshscan and disable freshscan',
                    dsz.ERROR)
        return False
    driverlist(wait=options.wait,
               quiet=options.quiet,
               maxage=options.maxage,
               minimal=options.minimal,
               grabhashes=options.grabhashes,
               showall=options.showall,
               autofreshscan=options.autofreshscan,
               dofreshscan=options.dofreshscan,
               gath=options.gath,
               grdo=options.grdo)
Esempio n. 15
0
def main(args=[]):
    flags = dsz.control.Method()
    if ((__name__ == '__main__') and
        (dsz.script.Env['script_parent_echo_disabled'].lower() == 'true')):
        dsz.control.quiet.On()
    parser = ArgumentParser(prog='prettych', add_help=False)
    cmdopts = parser.add_argument_group(title='commands options')
    cmdopts.add_argument('--all',
                         action='store_true',
                         help='Also display finished commands')
    cmdopts.add_argument('--any',
                         action='store_true',
                         help='Display commands from any address')
    locationgrp = cmdopts.add_mutually_exclusive_group()
    locationgrp.add_argument('--local',
                             dest='location',
                             default=LOCATION_LOCAL,
                             const=LOCATION_LOCAL,
                             action='store_const',
                             help='List local commands (default)')
    locationgrp.add_argument('--remote',
                             dest='location',
                             const=LOCATION_REMOTE,
                             action='store_const',
                             help='List remote commands')
    cmdopts.add_argument(
        '--astyped',
        action='store_true',
        help='Show commands as typed (rather than displaying expanded aliases)'
    )
    cmdopts.add_argument('--verbose',
                         action='store_true',
                         help='Show additional command information')
    parser.add_argument(
        '--echo',
        dest='dszquiet',
        default=True,
        action='store_false',
        help=
        'Echo out the raw DSZ commands output in addition to pretty printing.')
    options = parser.parse_args(args)
    commands = ops.cmd.getDszCommand('commands',
                                     prefixes=['stopaliasing'],
                                     all=options.all,
                                     any=options.any,
                                     astyped=options.astyped,
                                     verbose=options.verbose,
                                     dszquiet=options.dszquiet)
    if (options.location == LOCATION_LOCAL):
        header = []
        fields = []
        if options.all:
            header.append('Status')
            fields.append('status')
        header.extend(['ID', 'Target'])
        fields.extend(['id', 'targetaddress'])
        if (options.astyped or options.verbose):
            header.append('Command (as-typed)')
            fields.append('commandastyped')
        if ((not options.astyped) or options.verbose):
            header.append('Full Command')
            fields.append('fullcommand')
        header.extend(['Sent', 'Received'])
        fields.extend(['bytessent', 'bytesreceived'])
    elif (options.location == LOCATION_REMOTE):
        commands.remote = True
        header = ['ID', 'Command']
        fields = ['id', 'name']
    else:
        print 'You win a prize! Also, you fail.'
        sys.exit((-1))
    result = commands.execute()
    if (__name__ == '__main__'):
        ops.data.script_export(result)
    if (__name__ == '__main__'):
        for i in xrange(len(result.command)):
            if (result.command[i].id == int(
                    dsz.script.Env['script_command_id'])):
                del result.command[i]
                break
    pprint(result.command, header=header, dictorder=fields)
    del flags
    return True
Esempio n. 16
0
def main():
    parser = ArgumentParser(prog='survey')
    actiongrp = parser.add_mutually_exclusive_group(required=True)
    actiongrp.add_argument(
        '--run',
        dest='run',
        const=ops.survey.DEFAULT_CONFIG,
        nargs='?',
        metavar='SURVEY',
        help='Run specified survey. Uses default if none specified. (%(const)s)'
    )
    actiongrp.add_argument('--modify',
                           dest='modify',
                           action='store_true',
                           default=False,
                           help='Manipulate the settings for default survey.')
    parser.add_argument('--sections',
                        dest='sections',
                        default=ops.survey.DEFAULT_SECTIONS,
                        metavar='SECTION',
                        nargs='+',
                        help='Sections for --run or --override.')
    modgrp = parser.add_argument_group(
        title='--modify options',
        description='These options are only used with the --modify option.')
    modgrp.add_argument('--override',
                        dest='override',
                        help='Change the default survey file for all targets.')
    modgrp.add_argument(
        '--exclude',
        dest='exclude',
        nargs='+',
        metavar='GROUP',
        help=
        'Adds the specified groups to the list of tasks to exclude when running survey configurations.'
    )
    modgrp.add_argument(
        '--include',
        dest='include',
        nargs='+',
        metavar='GROUP',
        help=
        'Removes the specified groups from the list of tasks to exclude when running survey configurations.'
    )
    modgrp.add_argument('--exclusions',
                        dest='printex',
                        action='store_true',
                        default=False,
                        help='Print out a list of excluded survey groups.')
    parser.add_argument(
        '--quiet',
        dest='quiet',
        action='store_true',
        default=False,
        help=
        'Suppress some framework messages, including the running commands list at the end.'
    )
    options = parser.parse_args()
    if ((not options.modify) and
        ((options.override is not None) or (options.exclude is not None) or
         (options.include is not None) or options.printex)):
        parser.error('-modify is required for these options')
    if options.modify:
        if options.override:
            ops.survey.override(options.override, options.sections)
        if options.exclude:
            if ops.survey.exclude(options.exclude):
                ops.info(('%s added to exclusion list.' % options.exclude))
                ops.survey.print_exclusion_list()
            else:
                ops.info(('%s already in exclusion list.' % options.exclude))
        if options.include:
            if ops.survey.include(options.include):
                ops.info(('%s removed from exclusion list.' % options.include))
                ops.survey.print_exclusion_list()
            else:
                ops.info(('%s not in exclusion list.' % options.include))
        if options.printex:
            ops.survey.print_exclusion_list()
    else:
        execute(options.run, options.sections, options.quiet)
Esempio n. 17
0
            return False
        diffs = _dodiff(dirres, os.path.join(os.path.join(ops.TARGET_TEMP, 'hour.txt')))
        _recordstate(dirres, os.path.join(os.path.join(ops.TARGET_TEMP, 'hour.txt')), restart)
    diffnames = []
    for modfile in diffs:
        prettyfiletime = modfile.filetimes.modified.time[0:19].replace('T', ' ')
        if modfile.attributes.directory:
            diffnames.append({'Path': modfile.dszparent.path, 'Name': modfile.name, 'Size': '<DIR>', 'Modtime': prettyfiletime})
        else:
            diffnames.append({'Path': modfile.dszparent.path, 'Name': modfile.name, 'Size': modfile.size, 'Modtime': prettyfiletime})
    if (len(diffnames) > 0):
        ops.pprint.pprint(diffnames, header=['Modtime', 'Size', 'Path', 'Name'], dictorder=['Modtime', 'Size', 'Path', 'Name'])
    else:
        ops.info('No changes detected')
if (__name__ == '__main__'):
    parser = ArgumentParser()
    path_group = parser.add_mutually_exclusive_group()
    time_group = parser.add_mutually_exclusive_group()
    age_group = parser.add_mutually_exclusive_group()
    parser.add_argument('--mask', action='store', dest='mask', default='*', help='Mask to use for the dir command, default is *')
    path_group.add_argument('--path', action='store', dest='path', default='*', help='Path to use for the dir command, default is *')
    age_group.add_argument('--age', action='store', dest='age', default='1h', help='Path to use for the dir command, default is 1h, may be ([#y][#w][#d][#h][#m][#s])')
    parser.add_argument('--recursive', action='store_true', dest='recursive', default=False, help='If present, dir will be done recursively, otherwise will not be recursive')
    parser.add_argument('--restart', action='store_true', dest='restart', default=False, help='If present, will not compare with previous results and will start a new baseline')
    parser.add_argument('--safe', action='store_true', dest='safe', default=False, help="Will run times and then craft a before/after parameter, rather then use dir's age parameter")
    path_group.add_argument('--sysdrive', action='store_true', dest='sysdrive', default=False, help='Will only run the dir against the system drive')
    parser.add_argument('--nodiff', action='store_true', dest='nodiff', default=False, help='Do not run a diffhour, only a normal hour')
    parser.add_argument('--noquiet', action='store_true', dest='noquiet', default=False, help='Display the results of the dir to screen')
    time_group.add_argument('--fromtime', action='store', dest='fromtime', metavar='"YYYY-MM-DD [hh:mm:ss]"', default=None, help='Date from which to calculate the age. Default is to calculate normally.')
    time_group.add_argument('--centeredtime', action='store', dest='centeredtime', metavar='"YYYY-MM-DD [hh:mm:ss]"', default=None, help='Date from which to calculate the age in both directions. Default is to calculate normally.')
    age_group.add_argument('--fromstart', action='store_true', dest='fromstart', default=False, help="Calculate the -after time since the first 'time' command run on this cpaddr")
Esempio n. 18
0
def parse_program_arguments(arguments):
    parser = ArgumentParser(prog='ripper', description='collects files from predetermined locations')
    parser.add_argument('-l', '--list', dest='list', help='list available plugins', action='store_true')
    parser.add_argument('-p', '--plugins', dest='plugins', help='plugins to run, comma separated')
    parser.add_argument('-m', '--maxsize', dest='maxsize', default=(256 * 1024), help='max file size to automatically get, in bytes')
    parser.add_argument('-u', '--users', dest='users', help='users to collect against, comma separated')
    options = parser.parse_args()
    if ((options.plugins == None) and (options.list != True)):
        parser.print_help()
        print ''
        example()
        print ''
        listplugins()
        return
    if (options.list == True):
        listplugins()
        return
    if options.plugins:
        global __PLUGINS
        for plugin in options.plugins.split(','):
            __PLUGINS.append(plugin)
    if options.maxsize:
        global __MAXSIZE
        __MAXSIZE = options.maxsize
    if options.users:
        global __COLLECTUSERS
        for user in options.users.split(','):
            __COLLECTUSERS.append(user)
Esempio n. 19
0
def main():
    usage = 'Usage: python windows\\vget.py -args "-F [Full Path to File] -p [path to file] -m [mask] Optional: -t [bytes] -hex -nosend"\n\nOptions:\n-t [bytes] : grab last x bytes of file (tail)\n-nosend : move file to nosend dir\n-hex : open file in hex editor\n\nEx. python windows\\vget.py -args "-m connections.log -p C:\\Documents and Settings\\user\\logs -t 10000 -nosend"\nEx. python windows\\vget.py -args "-F C:\\Documents and Settings\\user\\logs\\connections.log -t 10000 -nosend -hex"'
    parser = ArgumentParser(usage=usage)
    parser.add_argument('-p', dest='path', nargs='+', action='store', default=False)
    parser.add_argument('-m', dest='mask', action='store', default=False)
    parser.add_argument('-F', dest='full_path', nargs='+', action='store', default=False)
    parser.add_argument('-t', dest='tail', type=int, action='store', default=False)
    parser.add_argument('--nosend', dest='nosend', action='store_true', default=False)
    parser.add_argument('--hex', dest='hex', action='store_true', default=False)
    options = parser.parse_args()
    if (len(sys.argv) == 1):
        print usage
        sys.exit(0)
    if (options.full_path == options.mask == False):
        ops.warn('No mask or full path specified! Need one or the other to execute.')
        sys.exit(0)
    mask = options.mask
    tail = options.tail
    nosend = options.nosend
    hex = options.hex
    getCmd = ops.cmd.getDszCommand('get')
    if options.full_path:
        full_path = ' '.join(options.full_path)
        getCmd.arglist.append(('"%s"' % full_path))
    else:
        if options.path:
            path = ' '.join(options.path)
            getCmd.optdict['path'] = ('"%s"' % path)
        getCmd.optdict['mask'] = mask
    if tail:
        getCmd.arglist.append(('-tail %s' % tail))
    getCmd.dszquiet = False
    getCmd.execute()
    getResult = getCmd.result
    id = getResult.cmdid
    for n in getResult.filestop:
        if (n.successful != 1):
            ops.error(('Get Failed; see cmdid %s or above output for more info' % id))
            sys.exit(0)
    localName = ''
    for n in getResult.filelocalname:
        localName = n.localname
    fullLocalPath = os.path.join(dsz.env.Get('_LOGPATH'), 'GetFiles', localName)
    if (nosend == True):
        movePath = os.path.join(dsz.env.Get('_LOGPATH'), 'GetFiles\\NoSend', localName)
        moveCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c move %s %s"' % (fullLocalPath, movePath)))
        moveCmd.execute()
        fullLocalPath = movePath
        ops.info(('File moved to %s' % movePath))
    if (hex == False):
        ops.info('Opening file with notepad++')
        showCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c C:\\progra~1\\notepad++\\notepad++.exe %s"' % fullLocalPath))
    else:
        ops.info('Opening file with hex editor')
        showCmd = ops.cmd.getDszCommand(('local run -command "cmd.exe /c C:\\Progra~1\\BreakP~1\\HexWor~1.2\\hworks32.exe %s"' % fullLocalPath))
    showCmd.execute()
Esempio n. 20
0
def get_parser():
    parser = ArgumentParser(version='1.0.0', description='usb_monitor.py should be run in the background.  It runs the Drives command at a given interval (default = 300) and monitors if removable media is plugged in or removed.  It will run until killed.')
    group_types = parser.add_argument_group('usb_monitor.py Arguments')
    group_types.add_argument('--interval', dest='interval', type=int, action='store', nargs=1, help='The interval in SECONDS at which to run the Drives command.  Default = 300')
    return parser