Exemplo n.º 1
0
def main():
    import argparse

    parser = argparse.ArgumentParser(description='Event query example')
    parser.add_argument('-v', '--verbose', action='count', default=0)
    parser.add_argument('--src',
                        default="Security",
                        help='log source to query')
    parser.add_argument('-q', '--query', default="*", help='query string')
    parser.add_argument('-m',
                        '--max_entries',
                        type=int,
                        default=100,
                        help='max element count to retrieve')

    parser.add_argument(
        'smb_url',
        help=
        'Connection string that describes the authentication and target. Example: smb+ntlm-password://TEST\\Administrator:[email protected]'
    )

    args = parser.parse_args()
    print(__banner__)

    if args.verbose >= 1:
        logger.setLevel(logging.DEBUG)

    asyncio.run(
        amain(args.smb_url,
              src=args.src,
              query=args.query,
              max_entries=args.max_entries))
Exemplo n.º 2
0
def main():
    import argparse
    import platform
    import logging
    from asysocks import logger as sockslogger

    parser = argparse.ArgumentParser(description='Zerologon tester')
    parser.add_argument('-v', '--verbose', action='count', default=0)
    parser.add_argument('-e',
                        '--exploit',
                        action='store_true',
                        help='perform the expolit')
    parser.add_argument('dc_ip', help='IP address of the domain controller')
    parser.add_argument(
        'dc_name', help='NETBIOS NAME of the domain controller (without $)')

    args = parser.parse_args()
    if args.verbose >= 1:
        logger.setLevel(logging.DEBUG)

    if args.verbose > 2:
        print('setting deepdebug')
        logger.setLevel(1)  #enabling deep debug
        sockslogger.setLevel(1)
        asyncio.get_event_loop().set_debug(True)
        logging.basicConfig(level=logging.DEBUG)

    asyncio.run(run(args.dc_name, args.dc_ip, args.exploit))
Exemplo n.º 3
0
def main():
	import os
	import argparse
	parser = argparse.ArgumentParser(description='auto collector for MP')
	#parser.add_argument('-v', '--verbose', action='count', default=0, help='Increase verbosity, can be stacked')
	#parser.add_argument('sql', help='SQL connection string in URL format')
	parser.add_argument('-q', '--sqlite_folder_path', default='./workdir', help='A folder to store enumeration results in')
	parser.add_argument('-m', '--multiplexor', default = 'ws://127.0.0.1:9999', help='multiplexor connection string in URL format')
	parser.add_argument('-p', '--parallel_cnt', default = get_cpu_count(), type=int, help='agent count')
	parser.add_argument('-o', '--progress-out-file', default = None, help='Filename to write progress to')
	parser.add_argument('-s', '--start-ui', action='store_true', help='Automatically start jackdaw UI after successful enumeration')

	args = parser.parse_args()

	logging.basicConfig(level=logging.DEBUG)
	msldaplogger.setLevel(logging.INFO)
	smblogger.setLevel(1)
	logging.getLogger('websockets.server').setLevel(logging.ERROR)
	logging.getLogger('websockets.client').setLevel(logging.ERROR)
	logging.getLogger('websockets.protocol').setLevel(logging.ERROR)
	logging.getLogger('aiosmb').setLevel(100)
	logging.getLogger('asysocks').setLevel(100)

	
	mas = MultiplexorAutoStart(args.multiplexor, args.sqlite_folder_path, parallel_cnt=args.parallel_cnt, progress_file_name = args.progress_out_file, start_ui = args.start_ui)
	asyncio.run(mas.run())
Exemplo n.º 4
0
def main():
	import argparse
	import platform
	import logging
	from asysocks import logger as asylogger
	
	parser = argparse.ArgumentParser(description='Interactive SMB client')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	parser.add_argument('-s', '--silent', action='store_true', help='do not print banner')
	parser.add_argument('-n', '--no-interactive', action='store_true')
	parser.add_argument('smb_url', help = 'Connection string that describes the authentication and target. Example: smb+ntlm-password://TEST\\Administrator:[email protected]')
	parser.add_argument('commands', nargs='*')
	
	args = parser.parse_args()
	if args.silent is False:
		print(__banner__)

	if args.verbose >=1:
		logger.setLevel(logging.DEBUG)

	if args.verbose > 2:
		print('setting deepdebug')
		logger.setLevel(1) #enabling deep debug
		sockslogger.setLevel(1)
		asylogger.setLevel(1)
		asyncio.get_event_loop().set_debug(True)
		logging.basicConfig(level=logging.DEBUG)

	asyncio.run(amain(args))
Exemplo n.º 5
0
async def amain():
	import argparse
	import sys

	parser = argparse.ArgumentParser(description='SMB Protocol enumerator. Tells which dialects suported by the remote end')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	parser.add_argument('-w', '--smb-worker-count', type=int, default=100, help='Parallell count')
	parser.add_argument('-t', '--timeout', type=int, default=50, help='Timeout for each connection')
	parser.add_argument('--signing', action='store_true', help='Only check for the singing properties. (faster)')
	parser.add_argument('-s', '--stdin', action='store_true', help='Read targets from stdin')
	parser.add_argument('--json', action='store_true', help='Output in JSON format')
	parser.add_argument('--tsv', action='store_true', help='Output in TSV format. (TAB Separated Values)')
	parser.add_argument('--progress', action='store_true', help='Show progress bar')
	parser.add_argument('-o', '--out-file', help='Output file path.')
	parser.add_argument('targets', nargs='*', help = 'Hostname or IP address or file with a list of targets')
	args = parser.parse_args()
	
	if args.verbose >=1:
		logger.setLevel(logging.INFO)

	if args.verbose > 2:
		logger.setLevel(1) #enabling deep debug
		asyncio.get_event_loop().set_debug(True)
		logging.basicConfig(level=logging.DEBUG)
	
	output_type = 'str'
	if args.json is True:
		output_type = 'json'
	if args.tsv is True:
		output_type = 'tsv'

	smb_url = SMBConnectionURL('smb2+ntlm-password://dummy\\dummy:[email protected]')
	enumerator = SMBProtocolEnum(smb_url, worker_count = args.smb_worker_count, timeout = args.timeout, only_signing = args.signing, show_pbar=args.progress, out_file=args.out_file, output_type=output_type)

	notfile = []
	if len(args.targets) == 0 and args.stdin is True:
		enumerator.target_gens.append(ListTargetGen(sys.stdin))
	else:
		for target in args.targets:
			try:
				f = open(target, 'r')
				f.close()
				enumerator.target_gens.append(FileTargetGen(target))
			except:
				notfile.append(target)
	
	if len(notfile) > 0:
		enumerator.target_gens.append(ListTargetGen(notfile))

	if len(enumerator.target_gens) == 0:
		print('[-] No suitable targets were found!')
		return
		
	await enumerator.run()
	if args.progress is False:
		print('[+] Done!')
