forked from chainguard-dev/malcontent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogramkind.go
More file actions
328 lines (289 loc) · 8.26 KB
/
Copy pathprogramkind.go
File metadata and controls
328 lines (289 loc) · 8.26 KB
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
// Copyright 2024 Chainguard, Inc.
// SPDX-License-Identifier: Apache-2.0
package programkind
import (
"bytes"
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"github.com/chainguard-dev/malcontent/pkg/pool"
"github.com/gabriel-vasile/mimetype"
)
// Supported archive extensions.
var ArchiveMap = map[string]bool{
".apk": true,
".bz2": true,
".bzip2": true,
".deb": true,
".gem": true,
".gz": true,
".jar": true,
".rpm": true,
".tar": true,
".tar.gz": true,
".tar.xz": true,
".tgz": true,
".upx": true,
".whl": true,
".xz": true,
".zst": true,
".zstd": true,
".zip": true,
}
// file extension to MIME type, if it's a good scanning target.
var supportedKind = map[string]string{
"7z": "",
"Z": "application/zlib",
"asm": "",
"bash": "application/x-bsh",
"bat": "application/bat",
"beam": "application/x-erlang-binary",
"bin": "application/octet-stream",
"c": "text/x-c",
"cc": "text/x-c",
"class": "application/java-vm",
"com": "application/octet-stream",
"cpp": "text/x-c",
"cron": "text/x-cron",
"crontab": "text/x-crontab",
"csh": "application/x-csh",
"cxx": "text/x-c",
"dll": "application/octet-stream",
"dylib": "application/x-sharedlib",
"elf": "application/x-elf",
"exe": "application/octet-stream",
"expect": "text/x-expect",
"fish": "text/x-fish",
"go": "text/x-go",
"gzip": "application/gzip",
"h": "text/x-h",
"hh": "text/x-h",
"html": "",
"jar": "application/java-archive",
"java": "text/x-java",
"js": "application/javascript",
"json": "application/json",
"ko": "application/x-object",
"lnk": "application/x-ms-shortcut",
"lua": "text/x-lua",
"macho": "application/x-mach-binary",
"md": "",
"o": "application/octet-stream",
"pe": "application/vnd.microsoft.portable-executable",
"php": "text/x-php",
"pl": "text/x-perl",
"pm": "text/x-script.perl-module",
"ps1": "text/x-powershell",
"py": "text/x-python",
"pyc": "application/x-python-code",
"rb": "text/x-ruby",
"rs": "text/x-rust",
"scpt": "application/x-applescript",
"scptd": "application/x-applescript",
"script": "text/x-generic-script",
"service": "text/x-systemd",
"sh": "application/x-sh",
"so": "application/x-sharedlib",
"ts": "application/typescript",
"upx": "application/x-upx",
"whl": "application/x-wheel+zip",
"yaml": "",
"yara": "",
"yml": "",
"zsh": "application/x-zsh",
}
type FileType struct {
Ext string
MIME string
}
var (
headerPool *pool.BufferPool
initializeOnce sync.Once
)
const headerSize int = 512
// IsSupportedArchive returns whether a path can be processed by our archive extractor.
// UPX files are an edge case since they may or may not even have an extension that can be referenced.
func IsSupportedArchive(path string) bool {
if _, isValidArchive := ArchiveMap[GetExt(path)]; isValidArchive {
return true
}
if ft, err := File(path); err == nil && ft != nil {
if ft.MIME == "application/x-upx" {
return true
}
}
return false
}
// getExt returns the extension of a file path
// and attempts to avoid including fragments of filenames with other dots before the extension.
func GetExt(path string) string {
base := filepath.Base(path)
// Handle files with version numbers in the name
// e.g. file1.2.3.tar.gz -> .tar.gz
re := regexp.MustCompile(`\d+\.\d+\.\d+$`)
base = re.ReplaceAllString(base, "")
ext := filepath.Ext(base)
if ext != "" && strings.Contains(base, ".") {
parts := strings.Split(base, ".")
if len(parts) > 2 {
subExt := fmt.Sprintf(".%s%s", parts[len(parts)-2], ext)
if isValidExt := func(ext string) bool {
_, ok := ArchiveMap[ext]
return ok
}(subExt); isValidExt {
return subExt
}
}
}
return ext
}
var ErrUPXNotFound = errors.New("UPX executable not found in PATH")
func UPXInstalled() error {
_, err := exec.LookPath("upx")
if err != nil {
if errors.Is(err, exec.ErrNotFound) {
return ErrUPXNotFound
}
return fmt.Errorf("failed to check for UPX executable: %w", err)
}
return nil
}
// IsValidUPX checks whether a suspected UPX-compressed file can be decompressed with UPX.
func IsValidUPX(header []byte, path string) (bool, error) {
if !bytes.Contains(header, []byte("UPX!")) {
return false, nil
}
if err := UPXInstalled(); err != nil {
return false, err
}
cmd := exec.Command("upx", "-l", "-f", path)
output, err := cmd.CombinedOutput()
if err != nil && (bytes.Contains(output, []byte("NotPackedException")) ||
bytes.Contains(output, []byte("not packed by UPX"))) {
return false, nil
}
return true, nil
}
func makeFileType(path string, ext string, mime string) *FileType {
ext = strings.TrimPrefix(ext, ".")
// the only JSON files we currently scan are NPM package metadata, which ends in *package.json
if strings.HasSuffix(path, "package.json") {
return &FileType{
Ext: ext,
MIME: "application/json",
}
}
if supportedKind[ext] == "" {
return nil
}
// fix mimetype bug that defaults elf binaries to x-sharedlib
if mime == "application/x-sharedlib" && !strings.Contains(path, ".so") {
return Path(".elf")
}
if strings.Contains(mime, "application") || strings.Contains(mime, "text/x-") || strings.Contains(mime, "text/x-") || strings.Contains(mime, "executable") {
return &FileType{
Ext: ext,
MIME: mime,
}
}
return nil
}
// File detects what kind of program this file might be.
//
//nolint:cyclop // ignore complexity of 38
func File(path string) (*FileType, error) {
// Follow symlinks and return cleanly if the target does not exist
_, err := filepath.EvalSymlinks(path)
if os.IsNotExist(err) {
return nil, nil
}
st, err := os.Stat(path)
if err != nil {
return nil, fmt.Errorf("stat: %w", err)
}
if st.IsDir() {
return nil, nil
}
if st.Mode().Type() == fs.ModeIrregular {
return nil, nil
}
if st.Size() == 0 {
return nil, nil
}
initializeOnce.Do(func() {
headerPool = pool.NewBufferPool(runtime.GOMAXPROCS(0))
})
buf := headerPool.Get(int64(headerSize))
defer headerPool.Put(buf)
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open: %w", err)
}
defer f.Close()
bs, err := f.Read(buf)
if err != nil {
return nil, fmt.Errorf("read: %w", err)
}
hdr := buf[:bs]
// first strategy: mimetype
mimetype.SetLimit(uint32(headerSize))
mtype := mimetype.Detect(hdr)
if ft := makeFileType(path, mtype.Extension(), mtype.String()); ft != nil {
return ft, nil
}
// second strategy: path (extension, mostly)
if mtype := Path(path); mtype != nil {
return mtype, nil
}
// final strategy: DIY matching where mimetype is too strict.
if isUPX, err := IsValidUPX(hdr, path); err == nil && isUPX {
return Path(".upx"), nil
}
switch {
case hdr[0] == '\x7f' && (hdr[1] == 'E' && hdr[2] == 'L' && hdr[3] == 'F'):
return Path(".elf"), nil
case bytes.Contains(hdr, []byte("<?php")):
return Path(".php"), nil
case bytes.HasPrefix(hdr, []byte("import ")):
return Path(".py"), nil
case bytes.Contains(hdr, []byte(" = require(")):
return Path(".js"), nil
case bytes.HasPrefix(hdr, []byte("#!/bin/ash")) ||
bytes.HasPrefix(hdr, []byte("#!/bin/bash")) ||
bytes.HasPrefix(hdr, []byte("#!/bin/fish")) ||
bytes.HasPrefix(hdr, []byte("#!/bin/sh")) ||
bytes.HasPrefix(hdr, []byte("#!/bin/zsh")) ||
bytes.Contains(hdr, []byte("if [")) ||
bytes.Contains(hdr, []byte("if !")) ||
bytes.Contains(hdr, []byte("echo ")) ||
bytes.Contains(hdr, []byte("grep ")) ||
bytes.Contains(hdr, []byte("; then")) ||
bytes.Contains(hdr, []byte("export ")) ||
strings.HasSuffix(path, "profile"):
return Path(".sh"), nil
case bytes.HasPrefix(hdr, []byte("#!")):
return Path(".script"), nil
case bytes.Contains(hdr, []byte("#include <")):
return Path(".c"), nil
case bytes.Contains(hdr, []byte("BEAMAtU8")):
return Path(".beam"), nil
case hdr[0] == '\x1f' && hdr[1] == '\x8b':
return Path(".gzip"), nil
case hdr[0] == '\x78' && hdr[1] == '\x5E':
return Path(".Z"), nil
}
return nil, nil
}
// Path returns a filetype based strictly on file path.
func Path(path string) *FileType {
ext := strings.ReplaceAll(filepath.Ext(path), ".", "")
mime := supportedKind[ext]
return makeFileType(path, ext, mime)
}