-
Notifications
You must be signed in to change notification settings - Fork 154
/
util.go
213 lines (180 loc) 路 5.29 KB
/
util.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
package core
import (
"crypto/sha1"
"encoding/hex"
"math"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/deepfence/YaraHunter/constants"
log "github.com/sirupsen/logrus"
)
// CreateRecursiveDir Create directory structure recursively, if they do not exist
// @parameters
// completePath - Complete path of directory which needs to be created
// @returns
// Error - Errors if any. Otherwise, returns nil
func CreateRecursiveDir(completePath string) error {
if _, err := os.Stat(completePath); os.IsNotExist(err) {
log.Debugf("Folder does not exist. Creating folder... %s", completePath)
err = os.MkdirAll(completePath, os.ModePerm)
if err != nil {
log.Errorf("createRecursiveDir %q: %s", completePath, err)
}
return err
} else if err != nil {
log.Errorf("createRecursiveDir %q: %s. Deleting temp dir", completePath, err)
_ = DeleteTmpDir(completePath)
return err
}
return nil
}
// Create a sanitized string from image name which can used as a filename
// @parameters
// imageName - Name of the container image
// @returns
// string - Sanitized string which can used as part of filename
func getSanitizedString(imageName string) string {
//nolint:gocritic
reg, err := regexp.Compile("[^A-Za-z0-9]+")
if err != nil {
return "error"
}
sanitizedName := reg.ReplaceAllString(imageName, "")
return sanitizedName
}
// GetJSONFilepath Return complete path and filename for json output file
// @parameters
// image - Name of the container image or dir, for which json filename and path will be created
// @returns
// string - Sanitized string which can used as path and filename of json output file
// Error - Errors if path can't be created. Otherwise, returns nil
func GetJSONFilepath(jsonFilename, outputPath string) (string, error) {
if jsonFilename == "" {
return "", nil
}
outputDir := outputPath
if outputDir != "" && !PathExists(outputDir) {
err := CreateRecursiveDir(outputDir)
if err != nil {
log.Errorf("GetJsonFilepath: Could not create output dir: %s", err)
return "", err
}
}
jsonFilePath := filepath.Join(outputDir, jsonFilename)
log.Infof("Complete json file path and name: %s", jsonFilePath)
return jsonFilePath, nil
}
// GetTmpDir Create a temporrary directory to extract the conetents of container image
// @parameters
// imageName - Name of the container image
// @returns
// String - Complete path of the based directory where image will be extracted, empty string if error
// Error - Errors if any. Otherwise, returns nil
func GetTmpDir(imageName, tempDirectory string) (string, error) {
scanID := "df_" + getSanitizedString(imageName)
tempPath := filepath.Join(tempDirectory, "Deepfence", constants.TempDirSuffix, scanID)
// if runtime.GOOS == "windows" {
// tempPath = dir + "\temp\Deepfence\IOCScanning\df_" + scanId
//}
completeTempPath := path.Join(tempPath, constants.ExtractedImageFilesDir)
err := CreateRecursiveDir(completeTempPath)
if err != nil {
log.Errorf("getTmpDir: Could not create temp dir%s", err)
return "", err
}
return tempPath, err
}
// DeleteTmpDir Delete the temporary directory
// @parameters
// outputDir - Directory which need to be deleted
// @returns
// Error - Errors if any. Otherwise, returns nil
func DeleteTmpDir(outputDir string) error {
log.Infof("Deleting temporary dir %s", outputDir)
// Output dir will be empty string in case of error, don't delete
if outputDir != "" {
// deleteFiles(outputDir+"/", "*")
err := os.RemoveAll(outputDir)
if err != nil {
log.Errorf("deleteTmpDir: Could not delete temp dir: %s", err)
return err
}
}
return nil
}
// DeleteFiles Delete all the files and dirs recursively in specified directory
// @parameters
// path - Directory whose contents need to be deleted
// wildcard - patterns to match the filenames (e.g. '*')
func DeleteFiles(path string, wildCard string) {
var val string
files, _ := filepath.Glob(path + wildCard)
for _, val = range files {
os.RemoveAll(val)
}
}
// IsSymLink Check if input is a symLink, not normal file/dir
// path - Pathname which needs to be checked for symbolic link
// @returns
// bool - Return true if input is a symLink
func IsSymLink(path string) bool {
// can handle symbolic link, but will no follow the link
fileInfo, err := os.Lstat(path)
if err != nil {
// panic(err)
return false
}
// --- check if file is a symlink
if fileInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
return true
}
return false
}
func PathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
func LogIfError(text string, err error) {
if err != nil {
log.Errorf("%s (%s", text, err.Error())
}
}
func GetHash(s string) string {
h := sha1.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
func Pluralize(count int, singular string, plural string) string {
if count == 1 {
return singular
}
return plural
}
func GetEntropy(data string) (entropy float64) {
if data == "" {
return 0
}
for i := 0; i < 256; i++ {
px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return entropy
}
func GetTimestamp() int64 {
return time.Now().UTC().UnixNano() / 1000000
}
func GetCurrentTime() string {
return time.Now().UTC().Format("2006-01-02T15:04:05.000") + "Z"
}