Repository navigation
Expand file tree
/
Copy pathborrowed.go
More file actions
362 lines (339 loc) · 11.4 KB
/
Copy pathborrowed.go
File metadata and controls
362 lines (339 loc) · 11.4 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
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
package main
// The shell inside Python and JavaScript.
//
// This is not a Python parser and it is not a JavaScript parser. Writing
// either one properly is a project the size of this whole program, and a
// half good one would be worse than none, because everything here rests on
// parsing rather than searching and a report that guessed would not deserve
// to be believed.
//
// What it does instead is narrower and, for the question being asked, most
// of the value. The dangerous half of a setup.py or an install.js is not
// the Python or the JavaScript: it is the shell they hand to the machine.
// os.system, subprocess with shell=True, child_process.exec. So the string
// being handed over is lifted out and read by the same reader as everything
// else, and the finding says which line of which file it came from.
//
// The other half is the calls that do the damage without a shell at all:
// urlretrieve, fs.appendFileSync, shutil.copy. Those are turned into the
// shell line that would have done the same thing and read the same way. A
// script that appends to your .bashrc has done that whether it went through
// sh or not, and the report should say so either way.
//
// Where it stops is written down: a command built out of variables in
// Python is a Python expression, and this reads the literals. It says so
// rather than guessing.
import (
"regexp"
"strings"
)
// borrowing is a call in another language that hands work to the shell, or
// does something a shell line would have done. Payload says how to read
// what is inside the brackets.
type borrowing struct {
// Call is matched against the text, and the match must end at the
// opening bracket of the call.
Call *regexp.Regexp
// Shape is how the arguments become a command:
//
// line the first argument is a whole command line
// argv the arguments are a command and its arguments, already split
// as the arguments are put into Into with %s in the order given
Shape string
Into string
}
var pythonCalls = []borrowing{
{regexp.MustCompile(`\bos\.system\s*\(`), "line", ""},
{regexp.MustCompile(`\bos\.popen\s*\(`), "line", ""},
{regexp.MustCompile(`\bcommands\.getoutput\s*\(`), "line", ""},
{regexp.MustCompile(`\bsubprocess\.(?:run|call|check_call|check_output|Popen)\s*\(`), "argv", ""},
{regexp.MustCompile(`\bos\.exec[lv]p?e?\s*\(`), "argv", ""},
{regexp.MustCompile(`\bos\.spawn[lv]p?e?\s*\(`), "argv", ""},
// The ones that need no shell to do the same thing.
{regexp.MustCompile(`\burllib\.request\.urlretrieve\s*\(`), "as", "curl %s -o %s"},
{regexp.MustCompile(`\brequests\.(?:get|post)\s*\(`), "as", "curl %s"},
{regexp.MustCompile(`\burlopen\s*\(`), "as", "curl %s"},
{regexp.MustCompile(`\bshutil\.(?:copy|copy2|copyfile|move)\s*\(`), "as", "cp %s %s"},
{regexp.MustCompile(`\bos\.chmod\s*\(`), "as", "chmod %s %s"},
{regexp.MustCompile(`\bos\.remove\s*\(`), "as", "rm %s"},
{regexp.MustCompile(`\bPath\s*\(\s*`), "", ""},
}
var nodeCalls = []borrowing{
{regexp.MustCompile(`\b(?:child_process\.)?exec(?:Sync)?\s*\(`), "line", ""},
{regexp.MustCompile(`\bshell\.exec\s*\(`), "line", ""},
{regexp.MustCompile(`\b(?:child_process\.)?spawn(?:Sync)?\s*\(`), "argv", ""},
{regexp.MustCompile(`\b(?:child_process\.)?execFile(?:Sync)?\s*\(`), "argv", ""},
{regexp.MustCompile(`\bfs\.appendFileSync\s*\(`), "as", "echo x >> %s"},
{regexp.MustCompile(`\bfs\.appendFile\s*\(`), "as", "echo x >> %s"},
{regexp.MustCompile(`\bfs\.writeFileSync\s*\(`), "as", "echo x > %s"},
{regexp.MustCompile(`\bfs\.copyFileSync\s*\(`), "as", "cp %s %s"},
{regexp.MustCompile(`\bfs\.chmodSync\s*\(`), "as", "chmod %s %s"},
{regexp.MustCompile(`\bhttps?\.get\s*\(`), "as", "curl %s"},
{regexp.MustCompile(`\bfetch\s*\(`), "as", "curl %s"},
}
func fromPython(text string) (string, []Script, []string) {
found := borrowedFrom(text, pythonCalls)
kind := "a python file"
if len(found) == 0 {
return kind, nil, []string{
"this is python and this program reads shell, so only the commands " +
"it hands to a shell were read. There were none"}
}
return kind, found, []string{
"this is python and this program reads shell, so what was read is the " +
"commands it hands to a shell and nothing else the python does"}
}
func fromNode(text string) (string, []Script, []string) {
found := borrowedFrom(text, nodeCalls)
kind := "a javascript file"
if len(found) == 0 {
return kind, nil, []string{
"this is javascript and this program reads shell, so only the " +
"commands it hands to a shell were read. There were none"}
}
return kind, found, []string{
"this is javascript and this program reads shell, so what was read is " +
"the commands it hands to a shell and nothing else the javascript does"}
}
// borrowedFrom walks the text looking for each call and lifting out what it
// was handed.
func borrowedFrom(text string, calls []borrowing) []Script {
var out []Script
for _, call := range calls {
if call.Shape == "" {
continue
}
for _, at := range call.Call.FindAllStringIndex(text, -1) {
args := callArgs(text, at[1])
if len(args) == 0 {
continue
}
line := strings.Count(text[:at[0]], "\n") + 1
switch call.Shape {
case "line":
if word := asWord(args[0]); word != "" {
out = append(out, Script{Body: word, Line: line})
}
case "argv":
if body := asArgv(args[0]); body != "" {
out = append(out, Script{Body: body, Line: line})
}
case "as":
body := call.Into
for _, arg := range args {
word := asWord(arg)
if word == "" {
word = "something"
}
body = replaceOnce(body, "%s", quoteWord(word))
}
if strings.Contains(body, "%s") {
continue
}
out = append(out, Script{Body: body, Line: line})
}
}
}
return out
}
func replaceOnce(text, from, to string) string {
at := strings.Index(text, from)
if at < 0 {
return text
}
return text[:at] + to + text[at+len(from):]
}
// quoteWord puts a value where a shell word goes without letting a space
// in it turn into two arguments.
func quoteWord(word string) string {
if strings.ContainsAny(word, " \t") {
return `"` + word + `"`
}
return word
}
// callArgs reads the arguments of a call, given the position just after the
// opening bracket. Nesting and quoting are counted so that a call inside a
// call comes back whole rather than cut in half at its first comma.
func callArgs(text string, from int) []string {
var out []string
depth := 0
start := from
var quote byte
for at := from; at < len(text); at++ {
c := text[at]
if quote != 0 {
if c == '\\' {
at++
continue
}
if c == quote {
quote = 0
}
continue
}
switch c {
case '\'', '"', '`':
quote = c
case '(', '[', '{':
depth++
case ')', ']', '}':
if c == ')' && depth == 0 {
out = append(out, strings.TrimSpace(text[start:at]))
return out
}
depth--
case ',':
if depth == 0 {
out = append(out, strings.TrimSpace(text[start:at]))
start = at + 1
}
case '\n':
// A call that runs off the end of the file rather than
// closing is not a call, and reading to the end of the file
// looking for a bracket finds the whole rest of it.
if depth == 0 && at-from > 400 {
return out
}
}
}
return out
}
// asWord turns one argument into the text it stands for. A string literal
// gives its contents; anything else is a value this cannot know, and comes
// back as the shell would write an unknown: a dollar and the name.
func asWord(arg string) string {
arg = strings.TrimSpace(arg)
if arg == "" {
return ""
}
// An f-string is a string with holes in it, and the holes are values
// from somewhere else, which is exactly what a shell variable is.
prefix := ""
for len(arg) > 1 && (arg[0] == 'f' || arg[0] == 'r' || arg[0] == 'b' ||
arg[0] == 'F' || arg[0] == 'R') && (arg[1] == '\'' || arg[1] == '"') {
prefix += string(arg[0])
arg = arg[1:]
}
if len(arg) >= 2 && (arg[0] == '\'' || arg[0] == '"' || arg[0] == '`') &&
arg[len(arg)-1] == arg[0] {
inner := arg[1 : len(arg)-1]
if strings.ContainsAny(prefix, "fF") || arg[0] == '`' {
inner = holesToVariables(inner)
}
return inner
}
// Two literals stuck together with a plus, which is how a URL gets
// built in both languages.
if strings.Contains(arg, "+") {
var joined strings.Builder
for _, part := range strings.Split(arg, "+") {
word := asWord(part)
if word == "" {
return ""
}
joined.WriteString(word)
}
return joined.String()
}
if fixed := meaning[arg]; fixed != "" {
return "$" + fixed
}
if name := plainName(arg); name != "" {
return "$" + name
}
return ""
}
// asArgv turns a list of arguments into a command line. subprocess and
// spawn take the command already split up, which is the safer way to write
// it and reads the same once it is joined back together.
func asArgv(arg string) string {
arg = strings.TrimSpace(arg)
if len(arg) < 2 || arg[0] != '[' || arg[len(arg)-1] != ']' {
// Not a list, so it is a command line after all.
return asWord(arg)
}
var parts []string
// Both brackets come off before the list is read: callArgs stops at a
// closing round bracket, and a square one left on the end takes the
// depth negative and swallows the last item.
for _, item := range callArgs(arg[1:len(arg)-1]+")", 0) {
word := asWord(item)
if word == "" {
word = "something"
}
parts = append(parts, quoteWord(word))
}
return strings.Join(parts, " ")
}
// meaning is the handful of expressions in both languages that name a
// place rather than compute one. os.homedir() is a home directory on every
// machine there is, and turning it into $HOME lets the rest of the program
// recognise ${os.homedir()}/.zshrc as a shell profile, which is the whole
// finding in half the install scripts npm carries.
var meaning = map[string]string{
"os.homedir()": "HOME",
"os.userInfo().homedir": "HOME",
"process.env.HOME": "HOME",
"process.env.USERPROFILE": "HOME",
"os.tmpdir()": "TMPDIR",
"os.path.expanduser('~')": "HOME",
"os.path.expanduser(\"~\")": "HOME",
"Path.home()": "HOME",
"os.environ['HOME']": "HOME",
"os.environ[\"HOME\"]": "HOME",
"os.environ.get('HOME')": "HOME",
"tempfile.gettempdir()": "TMPDIR",
"os.getcwd()": "PWD",
"process.cwd()": "PWD",
"sys.prefix": "PREFIX",
"site.getusersitepackages()": "PREFIX",
}
// holesToVariables turns the ${x} of a template literal and the {x} of an
// f-string into $x, so that a path built out of a variable still reads as a
// path built out of a variable.
func holesToVariables(text string) string {
var out strings.Builder
for at := 0; at < len(text); at++ {
if text[at] == '$' && at+1 < len(text) && text[at+1] == '{' {
at++
}
if text[at] != '{' {
out.WriteByte(text[at])
continue
}
end := strings.IndexByte(text[at:], '}')
if end < 0 {
out.WriteByte(text[at])
continue
}
inner := strings.TrimSpace(text[at+1 : at+end])
switch {
case meaning[inner] != "":
out.WriteString("$" + meaning[inner])
case plainName(inner) != "":
out.WriteString("$" + plainName(inner))
default:
out.WriteString("$something")
}
at += end
}
return out.String()
}
// plainName is an identifier, possibly with dots in it, and nothing else.
func plainName(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
for i := 0; i < len(s); i++ {
c := s[i]
if isNameByte(c) || c == '.' {
continue
}
return ""
}
if s[0] >= '0' && s[0] <= '9' {
return ""
}
return strings.ReplaceAll(s, ".", "_")
}