Exemplo n.º 6
0
async def amain():
	import argparse
	import sys

	parser = argparse.ArgumentParser(description='SMB Protocol enumerator. Tells which dialects suported by the remote end')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	parser.add_argument('-w', '--smb-worker-count', type=int, default=100, help='Parallell count')
	parser.add_argument('-t', '--timeout', type=int, default=50, help='Timeout for each connection')
	parser.add_argument('--signing', action='store_true', help='Only check for the singing properties. (faster)')
	parser.add_argument('-s', '--stdin', action='store_true', help='Read targets from stdin')
	parser.add_argument('targets', nargs='*', help = 'Hostname or IP address or file with a list of targets')
	args = parser.parse_args()

	if args.verbose >=1:
		logger.setLevel(logging.DEBUG)

	if args.verbose > 2:
		print('setting deepdebug')
		logger.setLevel(1) #enabling deep debug
		asyncio.get_event_loop().set_debug(True)
		logging.basicConfig(level=logging.DEBUG)

	enumerator = SMBProtocolEnum(worker_count = args.smb_worker_count, timeout = args.timeout, only_signing = args.signing)

	notfile = []
	if len(args.targets) == 0 and args.stdin is True:
		enumerator.target_gens.append(ListTargetGen(sys.stdin))
	else:
		for target in args.targets:
			try:
				f = open(target, 'r')
				f.close()
				enumerator.target_gens.append(FileTargetGen(target))
			except:
				notfile.append(target)
	
	if len(notfile) > 0:
		enumerator.target_gens.append(ListTargetGen(notfile))

	if len(enumerator.target_gens) == 0:
		print('[-] No suitable targets were found!')
		return
		
	await enumerator.run()
	print('[+] Done!')
Exemplo n.º 7
0
def main():
	import argparse
	import platform
	
	parser = argparse.ArgumentParser(description='Interactive SMB client')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	parser.add_argument('-n', '--no-interactive', action='store_true')
	parser.add_argument('smb_url', help = 'Connection string that describes the authentication and target. Example: smb+ntlm-password://TEST\\Administrator:[email protected]')
	parser.add_argument('commands', nargs='*')
	
	args = parser.parse_args()
	print(__banner__)

	if args.verbose > 2:
		print('setting deepdebug')
		logger.setLevel(1) #enabling deep debug
		sockslogger.setLevel(1)

	print(args.commands)

	asyncio.run(amain(args))
Exemplo n.º 8
0
def main():
	import argparse

	parser = argparse.ArgumentParser(description='Request certificate via ICPR-RPC service')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	parser.add_argument('--pfx-file', help = 'Output PFX file name. Default is cert_<rand>.pfx')
	parser.add_argument('--pfx-pass', default = 'admin', help = 'Ouput PFX file password')
	parser.add_argument('--alt-name', help = 'Alternate username. Preferable username@FQDN format')
	parser.add_argument('--cn', help = 'CN (common name). In case you want to set it to something custom. Preferable username@FQDN format')
	agentenroll = parser.add_argument_group('Agent enrollment parameters')
	agentenroll.add_argument('--on-behalf', help = 'On behalf username')
	agentenroll.add_argument('--enroll-cert', help = 'Agent enrollment PFX file')
	agentenroll.add_argument('--enroll-pass', help = 'Agent enrollment PFX file password')

	parser.add_argument('smb_url', help = 'Connection string that describes the authentication and target. Example: smb+ntlm-password://TEST\\Administrator:[email protected]')
	parser.add_argument('service', help = 'Enrollment service endpoint')
	parser.add_argument('template', help = 'Certificate template name to use')
	
	args = parser.parse_args()
	print(__banner__)

	if args.verbose >=1:
		logger.setLevel(logging.DEBUG)

	asyncio.run(
		amain(
			args.smb_url,
			args.service,
			args.template,
			args.alt_name,
			args.on_behalf,
			args.cn,
			args.pfx_file,
			args.pfx_pass,
			args.enroll_cert,
			args.enroll_pass
		)
	)
Exemplo n.º 9
0
def main():
	import argparse

	parser = argparse.ArgumentParser(description='SMB file downloader')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	#parser.add_argument('-r', '--recursive', action='store_true', help='Recirsively donwload all files from the remote folder')
	parser.add_argument('--progress', action='store_true', help='Show progress')
	parser.add_argument('-o', '--out-file', help='Output file name. Optional.')
	parser.add_argument('url', help='SMB URL with full file path. Example: smb2+ntlm-password://TEST\\Administrator:[email protected]/C$/test.txt')
	
	args = parser.parse_args()

	if args.verbose >=1:
		logger.setLevel(logging.DEBUG)

	if args.verbose > 2:
		print('setting deepdebug')
		logger.setLevel(1) #enabling deep debug
		asyncio.get_event_loop().set_debug(True)
		logging.basicConfig(level=logging.DEBUG)

	
	asyncio.run(amain(args.url, args.out_file))
Exemplo n.º 10
0
    async def run_live(self, args):
        if platform.system().lower() != 'windows':
            raise Exception('Live commands only work on Windows!')

        from aiosmb import logger as smblog

        if args.verbose == 0:
            smblog.setLevel(100)
        elif args.verbose == 1:
            smblog.setLevel(level=logging.INFO)
        else:
            level = 5 - args.verbose
            smblog.setLevel(level=level)

        if args.livesmbcommand == 'console':
            from aiosmb.examples.smbclient import amain
            from winacl.functions.highlevel import get_logon_info
            info = get_logon_info()
            la = SMBCMDArgs()
            la.smb_url = 'smb%s+sspi-%s://%s\\%s@%s' % (
                args.protocol_version, args.authmethod, info['domain'],
                info['username'], args.host)
            la.verbose = args.verbose

            if args.commands is not None and len(args.commands) > 0:
                la.commands = []
                if args.commands[0] == 'help':
                    la.commands = ['help']
                else:
                    if args.commands[0] != 'login':
                        la.commands.append('login')

                    for command in args.commands:
                        la.commands.append(command)

            await amain(la)
Exemplo n.º 11
0
    async def run_live(self, args):
        if platform.system().lower() != 'windows':
            raise Exception('Live commands only work on Windows!')

        from aiosmb import logger as smblog

        if args.verbose == 0:
            smblog.setLevel(100)
        elif args.verbose == 1:
            smblog.setLevel(level=logging.INFO)
        else:
            level = 5 - args.verbose
            smblog.setLevel(level=level)

        if args.livesmbcommand == 'console':
            from aiosmb.examples.smbclient import amain
            from winacl.functions.highlevel import get_logon_info
            info = get_logon_info()
            la = SMBCMDArgs()
            la.smb_url = 'smb%s+sspi-%s://%s\\%s@%s' % (
                args.protocol_version, args.authmethod, info['domain'],
                info['username'], args.host)
            la.verbose = args.verbose

            if args.commands is not None and len(args.commands) > 0:
                la.commands = []
                if args.commands[0] == 'help':
                    la.commands = ['help']
                else:
                    if args.commands[0] != 'login':
                        la.commands.append('login')

                    for command in args.commands:
                        la.commands.append(command)

            await amain(la)

        elif args.livesmbcommand == 'shareenum':
            from pypykatz.smb.shareenum import shareenum

            output_type = 'str'
            if args.json is True:
                output_type = 'json'
            if args.tsv is True:
                output_type = 'tsv'

            exclude_share = []
            if args.es is not None:
                exclude_share = args.es

            exclude_dir = []
            if args.ed is not None:
                exclude_dir = args.ed

            ldap_url = 'auto'
            if args.skip_ldap is True:
                ldap_url = None

            exclude_target = []
            if args.et is not None:
                exclude_target = args.et

            await shareenum(
                smb_url='auto',
                targets=args.target,
                smb_worker_count=args.worker_count,
                depth=args.depth,
                out_file=args.out_file,
                progress=args.progress,
                max_items=args.maxitems,
                dirsd=args.dirsd,
                filesd=args.filesd,
                authmethod=args.authmethod,
                protocol_version=args.protocol_version,
                output_type=output_type,
                max_runtime=args.max_runtime,
                exclude_share=exclude_share,
                exclude_dir=exclude_dir,
                ldap_url=ldap_url,
                exclude_target=exclude_target,
            )
