-
Notifications
You must be signed in to change notification settings - Fork 28
/
utils_common.go
308 lines (252 loc) · 6.9 KB
/
utils_common.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
package main
import (
"crypto/rc4"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"io"
"net/url"
"os"
"os/user"
"path/filepath"
"strings"
"time"
)
type Env struct {
Name string
Value string
}
type DriveInfo struct {
Name string
Type uint32
}
const (
DRIVE_UNKNOWN = 0
DRIVE_NO_ROOT_DIR = 1
DRIVE_REMOVABLE = 2
DRIVE_FIXED = 3
DRIVE_REMOTE = 4
DRIVE_CDROM = 5
DRIVE_RAMDISK = 6
)
// RenderFastfinderLogo is a (useless) function displaying fastfinder logo as ascii art
func RenderFastfinderLogo() string {
txtLogo := " ___ __ ___ ___ __ ___ __ " + LineBreak
txtLogo += " |__ /\\ /__` | |__ | |\\ | | \\ |__ |__) " + LineBreak
txtLogo += " | /~~\\ .__/ | | | | \\| |__/ |___ | \\ " + LineBreak
txtLogo += " " + LineBreak
txtLogo += " 2021-2022 | Jean-Pierre GARNIER | @codeyourweb " + LineBreak
txtLogo += " https://github.com/codeyourweb/fastfinder " + LineBreak
return txtLogo
}
// RenderFastfinderVersion returns program and YARA version
func RenderFastfinderVersion() string {
return "Fastfinder version " + FASTFINDER_VERSION + " with embedded YARA version " + YARA_VERSION
}
// ExitProgram close file log handles and exit the program
func ExitProgram(code int, noWindow bool) {
if !noWindow {
message := "Press Ctrl+C to exit"
if AppStarted {
message = "[yellow]" + message
}
LogMessage(LOG_EXIT, message)
fmt.Scanln()
fmt.Print("\n\n")
}
if loggingFile != nil {
loggingFile.Close()
}
os.Exit(code)
}
// GetEnvironmentVariables return a list of environment variables in []Env slice
func GetEnvironmentVariables() (environmentVariables []Env) {
for _, item := range os.Environ() {
envPair := strings.SplitN(item, "=", 2)
env := Env{
Name: envPair[0],
Value: envPair[1],
}
environmentVariables = append(environmentVariables, env)
}
return environmentVariables
}
// RetrivesFilesFromUserPath return a []string of available files from specified path (includeFileExtensions is available only if listFiles is true)
func RetrivesFilesFromUserPath(path string, listFiles bool, includeFileExtensions []string, recursive bool) ([]string, error) {
var p []string
info, err := os.Stat(path)
if os.IsNotExist(err) {
return []string{}, errors.New("Input file not found")
}
if !info.IsDir() {
p = append(p, path)
} else {
if !recursive {
files, err := os.ReadDir(path)
if err != nil {
return []string{}, err
}
for _, f := range files {
if !(f.IsDir() == listFiles) && (len(includeFileExtensions) == 0 || Contains(includeFileExtensions, filepath.Ext(f.Name()))) {
p = append(p, path+string(os.PathSeparator)+f.Name())
}
}
} else {
err := filepath.Walk(path, func(walk string, info os.FileInfo, err error) error {
if err != nil {
LogMessage(LOG_ERROR, "(ERROR)", err)
}
if err == nil && !(info.IsDir() == listFiles) && (len(includeFileExtensions) == 0 || Contains(includeFileExtensions, filepath.Ext(walk))) {
p = append(p, walk)
}
return nil
})
if err != nil {
LogMessage(LOG_ERROR, "(ERROR)", err)
}
}
}
return p, nil
}
// ListFilesRecursively returns a list of files in the specified path and its subdirectories
func ListFilesRecursively(path string, excludedPaths []string) *[]string {
var files []string
err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
if err != nil {
LogMessage(LOG_ERROR, "(ERROR)", err)
return filepath.SkipDir
}
if !f.IsDir() {
for _, excludedPath := range excludedPaths {
if len(excludedPath) > 1 && strings.HasPrefix(path, excludedPath) && len(path) > len(excludedPath) {
LogMessage(LOG_INFO, "(INFO)", "Skipping dir", path)
return filepath.SkipDir
}
}
files = append(files, path)
}
return nil
})
if err != nil {
LogMessage(LOG_ERROR, "(ERROR)", err)
}
return &files
}
// ListFilesRecursively returns a list of files in the specified path and its subdirectories
func ListDirectoryRecursively(path string, excludedPaths []string) *[]string {
var directories []string
err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
if err != nil {
LogMessage(LOG_ERROR, "(ERROR)", err)
return filepath.SkipDir
}
if f.IsDir() {
for _, excludedPath := range excludedPaths {
if len(excludedPath) > 1 && strings.HasPrefix(path, excludedPath) && len(path) > len(excludedPath) {
LogMessage(LOG_INFO, "(INFO)", "Skipping dir", path)
return filepath.SkipDir
}
}
directories = append(directories, path)
}
return nil
})
if err != nil {
LogMessage(LOG_ERROR, "(ERROR)", err)
}
return &directories
}
// FileCopy copy the specified file from src to dst path, and eventually encode its content to base64. Return copied file path
func FileCopy(src, dst string, base64Encode bool) string {
dst += fmt.Sprintf("%d_%s.fastfinder", time.Now().Unix(), filepath.Base(src))
srcFile, err := os.Open(src)
if err != nil {
LogFatal(fmt.Sprintf("%v", err))
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
LogFatal(fmt.Sprintf("%v", err))
}
defer dstFile.Close()
if base64Encode {
encoder := base64.NewEncoder(base64.StdEncoding, dstFile)
defer encoder.Close()
_, err = io.Copy(encoder, srcFile)
} else {
_, err = io.Copy(dstFile, srcFile)
}
if err != nil {
LogFatal(fmt.Sprintf("%v", err))
}
return dst
}
// Contains checks if a string is contained in a slice of strings
func Contains(s []string, str string) bool {
for i := 0; i < len(s); i++ {
if s[i] == str {
return true
}
}
return false
}
// IsValidUrl tests a string to determine if it is a well-structured url or not.
func IsValidUrl(toTest string) bool {
_, err := url.ParseRequestURI(toTest)
if err != nil {
return false
}
u, err := url.Parse(toTest)
if err != nil || u.Scheme == "" || u.Host == "" {
return false
}
return true
}
// GetHostname returns the hostname of the current machine
func GetHostname() string {
name, err := os.Hostname()
if err != nil {
return ""
}
return name
}
// GetUsername returns the current user name
func GetUsername() string {
user, err := user.Current()
if err != nil {
return ""
}
return user.Username
}
// GetCurrentDirectory returns the current directory
func GetCurrentDirectory() string {
dir, err := os.Getwd()
if err != nil {
return ""
}
return dir
}
// Get SHA256 checksum of the specified file
func FileSHA256Sum(path string) string {
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
hash := sha256.New()
_, err = io.Copy(hash, file)
if err != nil {
panic(err)
}
return fmt.Sprintf("%x", hash.Sum(nil))
}
// RC4Cipher is used on Yara ciphered rules
func RC4Cipher(content []byte, key string) []byte {
c, err := rc4.NewCipher([]byte(key))
if err != nil {
LogFatal(fmt.Sprintf("(ERROR) %v", err))
}
c.XORKeyStream(content, content)
return content
}