def create(portfwdtype=None, lhost=None, lport=None, rhost=None, rport=None, sessionid=None): # 获取不同转发的默认参数 flag, context = PortFwd._check_host_port(portfwdtype, lhost, lport, rhost, rport) if flag is not True: return context # flag, lportsstr = is_empty_ports(lportint) # if flag is not True: # # 端口已占用 # context = dict_data_return(CODE, CODE_MSG.get(CODE), {}) # return context opts = {'TYPE': portfwdtype, 'LHOST': lhost, 'LPORT': lport, 'RHOST': rhost, 'RPORT': rport, 'SESSION': sessionid, 'CMD': 'add'} result = MSFModule.run(module_type="post", mname="multi/manage/portfwd_api", opts=opts) if result is None: context = data_return(308, PORTFWD_MSG.get(308), {}) return context try: result_dict = json.loads(result) except Exception as E: logger.warning(E) context = data_return(301, PORTFWD_MSG.get(301), []) return context if result_dict.get('status') is True: Notice.send_success(f"新增端口转发 SID:{sessionid} {portfwdtype} {lhost}/{lport} {rhost}/{rport}") context = data_return(201, PORTFWD_MSG.get(201), result_dict.get('data')) return context else: context = data_return(301, PORTFWD_MSG.get(301), []) return context
def destory(socks_type=None, jobid=None): if socks_type == "msf_socks4a": flag = Job.destroy(jobid) if flag: if Job.is_msf_job_alive(jobid) is not True: Notice.send_success( "删除msf_socks4a代理 JobID:{}".format(jobid)) context = data_return(204, Socks_MSG.get(204), {}) else: context = data_return(304, Socks_MSG.get(304), {}) else: context = data_return(304, Socks_MSG.get(304), {}) return context elif socks_type == "msf_socks5": flag = Job.destroy(jobid) if flag: if Job.is_msf_job_alive(jobid) is not True: Notice.send_success( "删除msf_socks5代理 JobID:{}".format(jobid)) context = data_return(204, Socks_MSG.get(204), {}) else: context = data_return(304, Socks_MSG.get(304), {}) else: context = data_return(304, Socks_MSG.get(404), {}) return context
def destroy(sessionid=None): if sessionid is None or sessionid <= 0: context = data_return(304, Session_MSG.get(304), {}) return context else: params = [sessionid] try: result = RpcClient.call(Method.SessionStop, params, timeout=12) if result is None: # 删除超时 Notice.send_success( f"{Session_MSG.get(202)} SID: {sessionid}") context = data_return(202, Session_MSG.get(202), {}) return context elif result.get('result') == 'success': Notice.send_success( f"{Session_MSG.get(201)} SID: {sessionid}") context = data_return(201, Session_MSG.get(201), {}) return context else: Notice.send_warning( f"{Session_MSG.get(301)} SID: {sessionid}") context = data_return(301, Session_MSG.get(301), {}) return context except Exception as E: logger.error(E) Notice.send_warning(f"{Session_MSG.get(301)} SID: {sessionid}") context = data_return(301, Session_MSG.get(301), {}) return context
def store_result_from_sub(message=None): # 回调报文数据格式 # { # 'job_id': None, # 'uuid': '1b1a1ac0-95db-0137-5103-000c2966078a', # 'status': True, # 'message': None, # 'data': {'WHOAMI': 'nt authority\\system', 'IS_SYSTEM': True, } # } body = message.get('data') # 解析报文 try: msf_module_return_dict = json.loads(body) except Exception as E: logger.error(E) return False # 获取对应模块实例 try: req = Xcache.get_module_task_by_uuid(task_uuid=msf_module_return_dict.get("uuid")) except Exception as E: logger.error(E) return False if req is None: logger.error("未找到请求模块实例") logger.error(msf_module_return_dict) return False module_intent = req.get('module') if module_intent is None: logger.error("获取模块失败,body: {}".format(msf_module_return_dict)) return False # 调用回调函数 try: logger.warning(f"模块回调:{module_intent.NAME} " f"job_id: {msf_module_return_dict.get('job_id')} " f"uuid: {msf_module_return_dict.get('uuid')}") module_intent._clean_log() # 清理历史结果 except Exception as E: logger.error(E) return False try: module_intent.callback(status=msf_module_return_dict.get("status"), message=msf_module_return_dict.get("message"), data=msf_module_return_dict.get("data")) except Exception as E: Notice.send_error("模块 {} 的回调函数callhack运行异常".format(module_intent.NAME)) logger.error(E) try: module_intent._store_result_in_history() # 存储到历史记录 except Exception as E: logger.error(E) Xcache.del_module_task_by_uuid(task_uuid=msf_module_return_dict.get("uuid")) # 清理缓存信息 Notice.send_success("模块: {} {} 执行完成".format(module_intent.NAME, module_intent._target_str))
def create(socks_type=None, port=None): if socks_type == "msf_socks4a": opts = {'SRVHOST': '0.0.0.0', 'SRVPORT': port} flag, lportsstr = is_empty_ports(port) if flag is not True: # 端口已占用 context = data_return(408, CODE_MSG.get(408), {}) return context result = MSFModule.run(module_type="auxiliary", mname="server/socks4a_api", opts=opts, runasjob=True) if isinstance(result, dict) is not True or result.get('job_id') is None: opts['job_id'] = None context = data_return(303, Socks_MSG.get(303), opts) else: job_id = int(result.get('job_id')) if Job.is_msf_job_alive(job_id): opts['job_id'] = int(result.get('job_id')) Notice.send_success("新建msf_socks4a代理成功,Port: {}".format( opts.get('SRVPORT'), opts.get('job_id'))) context = data_return(201, Socks_MSG.get(201), opts) else: context = data_return(306, Socks_MSG.get(306), opts) return context elif socks_type == "msf_socks5": opts = {'SRVHOST': '0.0.0.0', 'SRVPORT': port} flag, lportsstr = is_empty_ports(port) if flag is not True: # 端口已占用 context = data_return(408, CODE_MSG.get(408), {}) return context result = MSFModule.run(module_type="auxiliary", mname="server/socks5_api", opts=opts, runasjob=True) if isinstance(result, dict) is not True or result.get('job_id') is None: opts['job_id'] = None context = data_return(303, Socks_MSG.get(303), opts) else: job_id = int(result.get('job_id')) if Job.is_msf_job_alive(job_id): opts['job_id'] = int(result.get('job_id')) Notice.send_success("新建msf_socks5代理成功,Port: {}".format( opts.get('SRVPORT'), opts.get('job_id'))) context = data_return(201, Socks_MSG.get(201), opts) else: context = data_return(306, Socks_MSG.get(306), opts) return context
def store_executed_result(task_uuid=None): req = Xcache.get_module_task_by_uuid(task_uuid=task_uuid) if req is None: logger.warning("缓存中无对应实例,可能已经模块已经中途退出") return False module_common_instance = req.get("module") # 存储运行结果 try: module_common_instance._store_result_in_history() Notice.send_success( "模块: {} {} 执行完成".format(module_common_instance.NAME, module_common_instance.target_str)) logger.warning("多模块实例执行完成:{}".format(module_common_instance.NAME)) Xcache.del_module_task_by_uuid(task_uuid=task_uuid) # 清理缓存信息 return True except Exception as E: Xcache.del_module_task_by_uuid(task_uuid=task_uuid) # 清理缓存信息 logger.error("多模块实例执行异常:{} 异常信息: {}".format(module_common_instance.NAME, E)) Notice.send_exception("模块: {} 执行异常,异常信息: {}".format(module_common_instance.NAME, E)) logger.error(E) return False
def create(subnet=None, netmask=None, sessionid=None, autoroute=None): if autoroute is True: # 调用autoroute opts = {'CMD': 'autoadd', 'SESSION': sessionid} else: opts = { 'CMD': 'add', 'SUBNET': subnet, 'NETMASK': netmask, 'SESSION': sessionid } result = MSFModule.run(module_type="post", mname="multi/manage/routeapi", opts=opts) if result is None: context = data_return(505, CODE_MSG.get(505), []) return context try: result_dict = json.loads(result) except Exception as E: logger.warning(E) context = data_return(306, Route_MSG.get(306), []) return context if result_dict.get('status') is True: if isinstance(result_dict.get('data'), list): if autoroute: Notice.send_success(f"新增路由,SID:{sessionid} 自动模式") else: Notice.send_success( f"新增路由,SID:{sessionid} {subnet}/{netmask}") context = data_return(201, Route_MSG.get(201), result_dict.get('data')) else: context = data_return(305, Route_MSG.get(305), []) return context else: context = data_return(305, Route_MSG.get(305), []) return context
def start(self): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 47200)) except socket.error: logger.warning("MainMonitor 已经启动,请勿重复启动") return # 获取缓存监听 handler_list = Xcache.get_cache_handlers() # Xcache初始化部分 Xcache.init_xcache_on_start() # 加载模块配置信息 PostModuleConfig.load_all_modules_config() # 关闭apscheduler的警告 log = logging.getLogger('apscheduler.scheduler') log.setLevel(logging.ERROR) self.MainScheduler = BackgroundScheduler() # msf模块result数据监听线程 self.MainScheduler.add_job(func=self.sub_msf_module_result_thread, max_instances=1, trigger='interval', seconds=1, id='sub_msf_module_result_thread') # msf模块data数据监听线程 self.MainScheduler.add_job(func=self.sub_msf_module_data_thread, max_instances=1, trigger='interval', seconds=1, id='sub_msf_module_data_thread') # msf模块log数据监听线程 self.MainScheduler.add_job(func=self.sub_msf_module_log_thread, max_instances=1, trigger='interval', seconds=1, id='sub_msf_module_log_thread') # 心跳线程 self.MainScheduler.add_job(func=self.sub_heartbeat_thread, max_instances=1, trigger='interval', seconds=1, id='sub_heartbeat_thread') # send_sms线程 self.MainScheduler.add_job(func=self.sub_send_sms_thread, max_instances=1, trigger='interval', seconds=1, id='sub_send_sms_thread') # bot 运行测试线程 self.MainScheduler.add_job(func=self.run_bot_wait_list, max_instances=1, trigger='interval', seconds=1, id='run_bot_wait_list') # 恢复上次运行保存的监听 self.MainScheduler.add_job(func=Handler.recovery_cache_last_handler, trigger='date', next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=15), args=[handler_list], id='recovery_cache_last_handler') self.MainScheduler.start() logger.warning("后台服务启动成功") Notice.send_success(f"后台服务启动成功,15秒后开始加载历史监听.")
def create(sessionid=None, handler=None): # 获取不同转发的默认参数 try: handleropts = json.loads(handler) except Exception as E: logger.warning(E) context = data_return(303, TRANSPORT_MSG.get(303), []) return context opts = { "uuid": None, "transport": None, "lhost": None, "lport": None, "ua": None, "proxy_host": None, "proxy_port": None, "proxy_type": None, "proxy_user": None, "proxy_pass": None, "comm_timeout": None, "session_exp": None, "retry_total": None, "retry_wait": None, "cert": None, "luri": None, } handler_payload = handleropts.get("PAYLOAD") if "reverse_tcp" in handler_payload: opts["transport"] = "reverse_tcp" elif "reverse_https" in handler_payload: opts["transport"] = "reverse_https" elif "reverse_http" in handler_payload: opts["transport"] = "reverse_http" elif "bind_tcp" in handler_payload: opts["transport"] = "bind_tcp" else: context = data_return(303, TRANSPORT_MSG.get(303), []) return context opts["uuid"] = handleropts.get("PayloadUUIDSeed") opts["lhost"] = handleropts.get("LHOST") opts["lport"] = handleropts.get("LPORT") opts["ua"] = handleropts.get("HttpUserAgent") opts["proxy_host"] = handleropts.get("HttpProxyHost") opts["proxy_port"] = handleropts.get("HttpProxyPort") opts["proxy_type"] = handleropts.get("HttpProxyType") opts["proxy_user"] = handleropts.get("HttpProxyUser") opts["proxy_pass"] = handleropts.get("HttpProxyPass") opts["comm_timeout"] = handleropts.get("SessionCommunicationTimeout") opts["session_exp"] = handleropts.get("SessionExpirationTimeout") opts["retry_total"] = handleropts.get("SessionRetryTotal") opts["retry_wait"] = handleropts.get("SessionRetryWait") opts["cert"] = handleropts.get("HandlerSSLCert") opts["luri"] = handleropts.get("LURI") result_flag = RpcClient.call(Method.SessionMeterpreterTransportAdd, [sessionid, opts]) if result_flag: Notice.send_success(f"新增传输 SID:{sessionid}") context = data_return(201, TRANSPORT_MSG.get(201), {}) return context else: context = data_return(301, TRANSPORT_MSG.get(301), []) return context
def load_all_modules_config(): all_modules_config = [] # viper 内置模块 viper_module_count = 0 modulenames = os.listdir(os.path.join(settings.BASE_DIR, 'MODULES')) for modulename in modulenames: modulename = modulename.split(".")[0] if modulename == "__init__" or modulename == "__pycache__": # __init__.py的特殊处理 continue class_intent = importlib.import_module(f'MODULES.{modulename}') try: if isinstance(class_intent.PostModule.ATTCK, str): attck = [class_intent.PostModule.ATTCK] elif isinstance(class_intent.PostModule.ATTCK, list): attck = [class_intent.PostModule.ATTCK] else: attck = [] one_module_config = { "BROKER": class_intent.PostModule.MODULE_BROKER, # 处理器 "NAME": class_intent.PostModule.NAME, "DESC": class_intent.PostModule.DESC, "WARN": class_intent.PostModule.WARN, "AUTHOR": class_intent.PostModule.AUTHOR, "REFERENCES": class_intent.PostModule.REFERENCES, "README": class_intent.PostModule.README, "MODULETYPE": class_intent.PostModule.MODULETYPE, "OPTIONS": class_intent.PostModule.OPTIONS, "loadpath": 'MODULES.{}'.format(modulename), # post类配置 "REQUIRE_SESSION": class_intent.PostModule.REQUIRE_SESSION, "PLATFORM": class_intent.PostModule.PLATFORM, "PERMISSIONS": class_intent.PostModule.PERMISSIONS, "ATTCK": attck, # bot类配置 "SEARCH": class_intent.PostModule.SEARCH, } all_modules_config.append(one_module_config) viper_module_count += 1 except Exception as E: logger.error(E) continue logger.warning("内置模块加载完成,加载{}个模块".format(viper_module_count)) Notice.send_success(f"内置模块加载完成,加载{viper_module_count}个模块") # 自定义模块 diy_module_count = 0 modulenames = os.listdir( os.path.join(settings.BASE_DIR, 'Docker', "module")) for modulename in modulenames: modulename = modulename.split(".")[0] if modulename == "__init__" or modulename == "__pycache__": # __init__.py的特殊处理 continue try: class_intent = importlib.import_module( 'Docker.module.{}'.format(modulename)) importlib.reload(class_intent) except Exception as E: logger.exception(E) Notice.send_alert(f"加载自定义模块:{modulename} 失败") continue try: if isinstance(class_intent.PostModule.ATTCK, str): attck = [class_intent.PostModule.ATTCK] elif isinstance(class_intent.PostModule.ATTCK, list): attck = [class_intent.PostModule.ATTCK] else: attck = [] one_module_config = { "BROKER": class_intent.PostModule.MODULE_BROKER, # 处理器 "NAME": class_intent.PostModule.NAME, "DESC": class_intent.PostModule.DESC, "WARN": class_intent.PostModule.WARN, "AUTHOR": class_intent.PostModule.AUTHOR, "REFERENCES": class_intent.PostModule.REFERENCES, "README": class_intent.PostModule.README, "MODULETYPE": class_intent.PostModule.MODULETYPE, "OPTIONS": class_intent.PostModule.OPTIONS, "loadpath": 'Docker.module.{}'.format(modulename), # post类配置 "REQUIRE_SESSION": class_intent.PostModule.REQUIRE_SESSION, "PLATFORM": class_intent.PostModule.PLATFORM, "PERMISSIONS": class_intent.PostModule.PERMISSIONS, "ATTCK": attck, # bot类配置 "SEARCH": class_intent.PostModule.SEARCH, } all_modules_config.append(one_module_config) diy_module_count += 1 except Exception as E: logger.error(E) continue logger.warning("自定义模块加载完成,加载{}个模块".format(diy_module_count)) Notice.send_success(f"自定义模块加载完成,加载{diy_module_count}个模块") all_modules_config.sort(key=lambda s: (TAG2CH.get_moduletype_order( s.get('MODULETYPE')), s.get('loadpath'))) if Xcache.update_moduleconfigs(all_modules_config): return len(all_modules_config) else: return 0
def create(opts=None): # 所有的参数必须大写 # opts = {'PAYLOAD': payload, 'LHOST': LHOST, 'LPORT': LPORT, 'RHOST': RHOST} if opts.get('VIRTUALHANDLER') is True: # 虚拟监听 opts.pop('VIRTUALHANDLER') result = Handler.create_virtual_handler(opts) if result is None: opts['ID'] = None context = data_return(301, Handler_MSG.get(301), opts) else: context = data_return(201, Handler_MSG.get(201), {}) else: # 真正的监听 # 处理代理相关参数 if opts.get("proxies_proto") == "Direct" or opts.get("proxies_proto") is None: try: opts.pop('proxies_proto') except Exception as _: pass try: opts.pop('proxies_ipport') except Exception as _: pass else: proxies_proto = opts.get('proxies_proto') proxies_ipport = opts.get('proxies_ipport') opts["proxies"] = f"{proxies_proto}:{proxies_ipport}" try: opts.pop('proxies_proto') except Exception as _: pass try: opts.pop('proxies_ipport') except Exception as _: pass try: if opts.get('PAYLOAD').find("reverse") > 0: try: opts.pop('RHOST') except Exception as _: pass # 查看端口是否已占用 # lport = int(opts.get('LPORT')) # flag, lportsstr = is_empty_ports(lport) # if flag is not True: # context = dict_data_return(306, Handler_MSG.get(306), {}) # return context elif opts.get('PAYLOAD').find("bind") > 0: if opts.get('LHOST') is not None: opts.pop('LHOST') # 反向http(s)服务常驻问题特殊处理 if opts.get('PAYLOAD').find("reverse_http") or opts.get('PAYLOAD').find("reverse_winhttp"): opts['EXITONSESSION'] = False opts['KillHandlerFouce'] = True else: if opts.get('EXITONSESSION'): opts['EXITONSESSION'] = True else: opts['EXITONSESSION'] = False opts['PayloadUUIDSeed'] = str(uuid.uuid1()) except Exception as E: logger.error(E) context = data_return(500, CODE_MSG.get(500), {}) return context result = MSFModule.run(module_type="exploit", mname="multi/handler", opts=opts, runasjob=True) if isinstance(result, dict) is not True or result.get('job_id') is None: opts['ID'] = None context = data_return(301, Handler_MSG.get(301), opts) else: job_id = int(result.get('job_id')) if Job.is_msf_job_alive(job_id): opts['ID'] = int(result.get('job_id')) Notice.send_success("新建监听成功:{} {} JobID:{}".format(opts.get('PAYLOAD'), opts.get('LPORT'), result.get('job_id'))) context = data_return(201, Handler_MSG.get(201), opts) else: context = data_return(301, Handler_MSG.get(301), opts) return context
def create(kind=None, tag=None, setting=None): """创建系统配置""" if isinstance(setting, str): setting = json.loads(setting) if kind == "telegram": token = setting.get("token") chat_id = setting.get("chat_id") proxy = setting.get("proxy") if tag == "check": # 获取chat_id user_chat_id_list = Telegram.get_alive_chat_id(token, proxy) context = data_return(201, Setting_MSG.get(201), user_chat_id_list) return context else: if Settings._check_telegram_aliveable(token, chat_id, proxy) is not True: data = { "token": token, "chat_id": chat_id, "proxy": proxy, "alive": False } Xcache.set_telegram_conf(data) context = data_return(303, Setting_MSG.get(303), data) return context else: Notice.send_success("设置Telegram通知成功") data = { "token": token, "chat_id": chat_id, "proxy": proxy, "alive": True } Xcache.set_telegram_conf(data) context = data_return(202, Setting_MSG.get(202), data) return context elif kind == "dingding": access_token = setting.get("access_token") keyword = setting.get("keyword") if Settings._check_dingding_aliveable(access_token, keyword) is not True: data = { "access_token": access_token, "keyword": keyword, "alive": False } Xcache.set_dingding_conf(data) context = data_return(304, Setting_MSG.get(304), data) return context else: Notice.send_success("设置DingDing通知成功") data = { "access_token": access_token, "keyword": keyword, "alive": True } Xcache.set_dingding_conf(data) context = data_return(203, Setting_MSG.get(203), data) return context elif kind == "serverchan": sendkey = setting.get("sendkey") if Settings._check_serverchan_aliveable(sendkey) is not True: data = {"sendkey": sendkey, "alive": False} Xcache.set_serverchan_conf(data) context = data_return(305, Setting_MSG.get(305), data) return context else: Notice.send_success("设置Server酱通知成功") data = {"sendkey": sendkey, "alive": True} Xcache.set_serverchan_conf(data) context = data_return(207, Setting_MSG.get(207), data) return context elif kind == "FOFA": email = setting.get("email") key = setting.get("key") client = FOFAClient() client.set_email_and_key(email, key) if client.is_alive() is not True: data = {"email": email, "key": key, "alive": False} Xcache.set_fofa_conf(data) context = data_return(306, Setting_MSG.get(306), data) return context else: Notice.send_success("设置FOFA API 成功") data = {"email": email, "key": key, "alive": True} Xcache.set_fofa_conf(data) context = data_return(206, Setting_MSG.get(206), data) return context elif kind == "sessionmonitor": flag = setting.get("flag") Xcache.set_sessionmonitor_conf({"flag": flag}) if flag: msg = "Session监控功能已打开" Notice.send_success(msg) Notice.send_sms(msg) else: msg = "Session监控功能已关闭" Notice.send_info(msg) Notice.send_sms(msg) context = data_return(204, Setting_MSG.get(204), {"flag": flag}) return context elif kind == "lhost": Xcache.set_lhost_config(setting) Notice.send_success(f"设置回连地址成功,当前回连地址: {setting.get('lhost')}") context = data_return(205, Setting_MSG.get(205), setting) return context else: context = data_return(301, Setting_MSG.get(301), {}) return context