Exemplo n.º 12
0
async def amain():
    import argparse
    import sys
    import logging

    parser = argparse.ArgumentParser(
        description='Registry manipulation via SMB')
    SMBConnectionParams.extend_parser(parser)
    parser.add_argument('-v', '--verbose', action='count', default=0)
    parser.add_argument(
        'url',
        help=
        'Connection URL base, target can be set to anything. Owerrides all parameter based connection settings! Example: "smb2+ntlm-password://TEST\\victim@test"'
    )
    parser.add_argument(
        'commands',
        nargs='*',
        help=
        'Commands in the following format: "r:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest:Negotiate"'
    )

    args = parser.parse_args()

    if args.verbose >= 1:
        logger.setLevel(logging.DEBUG)

    if args.verbose > 2:
        print('setting deepdebug')
        logger.setLevel(1)  #enabling deep debug
        asyncio.get_event_loop().set_debug(True)
        logging.basicConfig(level=logging.DEBUG)

    commands = []
    smb_url = None
    if args.url is not None:
        smb_url = args.url
    else:
        try:
            smb_url = SMBConnectionParams.parse_args(args)
        except Exception as e:
            print(
                'Either URL or all connection parameters must be set! Error: %s'
                % str(e))
            sys.exit(1)

    #pre-parsing commands
    for cmd in args.commands:
        c, path = cmd.split(':', 1)
        c = SMBREG_COMMAND(c.upper())
        commands.append((c, path))

    connection = SMBConnectionURL(smb_url).get_connection()
    _, err = await connection.login()
    if err is not None:
        print('Login failed! Reason: %s' % str(err))
        return
    machine = SMBMachine(connection)
    #async for srv, err in machine.list_services():
    #	if err is not None:
    #		print(err)
    #		return
    #	print(srv)
    registry_srv_status, err = await machine.check_service_status(
        "RemoteRegistry")
    if err is not None:
        print('Check service status error! %s' % err)
        return

    if registry_srv_status != SMBServiceStatus.RUNNING:
        logger.info('RemoteRegistry is not running! Starting it now..')
        res, err = await machine.enable_service("RemoteRegistry")
        if err is not None:
            print(err)
            return
        await asyncio.sleep(5)  #waiting for service to start up

    reg_api, err = await machine.get_regapi()
    if err is not None:
        print(err)
        return

    ## do stuff
    for cmd, target in commands:
        if cmd == SMBREG_COMMAND.READ:
            regpath, name = target.split(':', 1)
            hkey, err = await reg_api.OpenRegPath(regpath)
            if err is not None:
                print(err)
                continue

            val_type, value, err = await reg_api.QueryValue(hkey, name)
            if err is not None:
                print(err)
                continue
            print(value)

        elif cmd == SMBREG_COMMAND.ENUMVALUE:
            hkey, err = await reg_api.OpenRegPath(target)
            if err is not None:
                print(err)
                continue

            i = 0
            while True:
                value_name, value_type, value_data, err = await reg_api.EnumValue(
                    hkey, i)
                i += 1
                if err is not None:
                    print(err)
                    break
                print(value_name)
                print(value_type)
                print(value_data)

        elif cmd == SMBREG_COMMAND.ENUMKEY:
            hkey, err = await reg_api.OpenRegPath(target)
            if err is not None:
                print(err)
                continue
            i = 0
            while True:
                res, err = await reg_api.EnumKey(hkey, i)
                i += 1
                if err is not None:
                    print(err)
                    break

                print(res)
Exemplo n.º 13
0
	async def run(self, args):

		from aiosmb import logger as smblog

		if args.verbose == 0:
			smblog.setLevel(100)
		elif args.verbose == 1:
			smblog.setLevel(level=logging.INFO)
		else:
			level = 5 - args.verbose
			smblog.setLevel(level=level)
		
		if args.smb_module == 'lsassfile':
			from pypykatz.smb.lsassutils import lsassfile
			mimi = await lsassfile(args.url, chunksize=args.chunksize, packages=args.packages)
			self.process_results({'smbfile':mimi}, [], args)

		elif args.smb_module == 'lsassdump':
			from pypykatz.smb.lsassutils import lsassdump
			mimi = await lsassdump(args.url, chunksize=args.chunksize, packages=args.packages)
			self.process_results({'smbfile':mimi}, [], args)

		elif args.smb_module == 'secretsdump':
			from pypykatz.smb.lsassutils import lsassdump
			from pypykatz.smb.regutils import regdump
			from pypykatz.smb.dcsync import dcsync

			try:
				mimi = await lsassdump(args.url, chunksize=args.chunksize, packages=args.packages)
				if mimi is not None:
					self.process_results({'smbfile':mimi}, [], args, file_prefix='_lsass.txt')
			except Exception as e:
				logging.exception('[SECRETSDUMP] Failed to get LSASS secrets')
			
			try:
				po = await regdump(args.url)
				if po is not None:
					if args.outfile:
						po.to_file(args.outfile+'_registry.txt', args.json)
					else:
						if args.json:
							print(json.dumps(po.to_dict(), cls = UniversalEncoder, indent=4, sort_keys=True))
						else:
							print(str(po))
			except Exception as e:
				logging.exception('[SECRETSDUMP] Failed to get registry secrets')
			

			try:
				if args.outfile is not None:
					outfile = open(args.outfile+'_dcsync.txt', 'w', newline = '')

				async for secret in dcsync(args.url):
					if args.outfile is not None:
						outfile.write(str(secret))
					else:
						print(str(secret))

			except Exception as e:
				logging.exception('[SECRETSDUMP] Failed to perform DCSYNC')
			finally:
				if args.outfile is not None:
					outfile.close()
		
		elif args.smb_module == 'dcsync':
			from pypykatz.smb.dcsync import dcsync
			
			if args.outfile is not None:
				outfile = open(args.outfile, 'w', newline = '')

			async for secret in dcsync(args.url, args.username):
				if args.outfile is not None:
					outfile.write(str(secret))
				else:
					print(str(secret))

			if args.outfile is not None:
				outfile.close()
		
		elif args.smb_module == 'regdump':
			from pypykatz.smb.regutils import regdump
			po = await regdump(args.url)

			if po is not None:
				if args.outfile:
					po.to_file(args.outfile, args.json)
				else:
					if args.json:
						print(json.dumps(po.to_dict(), cls = UniversalEncoder, indent=4, sort_keys=True))
					else:
						print(str(po))
		
		elif args.smb_module == 'regfile':
			from pypykatz.smb.regutils import regfile
			po = await regfile(args.url, args.system, sam = args.sam, security = args.security, software = args.software)

			if po is not None:
				if args.outfile:
					po.to_file(args.outfile, args.json)
				else:
					if args.json:
						print(json.dumps(po.to_dict(), cls = UniversalEncoder, indent=4, sort_keys=True))
					else:
						print(str(po))
		
		elif args.smb_module == 'shareenum':
			from pypykatz.smb.shareenum import shareenum


			output_type = 'str'
			if args.json is True:
				output_type = 'json'
			if args.tsv is True:
				output_type = 'tsv'

			exclude_share = []
			if args.es is not None:
				exclude_share = args.es
			
			exclude_dir = []
			if args.ed is not None:
				exclude_dir = args.ed

			exclude_target = []
			if args.et is not None:
				exclude_target = args.et

			
			await shareenum(
				args.smb_url,
				targets = args.target,  
				smb_worker_count = args.worker_count, 
				depth = args.depth, 
				out_file = args.out_file, 
				progress = args.progress, 
				max_items = args.maxitems, 
				dirsd = args.dirsd, 
				filesd = args.filesd, 
				output_type = output_type,
				max_runtime = args.max_runtime,
				exclude_share = exclude_share,
				exclude_dir = exclude_dir,
				ldap_url = args.ldap,
				exclude_target = exclude_target,
			)


		elif args.smb_module == 'client':
			from aiosmb.examples.smbclient import amain
			la = SMBCMDArgs()
			la.smb_url = args.url
			la.verbose = args.verbose
			if args.commands is not None and len(args.commands) > 0:
				la.commands = []
				if args.commands[0] == 'help':
					la.commands = ['help']
				else:
					if args.commands[0] != 'login':
						la.commands.append('login')
					
					for command in args.commands:
						la.commands.append(command)

			await amain(la)
