-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathopa.go
192 lines (155 loc) · 4.12 KB
/
opa.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
/*
Copyright The Kubeshield Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os/user"
"sync"
"github.com/the-redback/go-oneliners"
v1 "k8s.io/api/core/v1"
"kubeshield.dev/bpf-opa-demo/rules"
)
type opaRequest struct {
Input *opaInput `json:"input"`
}
type opaInput struct {
Event *syscallEvent `json:"event"`
Process *Process `json:"process"`
}
type syscallEvent struct {
*perfEventHeader
Name string `json:"name"`
Params map[string]interface{} `json:"params"`
}
type Process struct {
Name string `json:"name"`
Pid uint64 `json:"pid"`
Ppid uint64 `json:"ppid"`
Executable string `json:"executable"`
Args []string `json:"args"`
Command string `json:"command"`
Cgroup []string `json:"cgroup"`
Parent *Process `json:"parent"`
User *user.User `json:"user"`
ContainerID string `json:"containerID"`
Pod *v1.Pod `json:"pod"`
}
func querySyscallEventToOPA(wg *sync.WaitGroup, opaQueryCh chan *syscallEvent) {
defer wg.Done()
for evt := range opaQueryCh {
processMapLock.RLock()
proc := processMap[evt.Tid]
parent := processMap[proc.Ppid]
processMapLock.RUnlock()
if proc.Pid == 0 {
p, _ := procDirFS.Proc(int(evt.Tid))
proc = getProcessInfo(p)
}
if parent.Pid == 0 {
p, _ := procDirFS.Proc(int(proc.Ppid))
parent = getProcessInfo(p)
}
proc.Parent = &parent
evt.Name = getSyscallName(int(evt.Type))
req := &opaRequest{
Input: &opaInput{
Event: evt,
Process: &proc,
},
}
reqBytes, err := json.Marshal(req)
if err != nil {
logger.Error(err, "failed to marshal event")
continue
}
reqReader := bytes.NewReader(reqBytes)
out, err := callOpaAPI("POST", "http://localhost:8181/v1/data/rules", reqReader)
if err != nil {
logger.Error(err, "failed to call rules api")
continue
}
// output is empty, {"result":{}}
if len(out) <= 13 {
continue
}
var opaResult map[string]interface{}
err = json.Unmarshal(out, &opaResult)
if err != nil {
logger.Error(err, "failed to unmarshall queryToOPA response")
continue
}
oneliners.PrettyJson(opaResult["result"])
}
}
func loadRules() error {
err := loadFile("macros")
if err != nil {
logger.Error(err, "failed to laod macros file")
return err
}
err = loadFile("rules")
if err != nil {
logger.Error(err, "failed to laod rules file")
return err
}
return nil
}
func loadFile(name string) error {
filename := fmt.Sprintf("%s.rego", name)
log := logger.WithValues("filename", filename)
b, err := rules.Asset(filename)
if err != nil {
log.Error(err, "failed to read file")
return err
}
r := bytes.NewReader(b)
url := fmt.Sprintf("http://localhost:8181/v1/policies/%s", name)
_, err = callOpaAPI("PUT", url, r)
if err != nil {
log.Error(err, "failed to read macros file")
return err
}
return nil
}
func callOpaAPI(method, url string, body io.Reader) ([]byte, error) {
log := logger.WithValues("url", url, "method", method)
req, err := http.NewRequest(method, url, body)
if err != nil {
log.Error(err, "failed create request")
return nil, err
}
c := http.Client{}
resp, err := c.Do(req)
if err != nil {
log.Error(err, "failed to do http request")
return nil, err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error(err, "failed to read response body")
return nil, err
}
if resp.StatusCode != http.StatusOK {
err = errors.New("request is not successfull")
logger.Error(err, string(b), "code", resp.StatusCode)
return nil, err
}
return b, nil
}