-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd.go
112 lines (99 loc) · 2.3 KB
/
cmd.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
package cmd
import (
"bytes"
"context"
"fmt"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
// Command is a http.HandlerFunc that exec commands by given query string.
//
// Usage:
// https://github.com/tnclong/http-cmd/blob/master/cmd_test.go
func Command(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, private")
q := r.URL.Query()
name := q.Get("name")
arg := q["arg"]
timeout, err := strconv.ParseInt(q.Get("timeout"), 10, 64)
if err != nil {
http.Error(w, fmt.Sprintf("parse timeout with err: %s", err.Error()), http.StatusUnprocessableEntity)
return
}
if timeout <= 0 {
timeout = 10
}
env := os.Getenv("DANGER_HTTP_ALLOWED_CMDS")
if !isAllowedCmds(env, name) && !isAllowedAllCmds(env) {
http.Error(w, fmt.Sprintf("name=%q is unallowed while check env DANGER_HTTP_ALLOWED_CMDS=%s", name, env), http.StatusUnprocessableEntity)
return
}
ctx, cf := context.WithTimeout(r.Context(), time.Duration(timeout)*time.Second)
defer cf()
cmd := exec.CommandContext(ctx, name, arg...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
w.WriteHeader(http.StatusOK)
err = cmd.Run()
fmt.Fprintf(w, "name: %s\n", name)
fmt.Fprintf(w, "arg: %s\n", arg)
fmt.Fprintf(w, "timeout: %d\n", timeout)
fmt.Fprintln(w)
fmt.Fprintln(w)
w.Write([]byte("stdout:\n"))
w.Write(stdout.Bytes())
fmt.Fprintln(w)
fmt.Fprintln(w)
w.Write([]byte("stderr:\n"))
w.Write(stderr.Bytes())
fmt.Fprintln(w)
fmt.Fprintln(w)
if err != nil {
w.Write([]byte("err:\n"))
w.Write([]byte(err.Error()))
fmt.Fprintln(w)
}
}
func isAllowedAllCmds(env string) bool {
return isAllowedCmds(env, "***")
}
func isAllowedCmds(env, name string) bool {
i := strings.Index(env, name)
return backOk(env, i) && forwardOk(env, i, name)
}
func backOk(env string, i int) bool {
if i < 0 {
return false
}
for b := i - 1; b >= 0; b-- {
if env[b] == ' ' {
continue
}
if env[b] == ',' {
return true
}
return false
}
return true
}
func forwardOk(env string, i int, name string) bool {
if i < 0 {
return false
}
for f := i + len(name); f < len(env); f++ {
if env[f] == ' ' {
continue
}
if env[f] == ',' {
return true
}
return false
}
return true
}