Exemplo n.º 14
0
	async def run_live(self, args):
		if platform.system().lower() != 'windows':
			raise Exception('Live commands only work on Windows!')

		from aiosmb import logger as smblog
		from winacl.functions.highlevel import get_logon_info
		
		info = get_logon_info()
		if args.livesmbcommand != 'shareenum':
			smb_url = 'smb%s+sspi-%s://%s\\%s@%s' % (args.protocol_version, args.authmethod, info['domain'], info['username'], args.host)

		if args.verbose == 0:
			smblog.setLevel(100)
		elif args.verbose == 1:
			smblog.setLevel(level=logging.INFO)
		else:
			level = 5 - args.verbose
			smblog.setLevel(level=level)

		if args.livesmbcommand == 'client':
			from aiosmb.examples.smbclient import amain
			
			
			la = SMBCMDArgs()
			la.smb_url = smb_url
			la.verbose = args.verbose

			if args.commands is not None and len(args.commands) > 0:
				la.commands = []
				if args.commands[0] == 'help':
					la.commands = ['help']
				else:
					if args.commands[0] != 'login':
						la.commands.append('login')
					
					for command in args.commands:
						la.commands.append(command)

			await amain(la)


		elif args.livesmbcommand == 'lsassdump':
			from pypykatz.smb.lsassutils import lsassdump
			mimi = await lsassdump(smb_url, chunksize=args.chunksize, packages=args.packages)
			self.process_results({'smbfile':mimi}, [], args)

		elif args.livesmbcommand == 'secretsdump':
			from pypykatz.smb.lsassutils import lsassdump
			from pypykatz.smb.regutils import regdump
			from pypykatz.smb.dcsync import dcsync

			try:
				mimi = await lsassdump(smb_url, chunksize=args.chunksize, packages=args.packages)
				if mimi is not None:
					self.process_results({'smbfile':mimi}, [], args, file_prefix='_lsass.txt')
			except Exception as e:
				logging.exception('[SECRETSDUMP] Failed to get LSASS secrets')
			
			try:
				po = await regdump(smb_url)
				if po is not None:
					if args.outfile:
						po.to_file(args.outfile+'_registry.txt', args.json)
					else:
						if args.json:
							print(json.dumps(po.to_dict(), cls = UniversalEncoder, indent=4, sort_keys=True))
						else:
							print(str(po))
			except Exception as e:
				logging.exception('[SECRETSDUMP] Failed to get registry secrets')
			

			try:
				if args.outfile is not None:
					outfile = open(args.outfile+'_dcsync.txt', 'w', newline = '')

				async for secret in dcsync(smb_url):
					if args.outfile is not None:
						outfile.write(str(secret))
					else:
						print(str(secret))

			except Exception as e:
				logging.exception('[SECRETSDUMP] Failed to perform DCSYNC')
			finally:
				if args.outfile is not None:
					outfile.close()
		
		elif args.livesmbcommand == 'dcsync':
			from pypykatz.smb.dcsync import dcsync
			
			if args.outfile is not None:
				outfile = open(args.outfile, 'w', newline = '')

			async for secret in dcsync(smb_url, args.username):
				if args.outfile is not None:
					outfile.write(str(secret))
				else:
					print(str(secret))

			if args.outfile is not None:
				outfile.close()
		
		elif args.livesmbcommand == 'regdump':
			from pypykatz.smb.regutils import regdump
			po = await regdump(smb_url)

			if po is not None:
				if args.outfile:
					po.to_file(args.outfile, args.json)
				else:
					if args.json:
						print(json.dumps(po.to_dict(), cls = UniversalEncoder, indent=4, sort_keys=True))
					else:
						print(str(po))

		elif args.livesmbcommand == 'shareenum':
			from pypykatz.smb.shareenum import shareenum

			output_type = 'str'
			if args.json is True:
				output_type = 'json'
			if args.tsv is True:
				output_type = 'tsv'

			exclude_share = []
			if args.es is not None:
				exclude_share = args.es
			
			exclude_dir = []
			if args.ed is not None:
				exclude_dir = args.ed

			ldap_url = 'auto'
			if args.skip_ldap is True:
				ldap_url = None
			
			exclude_target = []
			if args.et is not None:
				exclude_target = args.et
			
			await shareenum(
				smb_url = 'auto',
				targets = args.target, 
				smb_worker_count = args.worker_count, 
				depth = args.depth, 
				out_file = args.out_file, 
				progress = args.progress, 
				max_items = args.maxitems, 
				dirsd = args.dirsd, 
				filesd = args.filesd, 
				authmethod = args.authmethod,
				protocol_version = args.protocol_version,
				output_type = output_type,
				max_runtime = args.max_runtime,
				exclude_share = exclude_share,
				exclude_dir = exclude_dir,
				ldap_url = ldap_url,
				exclude_target = exclude_target,
			)
Exemplo n.º 15
0
async def amain():
	import argparse
	import sys
	from aiosmb.commons.connection.params import SMBConnectionParams

	epilog = """
Output legend:
    [SHARE] C$ is accessible
    [SRV] Remote Service Manager is accessible
    [REG] Remote registry is accessible
    [E] Error
    [P] Progress (current/total)
"""

	parser = argparse.ArgumentParser(description='SMB Share enumerator', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=epilog)
	SMBConnectionParams.extend_parser(parser)
	parser.add_argument('-v', '--verbose', action='count', default=0)
	parser.add_argument('-w', '--smb-worker-count', type=int, default=100, help='Parallell count')
	parser.add_argument('-s', '--stdin', action='store_true', help='Read targets from stdin')
	parser.add_argument('--url', help='Connection URL base, target can be set to anything. Owerrides all parameter based connection settings! Example: "smb2+ntlm-password://TEST\\victim@test"')
	parser.add_argument('targets', nargs='*', help = 'Hostname or IP address or file with a list of targets')
	args = parser.parse_args()

	if args.verbose >=1:
		logger.setLevel(logging.DEBUG)

	if args.verbose > 2:
		print('setting deepdebug')
		logger.setLevel(1) #enabling deep debug
		asyncio.get_event_loop().set_debug(True)
		logging.basicConfig(level=logging.DEBUG)

	smb_url = None
	if args.url is not None:
		smb_url = args.url
	else:
		try:
			smb_url = SMBConnectionParams.parse_args(args)
		except Exception as e:
			print('Either URL or all connection parameters must be set! Error: %s' % str(e))
			sys.exit(1)
	
	enumerator = SMBAdminCheck(smb_url, worker_count = args.smb_worker_count)
	
	notfile = []
	if len(args.targets) == 0 and args.stdin is True:
		enumerator.target_gens.append(ListTargetGen(sys.stdin))
	else:
		for target in args.targets:
			try:
				f = open(target, 'r')
				f.close()
				enumerator.target_gens.append(FileTargetGen(target))
			except:
				notfile.append(target)
	
	if len(notfile) > 0:
		enumerator.target_gens.append(ListTargetGen(notfile))

	if len(enumerator.target_gens) == 0:
		print('[-] No suitable targets were found!')
		return
		
	await enumerator.run()
