-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
465 lines (411 loc) · 13.6 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
package main
import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/mtnmunuklu/alterix/ioc"
"github.com/mtnmunuklu/alterix/ioc/ievaluator"
"github.com/mtnmunuklu/alterix/sigma"
"github.com/mtnmunuklu/alterix/sigma/sevaluator"
"github.com/mtnmunuklu/alterix/yara"
"github.com/mtnmunuklu/alterix/yara/yevaluator"
)
var (
filePath string
configPath string
fileContent string
configContent string
showHelp bool
outputJSON bool
outputPath string
version bool
caseSensitive bool
useSigma bool
useYara bool
useIOC bool
)
// Set up the command-line flags
func init() {
flag.StringVar(&filePath, "filepath", "", "Name or path of the file or directory to read")
flag.StringVar(&configPath, "config", "", "Path to the configuration file")
flag.StringVar(&fileContent, "filecontent", "", "Base64-encoded content of the file or directory to read")
flag.StringVar(&configContent, "configcontent", "", "Base64-encoded content of the configuration file")
flag.BoolVar(&showHelp, "help", false, "Show usage")
flag.BoolVar(&outputJSON, "json", false, "Output results in JSON format")
flag.StringVar(&outputPath, "output", "", "Output directory for writing files")
flag.BoolVar(&version, "version", false, "Show version information")
flag.BoolVar(&caseSensitive, "cs", false, "Case sensitive mode")
flag.BoolVar(&useSigma, "sigma", false, "Use Sigma rules")
flag.BoolVar(&useYara, "yara", false, "Use Yara rules")
flag.BoolVar(&useIOC, "ioc", false, "Use IOCs")
flag.Parse()
// If the version flag is provided, print version information and exit
if version {
fmt.Println("Alterix version 1.5.0")
os.Exit(1)
}
// If the help flag is provided, print usage information and exit
if showHelp {
printUsage()
os.Exit(1)
}
// Check if filepath and configpath are provided as command-line arguments
if flag.NArg() > 0 {
filePath = flag.Arg(0)
}
if flag.NArg() > 1 {
configPath = flag.Arg(1)
}
// Check if both filecontent and configcontent are provided
if (filePath == "" && fileContent == "") || (configPath == "" && configContent == "") {
fmt.Println("Please provide either file paths or file contents, and either config path or config content.")
printUsage()
os.Exit(1)
}
}
func formatSigmaJSONResult(rule sigma.Rule, queries map[int]string) []byte {
// Define a struct type named JSONResult to represent the JSON output fields.
type JSONResult struct {
Name string `json:"Name"`
Description string `json:"Description"`
Query string `json:"Query"`
InsertDate string `json:"InsertDate"`
LastUpdateDate string `json:"LastUpdateDate"`
Tags []string `json:"Tags"`
Level string `json:"Level"`
}
// Create a strings.Builder variable named query.
var query strings.Builder
for i, qry := range queries {
// Add a newline character if the index is greater than zero.
if i > 0 {
query.WriteString("\n")
}
query.WriteString(qry)
}
// Create an instance of the JSONResult struct.
jsonResult := JSONResult{
Name: rule.Title,
Description: rule.Description + "\n\nAuthor: " + rule.Author + "\nSigma Repository: [GitHub](https://github.com/SigmaHQ/sigma)",
Query: query.String(),
InsertDate: time.Now().UTC().Format(time.RFC3339),
LastUpdateDate: time.Now().UTC().Format(time.RFC3339),
Tags: rule.Tags,
Level: rule.Level,
}
// Marshal the JSONResult struct into JSON data.
jsonData, err := json.MarshalIndent(jsonResult, "", " ")
if err != nil {
fmt.Println("Error encoding JSON:", err)
return nil
}
return jsonData
}
func formatYaraJSONResult(title, query string, tags []string, metas map[string]string) []byte {
// Define a struct type named JSONResult to represent the JSON output fields.
type JSONResult struct {
Name string `json:"Name"`
Description string `json:"Description"`
Query string `json:"Query"`
InsertDate string `json:"InsertDate"`
LastUpdateDate string `json:"LastUpdateDate"`
Tags []string `json:"Tags"`
Level string `json:"Level"`
}
// Convert the keys in metas map to lowercase
lowercaseMetas := make(map[string]string)
for key, value := range metas {
lowercaseMetas[strings.ToLower(key)] = value
}
// Check if the "description" and "author" fields are present in the lowercaseMetas map
var description, author string
if val, ok := lowercaseMetas["description"]; ok {
description = val
}
if val, ok := lowercaseMetas["author"]; ok {
author = val
}
// Create an instance of the JSONResult struct.
jsonResult := JSONResult{
Name: title,
Description: description + "\n\nAuthor: " + author,
Query: query,
InsertDate: time.Now().UTC().Format(time.RFC3339),
LastUpdateDate: time.Now().UTC().Format(time.RFC3339),
Tags: tags,
Level: "",
}
// Marshal the JSONResult struct into JSON data.
jsonData, err := json.MarshalIndent(jsonResult, "", " ")
if err != nil {
fmt.Println("Error encoding JSON:", err)
return nil
}
return jsonData
}
func formatIOCJSONResult(tags []string, query, name, description, level string) []byte {
// Define a struct type named JSONResult to represent the JSON output fields.
type JSONResult struct {
Name string `json:"Name"`
Description string `json:"Description"`
Query string `json:"Query"`
InsertDate string `json:"InsertDate"`
LastUpdateDate string `json:"LastUpdateDate"`
Tags []string `json:"Tags"`
Level string `json:"Level"`
}
// Create an instance of the JSONResult struct.
jsonResult := JSONResult{
Name: name,
Description: description,
Query: query,
InsertDate: time.Now().UTC().Format(time.RFC3339),
LastUpdateDate: time.Now().UTC().Format(time.RFC3339),
Tags: tags,
Level: level,
}
// Marshal the JSONResult struct into JSON data.
jsonData, err := json.MarshalIndent(jsonResult, "", " ")
if err != nil {
fmt.Println("Error encoding JSON:", err)
return nil
}
return jsonData
}
func printUsage() {
fmt.Println("Usage: alterix -sigma/-yara/-ioc -filepath <path> -config <path> [flags]")
fmt.Println("Flags:")
flag.PrintDefaults()
fmt.Println("Example:")
fmt.Println(" alterix -sigma/-yara/-ioc -filepath /path/to/file -config /path/to/config")
}
func main() {
// Ensure either Sigma or Yara flag is provided
if !useSigma && !useYara && !useIOC {
fmt.Println("Please provide either -sigma, -yara or -ioc flag to specify the type of rules.")
printUsage()
os.Exit(1)
}
// Read the contents of the file(s) specified by the filepath flag or filecontent flag
fileContents := make(map[string][]byte)
var err error
// Check if file paths are provided
if filePath != "" {
// Check if the filepath is a directory
fileInfo, err := os.Stat(filePath)
if err != nil {
fmt.Println("Error getting file/directory info:", err)
return
}
if fileInfo.IsDir() {
// filePath is a directory, so walk the directory to read all the files inside it
filepath.Walk(filePath, func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Println("Error accessing file:", err)
return nil
}
if !info.IsDir() {
// read file content
content, err := os.ReadFile(path)
if err != nil {
fmt.Println("Error reading file:", err)
return nil
}
fileContents[path] = content
}
return nil
})
} else {
// filePath is a file, so read its contents
fileContents[filePath], err = os.ReadFile(filePath)
if err != nil {
fmt.Println("Error reading file:", err)
return
}
}
} else if fileContent != "" {
// Check if the filecontent is a directory
lines := strings.Split(fileContent, "\n")
if len(lines) > 1 {
// fileContent is a directory, so read all lines as separate files
for _, line := range lines {
// decode base64 content
decodedContent, err := base64.StdEncoding.DecodeString(line)
if err != nil {
fmt.Println("Error decoding base64 content:", err)
return
}
fileContents[line] = decodedContent
}
} else {
// fileContent is a file, so read its content
// decode base64 content
decodedContent, err := base64.StdEncoding.DecodeString(fileContent)
if err != nil {
fmt.Println("Error decoding base64 content:", err)
return
}
fileContents["filecontent"] = decodedContent
}
}
// Read the contents of the configuration file or use configcontent
var configContents []byte
if configPath != "" {
configContents, err = os.ReadFile(configPath)
if err != nil {
fmt.Println("Error reading configuration file:", err)
return
}
} else if configContent != "" {
// decode base64 content
decodedContent, err := base64.StdEncoding.DecodeString(configContent)
if err != nil {
fmt.Println("Error decoding base64 content:", err)
return
}
configContents = decodedContent
}
// Loop over each file and parse its contents as a Sigma rule
for _, fileContent := range fileContents {
if useSigma {
sigmaRule, err := sigma.ParseRule(fileContent)
if err != nil {
fmt.Println("Error parsing rule:", err)
continue
}
// Parse the configuration file as a Sigma config
config, err := sigma.ParseConfig(configContents)
if err != nil {
fmt.Println("Error parsing config:", err)
continue
}
var sr *sevaluator.RuleEvaluator
if caseSensitive {
// Evaluate the Sigma rule against the config using case sensitive mode
sr = sevaluator.ForRule(sigmaRule, sevaluator.WithConfig(config), sevaluator.CaseSensitive)
} else {
// Evaluate the Sigma rule against the config
sr = sevaluator.ForRule(sigmaRule, sevaluator.WithConfig(config))
}
result, err := sr.Alters()
if err != nil {
fmt.Println("Error converting rule:", err)
continue
}
var output string
// Print the results of the query
if outputJSON {
jsonResult := formatSigmaJSONResult(sigmaRule, result.QueryResults)
output = string(jsonResult)
} else {
var builder strings.Builder
for _, queryResult := range result.QueryResults {
builder.WriteString(queryResult + "\n")
}
output = builder.String()
}
// Check if outputPath is provided
if outputPath != "" {
// Create the output file path using the Name field from the rule
outputFilePath := filepath.Join(outputPath, fmt.Sprintf("%s.json", sigmaRule.Title))
// Write the output string to the output file
err := os.WriteFile(outputFilePath, []byte(output), 0644)
if err != nil {
fmt.Println("Error writing output to file:", err)
continue
}
fmt.Printf("Output for rule '%s' written to file: %s\n", sigmaRule.Title, outputFilePath)
} else {
fmt.Printf("%s", output)
}
} else if useYara {
yaraRuleSet, err := yara.ParseRule(fileContent)
if err != nil {
fmt.Println("Error parsing rule:", err)
continue
}
// Parse the configuration file as a Yara config
config, err := yara.ParseConfig(configContents)
if err != nil {
fmt.Println("Error parsing config:", err)
continue
}
for _, yaraRule := range yaraRuleSet.Rules {
// Evaluate the Yara rule against the config
yr := yevaluator.ForRule(yaraRule, yevaluator.WithConfig(config))
result, err := yr.Alters()
if err != nil {
fmt.Println("Error converting rule:", err)
continue
}
var output string
// Print the results of the query
if outputJSON {
jsonResult := formatYaraJSONResult(yaraRule.Identifier, result.QueryResult, yaraRule.Tags, result.MetaResults)
output = string(jsonResult)
} else {
output = result.QueryResult
}
// Check if outputPath is provided
if outputPath != "" {
// Create the output file path using the Name field from the rule
outputFilePath := filepath.Join(outputPath, fmt.Sprintf("%s.json", yaraRule.Identifier))
// Write the output string to the output file
err := os.WriteFile(outputFilePath, []byte(output), 0644)
if err != nil {
fmt.Println("Error writing output to file:", err)
continue
}
fmt.Printf("Output for rule '%s' written to file: %s\n", yaraRule.Identifier, outputFilePath)
} else {
fmt.Printf("%s", output)
}
}
} else if useIOC {
iocs, err := ioc.ParseIOC(fileContent)
if err != nil {
fmt.Println("Error parsing rule:", err)
continue
}
// Parse the configuration file as a IOC config
config, err := ioc.ParseConfig(configContents)
if err != nil {
fmt.Println("Error parsing config:", err)
continue
}
ir := ievaluator.ForIOC(iocs, ievaluator.WithConfig(config))
result, err := ir.Alters()
if err != nil {
fmt.Println("Error converting rule:", err)
continue
}
var output string
// Print the results of the query
if outputJSON {
jsonResult := formatIOCJSONResult(result.Tags, result.QueryResult, "IOC Rule "+strings.Join(result.Tags, ", "), "", "info")
output = string(jsonResult)
} else {
output = result.QueryResult
}
// Check if outputPath is provided
if outputPath != "" {
// Create the output file path using the Name field from the rule
outputFilePath := filepath.Join(outputPath, fmt.Sprintf("%s.json", "IOC Rule "+strings.Join(result.Tags, ", ")))
// Write the output string to the output file
err := os.WriteFile(outputFilePath, []byte(output), 0644)
if err != nil {
fmt.Println("Error writing output to file:", err)
continue
}
fmt.Printf("Output for rule '%s' written to file: %s\n", "IOC Rule "+strings.Join(result.Tags, ", "), outputFilePath)
} else {
fmt.Printf("%s", output)
}
}
}
}