-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcorediff.go
325 lines (288 loc) · 8.74 KB
/
corediff.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
/*
corediff: quickly find unauthorized code changes to common applications
Copyright (C) 2020-2024 Willem de Groot <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"bufio"
"encoding/binary"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/gwillem/go-buildversion"
"github.com/gwillem/go-selfupdate"
)
var (
selfUpdateURL = fmt.Sprintf("https://sansec.io/downloads/%s-%s/corediff", runtime.GOOS, runtime.GOARCH)
placeholder = struct{}{}
corediffVersion = buildversion.String()
)
func loadDB(path string) hashDB {
// get file size of path to pre allocate proper map size
fi, err := os.Stat(path)
if os.IsNotExist(err) {
// creating new db?
return make(hashDB, 0)
} else if err != nil {
log.Fatal(err)
}
size := fi.Size()
// fatal if not multiple of 8
if size%8 != 0 {
log.Fatal("Invalid database size, corrupt?")
}
// create a map of size
m := make(hashDB, size/8)
f, err := os.Open(path)
if os.IsNotExist(err) {
return m
} else if err != nil {
log.Fatal(err)
}
defer f.Close()
reader := bufio.NewReader(f)
var b uint64
for {
err = binary.Read(reader, binary.LittleEndian, &b)
if err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
m[b] = placeholder
}
return m
}
func saveDB(path string, db hashDB) {
f, err := os.CreateTemp(filepath.Dir(path), "corediff_temp_db")
if err != nil {
log.Fatal(err)
}
// defer executed in reverse order
defer os.Remove(f.Name())
defer f.Close()
for k := range db {
if err := binary.Write(f, binary.LittleEndian, k); err != nil {
log.Fatal(err)
}
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
if err := os.Rename(f.Name(), path); err != nil {
log.Fatal(err)
}
}
func parseFile(path string, db hashDB, updateDB bool) (hits []int, lines [][]byte) {
fh, err := os.Open(path)
if err != nil && os.IsNotExist(err) {
fmt.Println(warn("file does not exist: " + path))
return nil, nil
} else if err != nil {
log.Fatal("open error on", path, err)
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
buf = buf[:0]
scanner.Buffer(buf, maxTokenSize)
for i := 0; scanner.Scan(); i++ {
x := scanner.Bytes()
h := hash(normalizeLine(x))
if _, ok := db[h]; !ok {
hits = append(hits, i)
lines = append(lines, x) // to show specific line number
if updateDB {
db[h] = placeholder
}
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return hits, lines
}
func checkPath(root string, db hashDB, args *baseArgs) *walkStats {
stats := &walkStats{}
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
var relPath string
if path == root {
relPath = root
} else {
relPath = path[len(root)+1:]
}
if err != nil {
fmt.Printf("failure accessing a path %q: %v\n", path, err)
return nil
}
if info.IsDir() {
return nil
}
if args.PathFilter != "" && !strings.HasPrefix(relPath, args.PathFilter) {
return nil
}
stats.totalFiles++
if (!args.AllValidText && !hasValidExt(path)) || (args.AllValidText && !isValidUtf8(path)) {
stats.filesNoCode++
return nil
}
// Only do path checking for non-root elts
if path != root && !args.IgnorePaths {
_, foundInDb := db[pathHash(relPath)]
shouldExclude := pathIsExcluded(relPath)
if !foundInDb || shouldExclude {
stats.filesCustomCode++
logVerbose(grey(" ? ", relPath))
return nil
}
}
hits, lines := parseFile(path, db, false)
if args.SuspectOnly {
hitsFiltered := []int{}
linesFiltered := [][]byte{}
for i, lineNo := range hits {
if shouldHighlight(lines[i]) {
hitsFiltered = append(hitsFiltered, lineNo)
linesFiltered = append(linesFiltered, lines[i])
}
}
hits = hitsFiltered
lines = linesFiltered
}
if len(hits) > 0 {
stats.filesWithChanges++
hasSuspectLines := false
fmt.Println(boldred("\n X " + relPath))
for i, lineNo := range hits {
// fmt.Println(string(lines[idx]))
if shouldHighlight(lines[i]) {
hasSuspectLines = true
fmt.Println(" ", grey(fmt.Sprintf("%-5d", lineNo)), alarm(string(lines[i])))
// fmt.Printf("%s %s\n", grey(fmt.Sprintf("%-5d", idx)), alarm(string(lines[idx])))
} else if !args.SuspectOnly {
fmt.Println(" ", grey(fmt.Sprintf("%-5d", lineNo)), string(lines[i]))
// fmt.Printf("%s %s\n", grey(fmt.Sprintf("%-5d", idx)), string(lines[idx]))
}
}
if hasSuspectLines {
stats.filesWithSuspectLines++
}
fmt.Println()
} else {
stats.filesWithoutChanges++
if args.Verbose {
stats.undetectedPaths = append(stats.undetectedPaths, path)
}
logVerbose(green(" V " + relPath))
}
return nil
})
if err != nil {
log.Fatalln("error walking the path", root, err)
}
return stats
}
func addPath(root string, db hashDB, args *baseArgs) {
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
var relPath string
if path == root {
relPath = root
} else {
relPath = path[len(root)+1:]
}
if err != nil {
fmt.Printf("failure accessing a path %q: %v\n", path, err)
return nil
}
if info.IsDir() {
return nil
}
if !args.AllValidText && !hasValidExt(path) {
logVerbose(grey(" - ", relPath, " (no code)"))
return nil
} else if !isValidUtf8(path) {
logVerbose(grey(" - ", relPath, " (invalid utf8)"))
return nil
}
// If relPath has valid ext, add hash of "path:<relPath>" to db
// Never add root path (possibly file)
if !args.IgnorePaths && path != root && !pathIsExcluded(relPath) {
db[pathHash(relPath)] = placeholder
}
hits, _ := parseFile(path, db, true)
if len(hits) > 0 {
logVerbose(green(" U " + relPath))
} else {
logVerbose(grey(" - " + relPath))
}
return nil
})
if err != nil {
log.Fatalln("error walking the path", root, err)
}
}
func main() {
if restarted, err := selfupdate.UpdateRestart(selfUpdateURL); restarted || err != nil {
logVerbose("Restarted new version", restarted, "with error:", err)
}
args := setup()
db := loadDB(args.Database)
fmt.Println(boldwhite("Corediff ", corediffVersion, " loaded ", len(db), " precomputed hashes. (C) 2020-2024 [email protected]"))
fmt.Println("Using database:", args.Database)
if args.Merge {
for _, p := range args.Path.Path {
db2 := loadDB(p)
fmt.Println("Merging", filepath.Base(p), "with", len(db2), "entries ..")
for k := range db2 {
db[k] = placeholder
}
}
fmt.Println("Saving", args.Database, "with a total of", len(db), "entries.")
saveDB(args.Database, db)
} else if args.Add {
oldSize := len(db)
for _, path := range args.Path.Path {
fmt.Println("Calculating checksums for", path)
addPath(path, db, args)
fmt.Println()
}
if len(db) != oldSize {
fmt.Println("Computed", len(db)-oldSize, "new hashes, saving to", args.Database, "..")
saveDB(args.Database, db)
} else {
fmt.Println("Found no new code hashes...")
}
} else {
without := "code"
if args.AllValidText {
without = "text"
}
for _, path := range args.Path.Path {
stats := checkPath(path, db, args)
fmt.Println("\n===============================================================================")
fmt.Println(" Corediff completed scanning", stats.totalFiles, "files in", path)
fmt.Println(" - Files with unrecognized lines :", boldred(fmt.Sprintf("%7d", stats.filesWithChanges)), grey(fmt.Sprintf("%8.2f%%", stats.percentage(stats.filesWithChanges))))
fmt.Println(" - Files with suspect lines :", warn(fmt.Sprintf("%7d", stats.filesWithSuspectLines)), grey(fmt.Sprintf("%8.2f%%", stats.percentage(stats.filesWithSuspectLines))))
fmt.Println(" - Files with only recognized lines :", green(fmt.Sprintf("%7d", stats.filesWithoutChanges)), grey(fmt.Sprintf("%8.2f%%", stats.percentage(stats.filesWithoutChanges))))
fmt.Println(" - Files with custom code :", fmt.Sprintf("%7d", stats.filesCustomCode), grey(fmt.Sprintf("%8.2f%%", stats.percentage(stats.filesCustomCode))))
fmt.Println(" - Files without", without, " :", fmt.Sprintf("%7d", stats.filesNoCode), grey(fmt.Sprintf("%8.2f%%", stats.percentage(stats.filesNoCode))))
logVerbose("Undetected paths:")
for _, p := range stats.undetectedPaths {
logVerbose(" ", p)
}
}
}
}