forked from deepfence/YaraHunter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
533 lines (468 loc) · 14.7 KB
/
main.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
package main
// ------------------------------------------------------------------------------
// MIT License
// Copyright (c) 2022 deepfence
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// ------------------------------------------------------------------------------
import (
"archive/tar"
"compress/gzip"
"crypto/sha256"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/deepfence/YaRadare/core"
"github.com/deepfence/YaRadare/output"
"github.com/deepfence/YaRadare/scan"
"github.com/deepfence/YaRadare/server"
"github.com/fatih/color"
)
type YaraRuleDetail struct {
Built time.Time `json:"built"`
Version int `json:"version"`
URL string `json:"url"`
Checksum string `json:"checksum"`
}
type YaraRuleListingV3 struct {
V3 []YaraRuleDetail `json:"3"`
}
type YaraRuleListing struct {
Available YaraRuleListingV3 `json:"available"`
}
type YaraRuleUpdater struct {
yaraRuleListingJson YaraRuleListing
yaraRulePath string
downloadYaraRulePath string
currentFileChecksum string
currentFilePath string
sync.RWMutex
}
const (
PLUGIN_NAME = "MalwareScanner"
)
// Read the regex signatures from config file, options etc.
// and setup the session to start scanning for IOC
var session = core.GetSession()
var wg sync.WaitGroup
// Scan a container image for IOC layer by layer
// @parameters
// image - Name of the container image to scan (e.g. "alpine:3.5")
// @returns
// Error, if any. Otherwise, returns nil
func findIOCInImage(image string) (*output.JsonImageIOCOutput, error) {
res, err := scan.ExtractAndScanImage(image)
if err != nil {
return nil, err
}
jsonImageIOCOutput := output.JsonImageIOCOutput{ImageName: image, IOC: res.IOCs}
jsonImageIOCOutput.SetTime()
jsonImageIOCOutput.SetImageId(res.ImageId)
jsonImageIOCOutput.SetIOC(res.IOCs)
jsonImageIOCOutput.PrintJsonHeader()
var isFirstIOC bool = true
output.PrintColoredIOC(res.IOCs, &isFirstIOC)
jsonImageIOCOutput.PrintJsonFooter()
return &jsonImageIOCOutput, nil
}
func sha256sum(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return fmt.Sprintf("sha256:%x", hash.Sum(nil)), nil
}
func fileExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
return false
}
func NewYaraRuleUpdater() (error, *YaraRuleUpdater) {
updater := &YaraRuleUpdater{
yaraRuleListingJson: YaraRuleListing{},
yaraRulePath: path.Join(*core.GetSession().Options.RulesPath, "metaListingData.json"),
downloadYaraRulePath: "",
}
if fileExists(updater.yaraRulePath) {
content, err := os.ReadFile(updater.yaraRulePath)
if err != nil {
return err, nil
}
err = json.Unmarshal(content, &updater)
if err != nil {
return err, nil
}
}
return nil, updater
}
func untar(d *os.File, r io.Reader) error {
gzr, err := gzip.NewReader(r)
if err != nil {
return err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
switch {
// if no more files are found return
case err == io.EOF:
return nil
// return any other error
case err != nil:
return err
// if the header is nil, just skip it (not sure how this happens)
case header == nil:
continue
}
// the target location where the dir/file should be created
// target := filepath.Join(dst, strings.Replace(header.Name,"yara-rules/", "", -1))
// fmt.Println("the target main is", header.Name,strings.Replace(header.Name,"yara-rules/", "", -1))
// fmt.Println("the target is", target)
// the following switch could also be done using fi.Mode(), not sure if there
// a benefit of using one vs. the other.
// fi := header.FileInfo()
// check the file type
switch header.Typeflag {
// if its a dir and it doesn't exist create it
// if it's a file create it
case tar.TypeReg:
//fmt.Println("the j is", header.Name)
if strings.Contains(header.Name, ".yar") {
if _, err := io.Copy(d, tr); err != nil {
session.Log.Error("copying err", err)
return err
}
// manually close here after each file operation; defering would cause each file close
// to wait until all operations have completed.
d.Close()
}
}
}
}
func createFile(dest string) (error, *os.File) {
// Create blank file
file, err := os.Create(filepath.Join(dest, "malware.yar"))
if err != nil {
return err, nil
}
return nil, file
}
func downloadFile(dUrl string, dest string) (error, string) {
//fmt.Println("the dynamic url is",dUrl)
fullUrlFile := dUrl
// Build fileName from fullPath
fileURL, err := url.Parse(fullUrlFile)
if err != nil {
return err, ""
}
//fmt.Println("the dynamic url is",fileURL)
path := fileURL.Path
segments := strings.Split(path, "/")
fileName := segments[len(segments)-1]
// Create blank file
file, err := os.Create(filepath.Join(dest, fileName))
if err != nil {
return err, ""
}
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
// Put content on file
resp, err := client.Get(fullUrlFile)
//fmt.Println(" The dynamic url is ",fileName)
if err != nil {
return err, ""
}
defer resp.Body.Close()
size, err := io.Copy(file, resp.Body)
session.Log.Debug("copied size %v", size)
if err != nil {
return err, ""
}
//fmt.Println("the dynamic url is",fileURL)
defer file.Close()
return nil, fileName
}
func writeToFile(dUrl string, dest string) error {
fullUrlFile := dUrl
// Build fileName from fullPath
fileURL, err := url.Parse(fullUrlFile)
if err != nil {
return err
}
path := fileURL.Path
segments := strings.Split(path, "/")
fileName := segments[len(segments)-1]
// Create blank file
file, err := os.Create(filepath.Join(dest, fileName))
if err != nil {
return err
}
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
// Put content on file
resp, err := client.Get(fullUrlFile)
if err != nil {
return err
}
defer resp.Body.Close()
size, err := io.Copy(file, resp.Body)
session.Log.Debug("copied size %v", size)
if err != nil {
return err
}
defer file.Close()
return nil
}
func runYaraUpdate() error {
err, yaraRuleUpdater := NewYaraRuleUpdater()
if err != nil {
core.GetSession().Log.Error("main: failed to serve: %v", err)
return err
}
downloadError, _ := downloadFile("https://threat-intel.deepfence.io/yara-rules/listing.json", *core.GetSession().Options.ConfigPath)
if downloadError != nil {
core.GetSession().Log.Error("main: failed to serve: %v", downloadError)
return err
}
content, err := os.ReadFile(filepath.Join(*core.GetSession().Options.ConfigPath, "/listing.json"))
if err != nil {
core.GetSession().Log.Error("main: failed to serve: %v", err)
return err
}
var yaraRuleListingJson YaraRuleListing
err = json.Unmarshal(content, &yaraRuleListingJson)
if err != nil {
core.GetSession().Log.Error("main: failed to serve: %v", err)
return err
}
if len(yaraRuleListingJson.Available.V3) > 0 {
if yaraRuleListingJson.Available.V3[0].Checksum != yaraRuleUpdater.currentFileChecksum {
yaraRuleUpdater.currentFileChecksum = yaraRuleListingJson.Available.V3[0].Checksum
file, _ := json.MarshalIndent(yaraRuleUpdater, "", " ")
writeErr := os.WriteFile(path.Join(*core.GetSession().Options.RulesPath, "metaListingData.json"), file, 0644)
if writeErr != nil {
core.GetSession().Log.Error("main: failed to serve: %v", writeErr)
return writeErr
}
downloadError, fileName := downloadFile(yaraRuleListingJson.Available.V3[0].URL, *core.GetSession().Options.ConfigPath)
//fmt.Println("reached here 5 times", fileName)
if downloadError != nil {
core.GetSession().Log.Error("main: failed to serve: %v", downloadError)
return downloadError
}
if fileExists(filepath.Join(*core.GetSession().Options.ConfigPath, fileName)) {
readFile, readErr := os.OpenFile(filepath.Join(*core.GetSession().Options.ConfigPath, fileName), os.O_CREATE|os.O_RDWR, 0755)
if readErr != nil {
core.GetSession().Log.Error("main: failed to serve: %v", readErr)
return readErr
}
createErr, newFile := createFile(*core.GetSession().Options.ConfigPath)
if createErr != nil {
core.GetSession().Log.Error("main: failed to create: %v", createErr)
return createErr
}
//fmt.Println("the new file created is",newFile)
unTarErr := untar(newFile, readFile)
if unTarErr != nil {
core.GetSession().Log.Error("main: failed to serve: %v", unTarErr)
return unTarErr
}
session = core.GetSession()
defer newFile.Close()
defer readFile.Close()
}
}
}
return nil
}
// Scan a directory
// @parameters
// dir - Complete path of the directory to be scanned
// @returns
// Error, if any. Otherwise, returns nil
func findIOCInDir(dir string) (*output.JsonDirIOCOutput, error) {
var tempIOCsFound []output.IOCFound
err := scan.ScanIOCInDir("", "", dir, nil, &tempIOCsFound, false)
if err != nil {
core.GetSession().Log.Error("findIOCInDir: %s", err)
return nil, err
}
dirName := *session.Options.Local
hostMountPath := *session.Options.HostMountPath
if hostMountPath != "" {
dirName = strings.TrimPrefix(dirName, hostMountPath)
}
jsonDirIOCOutput := output.JsonDirIOCOutput{DirName: dirName, IOC: tempIOCsFound}
jsonDirIOCOutput.SetTime()
jsonDirIOCOutput.PrintJsonHeader()
var isFirstIOC bool = true
output.PrintColoredIOC(jsonDirIOCOutput.IOC, &isFirstIOC)
jsonDirIOCOutput.PrintJsonFooter()
return &jsonDirIOCOutput, nil
}
// Scan a container for IOC
// @parameters
// containerId - Id of the container to scan (e.g. "0fdasf989i0")
// @returns
// Error, if any. Otherwise, returns nil
func findIOCInContainer(containerId string, containerNS string) (*output.JsonImageIOCOutput, error) {
var tempIOCsFound []output.IOCFound
tempIOCsFound, err := scan.ExtractAndScanContainer(containerId, containerNS)
if err != nil {
return nil, err
}
jsonImageIOCOutput := output.JsonImageIOCOutput{ContainerId: containerId, IOC: tempIOCsFound}
jsonImageIOCOutput.SetTime()
jsonImageIOCOutput.PrintJsonHeader()
var isFirstIOC bool = true
output.PrintColoredIOC(jsonImageIOCOutput.IOC, &isFirstIOC)
jsonImageIOCOutput.PrintJsonFooter()
return &jsonImageIOCOutput, nil
}
type IOCWriter interface {
WriteIOC(jsonFilename string) error
}
func runOnce() {
var jsonOutput IOCWriter
var err error
// Scan container image for IOC
if len(*session.Options.ImageName) > 0 {
session.Log.Info("Scanning image %s for IOC...\n", *session.Options.ImageName)
jsonOutput, err = findIOCInImage(*session.Options.ImageName)
if err != nil {
core.GetSession().Log.Error("error scanning the image: %s", err)
return
}
}
// Scan local directory for IOC
if len(*session.Options.Local) > 0 {
session.Log.Info("[*] Scanning local directory: %s\n", color.BlueString(*session.Options.Local))
jsonOutput, err = findIOCInDir(*session.Options.Local)
if err != nil {
core.GetSession().Log.Error("error scanning the dir: %s", err)
return
}
}
// Scan existing container for IOC
if len(*session.Options.ContainerId) > 0 {
session.Log.Info("Scanning container %s for IOC...\n", *session.Options.ContainerId)
jsonOutput, err = findIOCInContainer(*session.Options.ContainerId, *session.Options.ContainerNS)
if err != nil {
core.GetSession().Log.Error("error scanning the container: %s", err)
return
}
}
if jsonOutput == nil {
core.GetSession().Log.Error("set either -local or -image-name flag")
return
}
jsonFilename, err := core.GetJsonFilepath()
if err != nil {
core.GetSession().Log.Error("error while retrieving json output: %s", err)
return
}
if jsonFilename != "" {
err = jsonOutput.WriteIOC(jsonFilename)
if err != nil {
core.GetSession().Log.Error("error while writing IOC: %s", err)
return
}
}
}
func yaraUpdate(newwg *sync.WaitGroup) {
defer newwg.Done()
if *session.Options.SocketPath != "" && *session.Options.HttpPort != "" {
flag.Parse()
// this creates a new ticker which will
// `tick` every 1 second.
ticker := time.NewTicker(10 * time.Hour)
// for every `tick` that our `ticker`
// emits, we print `tock`
for t := range ticker.C {
core.GetSession().Log.Debug("check ticker value", t)
err := runYaraUpdate()
if err != nil {
core.GetSession().Log.Fatal("main: failed to serve: %v", err)
}
}
}
}
func yaraResults(newwg *sync.WaitGroup) {
defer newwg.Done()
flag.Parse()
err := runYaraUpdate()
if err != nil {
core.GetSession().Log.Fatal("main: failed to serve: %v", err)
}
if *session.Options.SocketPath != "" {
core.GetSession().Log.Debug("reached inside server")
//core.GetSession().Log.Info("reached inside server")
err := server.RunServer(*session.Options.SocketPath, PLUGIN_NAME)
if err != nil {
core.GetSession().Log.Fatal("main: failed to serve: %v", err)
}
//core.GetSession().Log.Info("reached at this point")
} else if *session.Options.HttpPort != "" {
core.GetSession().Log.Info("server inside port")
err := server.RunHttpServer(*session.Options.HttpPort)
if err != nil {
core.GetSession().Log.Fatal("main: failed to serve through http: %v", err)
}
} else if *session.Options.StandAloneHttpPort != "" {
core.GetSession().Log.Info("server inside port")
err := server.RunStandaloneHttpServer(*session.Options.StandAloneHttpPort)
if err != nil {
core.GetSession().Log.Fatal("main: failed to serve through http: %v", err)
}
} else {
runOnce()
}
}
func main() {
//fmt.Println(" Welcome to concurrency")
wg.Add(2)
go yaraUpdate(&wg)
go yaraResults(&wg)
//fmt.Println("Waiting To Finish")
wg.Wait()
//fmt.Println("\nTerminating Program")
//f2(<-out1, <-out2)
}