Exemplo n.º 16
0
async def run(args):
    print(__banner__)
    if args.verbose == 0:
        logging.basicConfig(level=logging.INFO)
        jdlogger.setLevel(logging.INFO)
        msldaplogger.setLevel(logging.WARNING)
        smblogger.setLevel(logging.CRITICAL)

    elif args.verbose == 1:
        logging.basicConfig(level=logging.DEBUG)
        jdlogger.setLevel(logging.DEBUG)
        msldaplogger.setLevel(logging.INFO)
        smblogger.setLevel(logging.INFO)

    elif args.verbose > 1:
        logging.basicConfig(level=1)
        msldaplogger.setLevel(logging.DEBUG)
        jdlogger.setLevel(1)
        smblogger.setLevel(1)

    if not args.sql:
        print(
            'SQL connection identification is missing! You need to provide the --sql parameter'
        )
        sys.exit()

    db_conn = args.sql
    if args.sql.lower().startswith('sqlite'):
        os.environ['JACKDAW_SQLITE'] = '1'

    if args.command == 'enum':
        smb_mgr = construct_smbdef(args)
        ldap_mgr = construct_ldapdef(args)

        mgr = LDAPEnumeratorManager(db_conn,
                                    ldap_mgr,
                                    agent_cnt=args.ldap_workers)
        adifo_id = await mgr.run()
        jdlogger.info('ADInfo entry successfully created with ID %s' %
                      adifo_id)

        mgr = SMBGathererManager(smb_mgr,
                                 worker_cnt=args.smb_workers,
                                 queue_size=args.smb_queue_size)
        mgr.gathering_type = ['all']
        mgr.db_conn = db_conn
        mgr.target_ad = adifo_id
        await mgr.run()

        if args.smb_share_enum is True:
            settings_base = SMBShareGathererSettings(adifo_id, smb_mgr, None,
                                                     None, None)
            settings_base.dir_depth = args.smb_folder_depth
            mgr = ShareGathererManager(settings_base,
                                       db_conn=db_conn,
                                       worker_cnt=args.smb_workers)
            mgr.run()

    elif args.command == 'dbinit':
        create_db(db_conn)

    elif args.command == 'adinfo':
        session = get_session(db_conn)
        from jackdaw.dbmodel.adinfo import JackDawADInfo
        from jackdaw.utils.table import print_table

        rows = [['Ad ID', 'domain name', 'scantime']]
        for did, distinguishedName, creation in session.query(
                JackDawADInfo).with_entities(JackDawADInfo.id,
                                             JackDawADInfo.distinguishedName,
                                             JackDawADInfo.fetched_at).all():
            name = distinguishedName.replace('DC=', '')
            name = name.replace(',', '.')
            rows.append([str(did), name, creation.isoformat()])
        print_table(rows)

    elif args.command == 'ldap':
        ldap_mgr = construct_ldapdef(args)
        ldap_conn = ldap_mgr.get_client()

        mgr = LDAPEnumeratorManager(db_conn,
                                    ldap_mgr,
                                    agent_cnt=args.ldap_workers,
                                    queue_size=args.ldap_queue_size,
                                    ad_id=args.ad_id)
        adifo_id = await mgr.run()
        jdlogger.info('ADInfo entry successfully created with ID %s' %
                      adifo_id)

    elif args.command in ['shares', 'sessions', 'localgroups', 'smball']:
        if args.command == 'smball':
            args.command = 'all'
        smb_mgr = construct_smbdef(args)
        mgr = SMBGathererManager(smb_mgr,
                                 worker_cnt=args.smb_workers,
                                 queue_size=args.smb_queue_size)
        mgr.gathering_type = [args.command]
        mgr.db_conn = db_conn
        mgr.lookup_ad = args.lookup_ad

        if args.ldap_url:
            ldap_mgr = construct_ldapdef(args)
            ldap_conn = ldap_mgr.get_client()
            mgr.ldap_conn = ldap_conn

        if args.ad_id:
            mgr.target_ad = args.ad_id

        if args.target_file:
            mgr.targets_file = args.target_file

        await mgr.run()

    elif args.command == 'files':
        if args.src == 'domain':
            if not args.ad_id:
                raise Exception('ad-id parameter is mandatory in ldap mode')

            mgr = SMBConnectionURL(args.smb_url)
            settings_base = SMBShareGathererSettings(args.ad_id, mgr, None,
                                                     None, None)
            settings_base.dir_depth = args.smb_folder_depth
            settings_base.dir_with_sd = args.with_sid
            settings_base.file_with_sd = args.with_sid

            mgr = ShareGathererManager(settings_base,
                                       db_conn=db_conn,
                                       worker_cnt=args.smb_workers)
            mgr.run()

    #	elif args.src == 'file':
    #		if not args.target_file:
    #			raise Exception('target-file parameter is mandatory in file mode')
    #
    #		args.target_file
    #		args.lookup_ad
    #		args.with_sid
    #		args.smb_workers
    #
    #	elif args.src == 'ldap':
    #		if not args.ldap_url:
    #			raise Exception('ldap-url parameter is mandatory in ldap mode')
    #		args.lookup_ad
    #		args.with_sid
    #		args.smb_workers
    #
    #
    #
    #	elif args.src == 'cmd':

    elif args.command == 'creds':
        creds = JackDawCredentials(args.db_conn, args.domain_id)
        creds.add_credentials_impacket(args.impacket_file)

    elif args.command == 'passwords':
        creds = JackDawCredentials(args.db_conn)
        creds.add_cracked_passwords(args.potfile, args.disable_usercheck,
                                    args.disable_passwordcheck)

    elif args.command == 'uncracked':
        creds = JackDawCredentials(args.db_conn, args.domain_id)
        creds.get_uncracked_hashes(args.hash_type, args.history)

    elif args.command == 'cracked':
        creds = JackDawCredentials(args.db_conn, args.domain_id)
        creds.get_cracked_info()

    elif args.command == 'nest':
        from jackdaw.nest.wrapper import NestServer

        debug = bool(args.verbose)

        server = NestServer(args.sql,
                            bind_ip=args.ip,
                            bind_port=args.port,
                            debug=debug)
        server.run()
Exemplo n.º 17
0
async def amain():
	import argparse
	import sys
	from aiosmb.commons.connection.params import SMBConnectionParams

	epilog = """
Output legend:
    [S] Share
    [D] Dictionary
    [F] File
    [E] Error
    [M] Maxed (max items limit reached for directory)
    [P] Progress (current/total)
"""

	parser = argparse.ArgumentParser(description='SMB Printnightmare enumerator', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=epilog)
	SMBConnectionParams.extend_parser(parser)
	parser.add_argument('-v', '--verbose', action='count', default=0)
	parser.add_argument('-w', '--smb-worker-count', type=int, default=100, help='Parallell count')
	parser.add_argument('-o', '--out-file', help='Output file path.')
	parser.add_argument('-s', '--stdin', action='store_true', help='Read targets from stdin')
	parser.add_argument('--url', help='Connection URL base, target can be set to anything. Owerrides all parameter based connection settings! Example: "smb2+ntlm-password://TEST\\victim@test"')
	parser.add_argument('--progress', action='store_true', help='Show progress bar')
	parser.add_argument('--json', action='store_true', help='Output in JSON format')
	parser.add_argument('--tsv', action='store_true', help='Output in TSV format. (TAB Separated Values)')
	parser.add_argument('targets', nargs='*', help = 'Hostname or IP address or file with a list of targets')

	args = parser.parse_args()

	if args.verbose >=1:
		logger.setLevel(logging.DEBUG)

	if args.verbose > 2:
		print('setting deepdebug')
		logger.setLevel(1) #enabling deep debug
		asyncio.get_event_loop().set_debug(True)
		logging.basicConfig(level=logging.DEBUG)

	output_type = 'str'
	if args.json is True:
		output_type = 'json'
	if args.tsv is True:
		output_type = 'tsv'

	smb_url = None
	if args.url is not None:
		smb_url = args.url
	else:
		try:
			smb_url = SMBConnectionParams.parse_args(args)
		except Exception as e:
			print('Either URL or all connection parameters must be set! Error: %s' % str(e))
			sys.exit(1)
	

	enumerator = SMBPrintnightmareEnum(
		smb_url,
		worker_count = args.smb_worker_count,
		out_file = args.out_file,
		show_pbar = args.progress,
		output_type = output_type,
	)
	
	notfile = []
	if len(args.targets) == 0 and args.stdin is True:
		enumerator.target_gens.append(ListTargetGen(sys.stdin))
	else:
		for target in args.targets:
			try:
				f = open(target, 'r')
				f.close()
				enumerator.target_gens.append(FileTargetGen(target))
			except:
				notfile.append(target)
	
	if len(notfile) > 0:
		enumerator.target_gens.append(ListTargetGen(notfile))

	if len(enumerator.target_gens) == 0:
		enumerator.enum_url = True

	await enumerator.run()
