-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathexecutil.go
More file actions
289 lines (244 loc) · 6.93 KB
/
Copy pathexecutil.go
File metadata and controls
289 lines (244 loc) · 6.93 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
package executil
import (
"encoding/base64"
"io"
"os/exec"
"runtime"
"strings"
"github.com/projectdiscovery/utils/errkit"
"golang.org/x/text/encoding/unicode"
)
const (
// token of prefix for space, escape char '\'
tkSpPrefix = '\\'
// the space
tkSp = ' '
)
// splitCmdArgs splits cmds with spaces.
// It recognizes "\ " as a " " (space) in arguments of the command.
// '\' is escape char only effect with space ' '.
// so "\\a" is also the "\\a" in argment, not "\a".
// e.g. "b\a" -> "b\a".
func splitCmdArgs(cmds string) []string {
raw := []byte(cmds)
length := len(raw)
argments := make([]string, 0, 4)
escape := false
// argment recognizing
argRec := false
var rawArg []byte
fillArgChar := func(c byte) []byte {
if rawArg == nil {
rawArg = make([]byte, 0, 16)
}
rawArg = append(rawArg, c)
return rawArg
}
finishArg := func() {
// finish one argment recognized
if len(rawArg) > 0 {
argment := string(rawArg)
argments = append(argments, argment)
}
rawArg = nil
}
for i := 0; i < length; i++ {
c := raw[i]
switch c {
case tkSp:
if escape {
fillArgChar(tkSp)
escape = false // exit excape
} else if argRec {
argRec = false
finishArg()
}
case tkSpPrefix:
if escape {
// like "\\"
fillArgChar(tkSpPrefix) // first '\'
} else {
escape = true
}
if !argRec {
argRec = true
}
default:
if !argRec {
argRec = true
}
if escape {
escape = false
fillArgChar(tkSpPrefix)
}
fillArgChar(c)
}
}
if escape {
fillArgChar(tkSpPrefix)
}
if argRec {
finishArg()
}
return argments
}
// convert spaces in arg to "\ "
// so it can split with func [splitCmdAgrs]
// func safeArg(arg string) string {
// return strings.ReplaceAll(arg, " ", "\\ ")
// }
// func splitt(s string) (tokens []string) {
// for _, ss := range strings.Split(s, " ") {
// tokens = append(tokens, strings.Split(ss, "\n")...)
// }
// return
// }
// Run the specified command in os shell (sh or powershell.exe) and return the output
func Run(cmd string) (string, error) {
if runtime.GOOS == "windows" {
return RunPS(cmd)
}
return RunSh(splitCmdArgs(cmd)...)
}
/*
RunSafe necessarily does not prevent command injection but prevents/limits damage to an extent
"the os/exec package intentionally does not invoke the system shell and does not expand
any glob patterns or handle other expansions, pipelines, or redirections typically done by shells"
This also mitigates windows security risk in go<1.19. refer https://pkg.go.dev/os/exec
*/
func RunSafe(cmd ...string) (string, error) {
execpath, err := exec.LookPath(cmd[0])
if err != nil {
if runtime.GOOS == "windows" {
return "", errkit.WithMessage(err, "RunSafe does not allow relative exection of binaries (ex ./main) due to security reasons")
}
return "", err
}
var cmdArgs []string
if runtime.GOOS == "windows" {
/* When command is run in Windows using exec.Command, args are passed as quoted strings
and are parsed/converted to args before command is run by Go Internally
*/
cmdArgs = cmd[1:]
} else {
cmdArgs = splitCmdArgs(strings.Join(cmd[1:], " "))
}
cmdExec := exec.Command(execpath, cmdArgs...)
in, err := cmdExec.StdinPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stdin pipe")
}
errorOut, err := cmdExec.StderrPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stderr pipe")
}
out, err := cmdExec.StdoutPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stdout pipe")
}
defer func() {
_ = in.Close()
_ = errorOut.Close()
_ = out.Close()
}()
if err := cmdExec.Start(); err != nil {
return "", errkit.Wrap(err, "failed to start command")
}
outData, _ := io.ReadAll(out)
errorData, _ := io.ReadAll(errorOut)
var adbError error = nil
if err := cmdExec.Wait(); err != nil {
if _, ok := err.(*exec.ExitError); ok {
adbError = errkit.Append(err, errkit.New("%s", string(errorData)), errkit.New("exit error"))
outData = errorData
} else {
return "", errkit.Wrap(err, "process i/o error")
}
}
return string(outData), adbError
}
// RunSh the specified command through sh
func RunSh(cmd ...string) (string, error) {
cmdExec := exec.Command("sh", "-c", strings.Join(cmd, " "))
in, err := cmdExec.StdinPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stdin pipe")
}
errorOut, err := cmdExec.StderrPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stderr pipe")
}
out, err := cmdExec.StdoutPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stdout pipe")
}
defer func() {
_ = in.Close()
_ = errorOut.Close()
_ = out.Close()
}()
if err := cmdExec.Start(); err != nil {
errorData, _ := io.ReadAll(errorOut)
return "", errkit.Wrapf(err, "failed to start process %v", string(errorData))
}
outData, _ := io.ReadAll(out)
errorData, _ := io.ReadAll(errorOut)
var adbError error = nil
if err := cmdExec.Wait(); err != nil {
if _, ok := err.(*exec.ExitError); ok {
adbError = errkit.Append(err, errkit.New("%s", string(errorData)), errkit.New("exit error"))
outData = errorData
} else {
return "", errkit.Wrap(err, "process i/o error")
}
}
return string(outData), adbError
}
// RunPS runs the specified command through powershell.exe
func RunPS(cmd string) (string, error) {
/*
Run command in powershell using -EncodedCommand flag and base64 of actual command
this makes it possible to run complex quotation marks or curly braces without manual escaping
more details can be found at:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-encodedcommand-base64encodedcommand
*/
utf16 := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
encodedCmd, err := utf16.NewEncoder().String(cmd)
if err != nil {
return "", err
}
b64cmd := base64.StdEncoding.EncodeToString([]byte(encodedCmd))
cmdExec := exec.Command("powershell.exe", "-EncodedCommand", b64cmd)
in, err := cmdExec.StdinPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stdin pipe")
}
errorOut, err := cmdExec.StderrPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stderr pipe")
}
out, err := cmdExec.StdoutPipe()
if err != nil {
return "", errkit.WithMessage(err, "failed to create stdout pipe")
}
defer func() {
_ = in.Close()
_ = errorOut.Close()
_ = out.Close()
}()
if err := cmdExec.Start(); err != nil {
return "", errkit.WithMessage(err, "start powershell.exe process error")
}
outData, _ := io.ReadAll(out)
errorData, _ := io.ReadAll(errorOut)
var adbError error = nil
if err := cmdExec.Wait(); err != nil {
if _, ok := err.(*exec.ExitError); ok {
adbError = errkit.Append(err, errkit.New("%s", string(errorData)), errkit.New("exit error"))
outData = errorData
} else {
return "", errkit.Wrap(err, "process i/o error")
}
}
return string(outData), adbError
}