Exemplo n.º 18
0
async def amain():
    import argparse
    import sys
    from aiosmb.commons.connection.params import SMBConnectionParams

    parser = argparse.ArgumentParser(description='SMB Share enumerator')
    SMBConnectionParams.extend_parser(parser)
    parser.add_argument('-v', '--verbose', action='count', default=0)
    parser.add_argument('-s',
                        '--stdin',
                        action='store_true',
                        help='Read targets from stdin')
    parser.add_argument(
        '-r',
        '--recursive',
        action='store_true',
        help='Recirsively donwload all files from the remote folder')
    parser.add_argument('--progress',
                        action='store_true',
                        help='Show progress')
    parser.add_argument(
        '--url',
        help=
        'Connection URL base, target can be set to anything. Owerrides all parameter based connection settings! Example: "smb2+ntlm-password://TEST\\victim@test"'
    )
    parser.add_argument(
        'targets',
        nargs='*',
        help='UNC paths of file eg. \\\\HOST\\SHARE\\file_or_folder')
    args = parser.parse_args()

    if args.verbose >= 1:
        logger.setLevel(logging.DEBUG)

    if args.verbose > 2:
        print('setting deepdebug')
        logger.setLevel(1)  #enabling deep debug
        asyncio.get_event_loop().set_debug(True)
        logging.basicConfig(level=logging.DEBUG)

    smb_url = None
    if args.url is not None:
        smb_url = args.smb_url
    else:
        try:
            smb_url = SMBConnectionParams.parse_args(args)
        except Exception as e:
            print(
                'Either URL or all connection parameters must be set! Error: %s'
                % str(e))
            sys.exit(1)

    smbget = SMBGET(smb_url, show_progress=args.progress)

    notfile = []
    if len(args.targets) == 0 and args.stdin is True:
        smbget.target_gens.append(ListTargetGen(sys.stdin))
    else:
        for target in args.targets:
            try:
                f = open(target, 'r')
                f.close()
                smbget.target_gens.append(FileTargetGen(target))
            except:
                notfile.append(target)

    if len(notfile) > 0:
        smbget.target_gens.append(ListTargetGen(notfile))

    if len(smbget.target_gens) == 0:
        print('[-] No suitable targets were found!')
        return

    await smbget.run()
Exemplo n.º 19
0
def run(args):
    if args.verbose == 0:
        logging.basicConfig(level=logging.INFO)
        jdlogger.setLevel(logging.INFO)
        msldaplogger.setLevel(logging.WARNING)
        smblogger.setLevel(logging.CRITICAL)

    elif args.verbose == 1:
        logging.basicConfig(level=logging.DEBUG)
        jdlogger.setLevel(logging.DEBUG)
        msldaplogger.setLevel(logging.INFO)
        smblogger.setLevel(logging.INFO)

    elif args.verbose > 1:
        logging.basicConfig(level=1)
        msldaplogger.setLevel(logging.DEBUG)
        jdlogger.setLevel(1)
        smblogger.setLevel(1)

    if not args.sql:
        print(
            'SQL connection identification is missing! You need to provide the --sql parameter'
        )
        sys.exit()

    db_conn = args.sql

    if args.command == 'enum':
        smb_mgr = construct_smbdef(args)
        ldap_mgr = construct_ldapdef(args)

        mgr = LDAPEnumeratorManager(db_conn,
                                    ldap_mgr,
                                    agent_cnt=args.ldap_workers)
        adifo_id = mgr.run()
        print('ADInfo entry successfully created with ID %s' % adifo_id)

        mgr = SMBGathererManager(smb_mgr, worker_cnt=args.smb_workers)
        mgr.gathering_type = ['all']
        mgr.db_conn = db_conn
        mgr.target_ad = adifo_id
        mgr.run()

    elif args.command == 'dbinit':
        create_db(db_conn)

    elif args.command == 'adinfo':
        session = get_session(db_conn)
        from jackdaw.dbmodel.adinfo import JackDawADInfo
        from jackdaw.utils.table import print_table

        rows = [['Ad ID', 'domain name', 'scantime']]
        for did, distinguishedName, creation in session.query(
                JackDawADInfo).with_entities(JackDawADInfo.id,
                                             JackDawADInfo.distinguishedName,
                                             JackDawADInfo.fetched_at).all():
            name = distinguishedName.replace('DC=', '')
            name = name.replace(',', '.')
            rows.append([str(did), name, creation.isoformat()])
        print_table(rows)

    elif args.command == 'ldap':
        ldap_mgr = construct_ldapdef(args)
        ldap_conn = ldap_mgr.get_connection()
        ldap_conn.connect()

        mgr = LDAPEnumeratorManager(db_conn,
                                    ldap_mgr,
                                    agent_cnt=args.ldap_workers)
        adifo_id = mgr.run()
        print('ADInfo entry successfully created with ID %s' % adifo_id)

    elif args.command in ['shares', 'sessions', 'localgroups']:
        smb_mgr = construct_smbdef(args)
        mgr = SMBGathererManager(smb_mgr)
        mgr.gathering_type = [args.command]
        mgr.db_conn = db_conn
        mgr.lookup_ad = args.lookup_ad

        if args.ldap_url:
            ldap_mgr = construct_ldapdef(args)
            ldap_conn = ldap_mgr.get_connection()
            ldap_conn.connect()
            mgr.ldap_conn = ldap_conn

        if args.ad_id:
            mgr.target_ad = args.ad_id

        if args.target_file:
            mgr.targets_file = args.target_file

        mgr.run()

    elif args.command == 'creds':
        creds = JackDawCredentials(args.db_conn, args.domain_id)
        creds.add_credentials_impacket(args.impacket_file)

    elif args.command == 'passwords':
        creds = JackDawCredentials(args.db_conn)
        creds.add_cracked_passwords(args.potfile, args.disable_usercheck,
                                    args.disable_passwordcheck)

    elif args.command == 'uncracked':
        creds = JackDawCredentials(args.db_conn, args.domain_id)
        creds.get_uncracked_hashes(args.hash_type, args.history)

    elif args.command == 'cracked':
        creds = JackDawCredentials(args.db_conn, args.domain_id)
        creds.get_cracked_info()

    elif args.command == 'nest':
        from jackdaw.nest.wrapper import NestServer

        debug = bool(args.verbose)

        server = NestServer(args.sql,
                            bind_ip=args.ip,
                            bind_port=args.port,
                            debug=debug)
        server.run()
Exemplo n.º 20
0
async def run(args):
    try:
        if args.silent is True:
            print(__banner__)
        if args.verbose == 0:
            logging.basicConfig(level=logging.INFO)
            jdlogger.setLevel(logging.INFO)
            msldaplogger.setLevel(logging.CRITICAL)
            smblogger.setLevel(100)

        elif args.verbose == 1:
            logging.basicConfig(level=logging.DEBUG)
            jdlogger.setLevel(logging.DEBUG)
            msldaplogger.setLevel(logging.WARNING)
            smblogger.setLevel(logging.CRITICAL)

        elif args.verbose > 1:
            logging.basicConfig(level=1)
            msldaplogger.setLevel(logging.DEBUG)
            jdlogger.setLevel(1)
            smblogger.setLevel(1)

        if not args.sql and args.command != 'auto':
            print(
                'SQL connection identification is missing! You need to provide the --sql parameter'
            )
            sys.exit()

        work_dir = './workdir'
        ldap_url = None
        smb_url = None

        if hasattr(args, 'ldap_url'):
            ldap_url = args.ldap_url
        if hasattr(args, 'smb_url'):
            smb_url = args.smb_url

        db_conn = args.sql
        if db_conn is not None:
            os.environ['JACKDAW_SQLITE'] = '0'
            if args.sql.lower().startswith('sqlite'):
                os.environ['JACKDAW_SQLITE'] = '1'
        else:
            os.environ['JACKDAW_SQLITE'] = '1'

        if args.command == 'enum':
            with multiprocessing.Pool() as mp_pool:
                gatherer = Gatherer(db_conn,
                                    work_dir,
                                    ldap_url,
                                    smb_url,
                                    kerb_url=args.kerberoast,
                                    ldap_worker_cnt=args.ldap_workers,
                                    smb_worker_cnt=args.smb_workers,
                                    mp_pool=mp_pool,
                                    smb_gather_types=['all'],
                                    progress_queue=None,
                                    show_progress=args.silent,
                                    calc_edges=True,
                                    ad_id=None,
                                    dns=args.dns,
                                    no_work_dir=args.no_work_dir)
                res, err = await gatherer.run()
                if err is not None:
                    raise err

        elif args.command == 'auto':
            _, err = await run_auto(ldap_worker_cnt=args.ldap_workers,
                                    smb_worker_cnt=args.smb_workers,
                                    dns=args.dns,
                                    work_dir=work_dir,
                                    show_progress=args.silent,
                                    no_work_dir=args.no_work_dir)
            if err is not None:
                print(err)

        elif args.command == 'dbinit':
            create_db(db_conn)

        elif args.command == 'adinfo':
            session = get_session(db_conn)
            from jackdaw.dbmodel.adinfo import ADInfo
            from jackdaw.utils.table import print_table

            rows = [['Ad ID', 'domain name', 'scantime']]
            for did, distinguishedName, creation in session.query(
                    ADInfo).with_entities(ADInfo.id, ADInfo.distinguishedName,
                                          ADInfo.fetched_at).all():
                name = distinguishedName.replace('DC=', '')
                name = name.replace(',', '.')
                rows.append([str(did), name, creation.isoformat()])
            print_table(rows)

        elif args.command == 'ldap':
            with multiprocessing.Pool() as mp_pool:
                gatherer = Gatherer(db_conn,
                                    work_dir,
                                    ldap_url,
                                    smb_url,
                                    ldap_worker_cnt=args.ldap_workers,
                                    smb_worker_cnt=None,
                                    mp_pool=mp_pool,
                                    smb_gather_types=['all'],
                                    progress_queue=None,
                                    show_progress=args.silent,
                                    calc_edges=args.calculate_edges,
                                    ad_id=args.ad_id,
                                    no_work_dir=args.no_work_dir)
                await gatherer.run()

        elif args.command == 'kerberoast':
            gatherer = Gatherer(db_conn,
                                work_dir,
                                None,
                                None,
                                kerb_url=args.kerberos_url,
                                ldap_worker_cnt=None,
                                smb_worker_cnt=None,
                                mp_pool=None,
                                smb_gather_types=[],
                                progress_queue=None,
                                show_progress=False,
                                calc_edges=False,
                                ad_id=args.ad_id)
            await gatherer.run()
            print('Kerberoast Finished!')

        elif args.command in ['shares', 'sessions', 'localgroups', 'smball']:
            if args.command == 'smball':
                args.command = 'all'

            gatherer = Gatherer(
                db_conn,
                work_dir,
                ldap_url,
                smb_url,
                ad_id=args.ad_id,
                ldap_worker_cnt=None,
                smb_worker_cnt=args.smb_workers,
                mp_pool=None,
                smb_gather_types=args.command,
                progress_queue=None,
                show_progress=args.silent,
                calc_edges=False,
                dns=args.dns,
            )
            await gatherer.run()

        elif args.command == 'dns':
            gatherer = Gatherer(
                db_conn,
                work_dir,
                None,
                None,
                ad_id=args.ad_id,
                ldap_worker_cnt=None,
                smb_worker_cnt=None,
                mp_pool=None,
                smb_gather_types=None,
                progress_queue=None,
                show_progress=args.silent,
                calc_edges=False,
                dns=args.dns,
            )
            await gatherer.run()

        elif args.command == 'version':
            print('Jackdaw version: %s' % jdversion)
            print('MSLDAP version : %s' % ldapversion)
            print('AIOSMB version : %s' % smbversion)

        elif args.command == 'files':
            raise Exception('not yet implemented!')
            #if args.src == 'domain':
            #	if not args.ad_id:
            #		raise Exception('ad-id parameter is mandatory in ldap mode')
            #
            #	mgr = SMBConnectionURL(args.smb_url)
            #	settings_base = SMBShareGathererSettings(args.ad_id, mgr, None, None, None)
            #	settings_base.dir_depth = args.smb_folder_depth
            #	settings_base.dir_with_sd = args.with_sid
            #	settings_base.file_with_sd = args.with_sid
            #
            #	mgr = ShareGathererManager(settings_base, db_conn = db_conn, worker_cnt = args.smb_workers)
            #	mgr.run()

        elif args.command == 'creds':
            creds = JackDawCredentials(db_conn, args.domain_id)
            creds.add_credentials_impacket(args.impacket_file)

        elif args.command == 'passwords':
            creds = JackDawCredentials(db_conn)
            creds.add_cracked_passwords(args.potfile, args.disable_usercheck,
                                        args.disable_passwordcheck)

        elif args.command == 'uncracked':
            creds = JackDawCredentials(db_conn, args.domain_id)
            creds.get_uncracked_hashes(args.hash_type, args.history)

        elif args.command == 'cracked':
            creds = JackDawCredentials(db_conn, args.domain_id)
            creds.get_cracked_info()

        elif args.command == 'recalc':
            with multiprocessing.Pool() as mp_pool:
                gatherer = Gatherer(db_conn,
                                    work_dir,
                                    None,
                                    None,
                                    mp_pool=mp_pool,
                                    progress_queue=None,
                                    show_progress=args.silent,
                                    calc_edges=True,
                                    store_to_db=True,
                                    ad_id=None,
                                    graph_id=args.graphid)
                await gatherer.run()

        elif args.command == 'nest':
            from jackdaw.nest.wrapper import NestServer

            debug = bool(args.verbose)

            server = NestServer(
                args.sql,
                bind_ip=args.ip,
                bind_port=args.port,
                debug=debug,
                work_dir=args.work_dir,
                graph_backend=args.backend,
            )
            server.run()

        elif args.command == 'ws':
            from jackdaw.nest.ws.server import NestWebSocketServer
            server = NestWebSocketServer(args.listen_ip,
                                         args.listen_port,
                                         args.sql,
                                         args.work_dir,
                                         args.backend,
                                         ssl_ctx=None)
            await server.run()

        elif args.command == 'bhimport':
            from jackdaw.utils.bhimport import BHImport
            print(
                'DISCLAIMER! This feature is still beta! Bloodhound acquires way less data than Jackdaw therefore not all functionality will work after import. Any errors during import will be silently ignored, use "-vvv" verbosity level to see all errors.'
            )
            bh = BHImport.from_zipfile(args.bhfile)
            bh.db_conn = db_conn
            if args.verbose > 1:
                bh.set_debug(True)
            bh.run()
            print('Import complete!')

    except Exception as e:
        jdlogger.exception('main')
Exemplo n.º 21
0
async def run_auto(ldap_worker_cnt=None,
                   smb_worker_cnt=500,
                   dns=None,
                   work_dir='./workdir',
                   db_conn=None,
                   show_progress=True,
                   no_work_dir=False):
    try:
        if platform.system() != 'Windows':
            raise Exception('auto mode only works on windows!')

        smblogger.setLevel(100)
        from winacl.functions.highlevel import get_logon_info
        logon = get_logon_info()

        jdlogger.debug(str(logon))
        if logon['domain'] == '' or logon['logonserver'] == '':
            if logon['domain'] == '':
                logon['domain'] = os.environ['USERDOMAIN']
            if logon['logonserver'] == '':
                logon['logonserver'] = os.environ['LOGONSERVER'].replace(
                    '\\', '')

            if logon['domain'] == '' or logon['logonserver'] == '':
                return False, Exception(
                    "Failed to find user's settings! Is this a domain user?")

        try:
            #checking connection can be made over ldap...
            reader, writer = await asyncio.wait_for(
                asyncio.open_connection(logon['logonserver'], 389), 2)
            writer.close()
        except:
            return False, Exception(
                "Failed to connect to server %s over LDAP" %
                (logon['logonserver']))

        if db_conn is None:
            db_loc = '%s_%s.db' % (logon['domain'], datetime.datetime.utcnow().
                                   strftime("%Y%m%d_%H%M%S"))
            db_conn = 'sqlite:///%s' % db_loc
            create_db(db_conn)
        ldap_url = 'ldap+sspi-ntlm://%s\\%s:jackdaw@%s' % (
            logon['domain'], logon['username'], logon['logonserver'])
        smb_url = 'smb2+sspi-kerberos://%s\\%s:jackdaw@%s' % (
            logon['domain'], logon['username'], logon['logonserver'])

        jdlogger.debug('LDAP connection: %s' % ldap_url)
        jdlogger.debug('SMB  connection: %s' % smb_url)
        if dns is None:
            from jackdaw.gatherer.rdns.dnstest import get_correct_dns_win
            srv_domain = '%s.%s' % (logon['logonserver'],
                                    logon['dnsdomainname'])
            dns = await get_correct_dns_win(srv_domain)
            if dns is None:
                jdlogger.debug('Failed to identify DNS server!')
            else:
                dns = str(dns)
                jdlogger.debug('DNS server selected: %s' % str(dns))

        kerb_url = 'auto'
        with multiprocessing.Pool() as mp_pool:
            gatherer = Gatherer(db_conn,
                                work_dir,
                                ldap_url,
                                smb_url,
                                kerb_url=kerb_url,
                                ldap_worker_cnt=ldap_worker_cnt,
                                smb_worker_cnt=smb_worker_cnt,
                                mp_pool=mp_pool,
                                smb_gather_types=['all'],
                                progress_queue=None,
                                show_progress=show_progress,
                                calc_edges=True,
                                dns=dns,
                                no_work_dir=no_work_dir)
            res, err = await gatherer.run()
            if err is not None:
                raise err
            return True, None
    except Exception as e:
        return False, e
Exemplo n.º 22
0
    async def run(self, args):

        from aiosmb import logger as smblog

        if args.verbose == 0:
            smblog.setLevel(100)
        elif args.verbose == 1:
            smblog.setLevel(level=logging.INFO)
        else:
            level = 5 - args.verbose
            smblog.setLevel(level=level)

        if args.smb_module == 'lsassfile':
            from pypykatz.smb.lsassutils import lsassfile
            mimi = await lsassfile(args.url)
            self.process_results({'smbfile': mimi}, [], args)

        elif args.smb_module == 'lsassdump':
            from pypykatz.smb.lsassutils import lsassdump
            mimi = await lsassdump(args.url)
            self.process_results({'smbfile': mimi}, [], args)

        elif args.smb_module == 'secretsdump':
            from pypykatz.smb.lsassutils import lsassdump
            from pypykatz.smb.regutils import regdump
            from pypykatz.smb.dcsync import dcsync

            try:
                mimi = await lsassdump(args.url)
                if mimi is not None:
                    self.process_results({'smbfile': mimi}, [],
                                         args,
                                         file_prefix='_lsass.txt')
            except Exception as e:
                logging.exception('[SECRETSDUMP] Failed to get LSASS secrets')

            try:
                po = await regdump(args.url)
                if po is not None:
                    if args.outfile:
                        po.to_file(args.outfile + '_registry.txt', args.json)
                    else:
                        if args.json:
                            print(
                                json.dumps(po.to_dict(),
                                           cls=UniversalEncoder,
                                           indent=4,
                                           sort_keys=True))
                        else:
                            print(str(po))
            except Exception as e:
                logging.exception(
                    '[SECRETSDUMP] Failed to get registry secrets')

            try:
                if args.outfile is not None:
                    outfile = open(args.outfile + '_dcsync.txt',
                                   'w',
                                   newline='')

                async for secret in dcsync(args.url):
                    if args.outfile is not None:
                        outfile.write(str(secret))
                    else:
                        print(str(secret))

            except Exception as e:
                logging.exception('[SECRETSDUMP] Failed to perform DCSYNC')
            finally:
                if args.outfile is not None:
                    outfile.close()

        elif args.smb_module == 'dcsync':
            from pypykatz.smb.dcsync import dcsync

            if args.outfile is not None:
                outfile = open(args.outfile, 'w', newline='')

            async for secret in dcsync(args.url, args.username):
                if args.outfile is not None:
                    outfile.write(str(secret))
                else:
                    print(str(secret))

            if args.outfile is not None:
                outfile.close()

        elif args.smb_module == 'regdump':
            from pypykatz.smb.regutils import regdump
            po = await regdump(args.url)

            if po is not None:
                if args.outfile:
                    po.to_file(args.outfile, args.json)
                else:
                    if args.json:
                        print(
                            json.dumps(po.to_dict(),
                                       cls=UniversalEncoder,
                                       indent=4,
                                       sort_keys=True))
                    else:
                        print(str(po))

        elif args.smb_module == 'regfile':
            from pypykatz.smb.regutils import regfile
            po = await regfile(args.url,
                               args.system,
                               sam=args.sam,
                               security=args.security,
                               software=args.software)

            if po is not None:
                if args.outfile:
                    po.to_file(args.outfile, args.json)
                else:
                    if args.json:
                        print(
                            json.dumps(po.to_dict(),
                                       cls=UniversalEncoder,
                                       indent=4,
                                       sort_keys=True))
                    else:
                        print(str(po))

        elif args.smb_module == 'console':
            from aiosmb.examples.smbclient import amain
            la = SMBCMDArgs()
            la.smb_url = args.url
            la.verbose = args.verbose
            if args.commands is not None and len(args.commands) > 0:
                la.commands = []
                if args.commands[0] == 'help':
                    la.commands = ['help']
                else:
                    if args.commands[0] != 'login':
                        la.commands.append('login')

                    for command in args.commands:
                        la.commands.append(command)

            await amain(la)