/
gitstoreutils.go
356 lines (309 loc) · 10.2 KB
/
gitstoreutils.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
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
package gitregostore
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
"github.com/armosec/armoapi-go/armotypes"
"github.com/go-gota/gota/dataframe"
opapolicy "github.com/kubescape/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/reporthandling/attacktrack/v1alpha1"
"go.uber.org/zap"
)
type storeSetter func(*GitRegoStore, string) error
const (
attackTracksJsonFileName = "attack_tracks.json"
attackTracksPathPrefix = "attack-tracks"
frameworksJsonFileName = "frameworks.json"
securityFrameworksJsonFileName = "security_frameworks.json"
controlsJsonFileName = "controls.json"
rulesJsonFileName = "rules.json"
frameworkControlRelationsFileName = "FWName_CID_CName.csv"
ControlRuleRelationsFileName = "ControlID_RuleName.csv"
defaultConfigInputsFileName = "default_config_inputs.json"
systemPostureExceptionFileName = "exceptions.json"
controlIDRegex = `^(?:[a-z]+|[A-Z]+)(?:[\-][v]?(?:[0-9][\.]?)+)(?:[\-]?[0-9][\.]?)+$`
earliestTagWithSecurityFrameworks = "v1.0.282-rc.0"
)
var (
controlIDRegexCompiled *regexp.Regexp
compileRexOnce sync.Once
storeSetterMapping = map[string]storeSetter{
attackTracksJsonFileName: (*GitRegoStore).setAttackTracks,
frameworksJsonFileName: (*GitRegoStore).setFrameworks,
controlsJsonFileName: (*GitRegoStore).setControls,
rulesJsonFileName: (*GitRegoStore).setRules,
frameworkControlRelationsFileName: (*GitRegoStore).setFrameworkControlRelations,
ControlRuleRelationsFileName: (*GitRegoStore).setControlRuleRelations,
defaultConfigInputsFileName: (*GitRegoStore).setDefaultConfigInputs,
systemPostureExceptionFileName: (*GitRegoStore).setSystemPostureExceptionPolicies,
}
)
type InnerTree []struct {
PATH string `json:"path"`
}
type Tree struct {
TREE InnerTree `json:"tree"`
}
func (gs *GitRegoStore) stripExtention(filename string) string {
if gs.StripFilesExtension {
return strings.Split(filename, ".")[0]
}
return filename
}
// func setURL()
func (gs *GitRegoStore) setURL() {
if p, err := url.JoinPath(gs.BaseUrl, gs.Owner, gs.Repository, gs.Branch, gs.Path, gs.Tag); err == nil {
gs.URL = p
}
}
func (gs *GitRegoStore) setFramework(respStr string) error {
framework := &opapolicy.Framework{}
if err := JSONDecoder(respStr).Decode(framework); err != nil {
return err
}
gs.Frameworks = append(gs.Frameworks, *framework)
return nil
}
func (gs *GitRegoStore) setAttackTrack(respStr string) error {
attackTrack := &v1alpha1.AttackTrack{}
if err := JSONDecoder(respStr).Decode(attackTrack); err != nil {
return err
}
gs.AttackTracks = append(gs.AttackTracks, *attackTrack)
return nil
}
func (gs *GitRegoStore) setSystemPostureExceptionPolicy(respStr string) error {
exceptions := []armotypes.PostureExceptionPolicy{}
if err := JSONDecoder(respStr).Decode(&exceptions); err != nil {
return err
}
gs.SystemPostureExceptionPolicies = append(gs.SystemPostureExceptionPolicies, exceptions...)
return nil
}
func (gs *GitRegoStore) setControl(respStr string) error {
control := &opapolicy.Control{}
if err := JSONDecoder(respStr).Decode(control); err != nil {
return err
}
gs.Controls = append(gs.Controls, *control)
return nil
}
// ======================== set Objects From Release =============================================
func (gs *GitRegoStore) setObjects() error {
var wg sync.WaitGroup
wg.Add(1)
var e error
go func() {
f := true
for {
if err := gs.setObjectsFromReleaseOnce(); err != nil {
e = err
}
if f {
wg.Done() // first update to done
f = false
}
if !gs.Watch {
return
}
time.Sleep(time.Duration(gs.FrequencyPullFromGitMinutes) * time.Minute)
}
}()
wg.Wait()
return e
}
func (gs *GitRegoStore) setObjectsFromReleaseOnce() error {
for kind, storeSetterMappingFunc := range storeSetterMapping {
respStr, err := HttpGetter(gs.httpClient, fmt.Sprintf("%s/%s", gs.URL, gs.stripExtention(kind)))
if err != nil {
return fmt.Errorf("error getting: %s from: '%s' ,error: %s", kind, gs.URL, err)
}
if err = storeSetterMappingFunc(gs, respStr); err != nil {
return err
}
}
return nil
}
func (gs *GitRegoStore) setFrameworks(respStr string) error {
frameworks := []opapolicy.Framework{}
if err := JSONDecoder(respStr).Decode(&frameworks); err != nil {
return err
}
// from a certain tag we have security frameworks
if gs.versionHasSecurityFrameworks() {
respStr1, err := HttpGetter(gs.httpClient, fmt.Sprintf("%s/%s", gs.URL, gs.stripExtention(securityFrameworksJsonFileName)))
if err != nil {
return fmt.Errorf("error getting: %s from: '%s' ,error: %s", securityFrameworksJsonFileName, gs.URL, err)
}
securityFrameworks := []opapolicy.Framework{}
if err := JSONDecoder(respStr1).Decode(&securityFrameworks); err != nil {
return err
}
frameworks = append(frameworks, securityFrameworks...)
}
gs.frameworksLock.Lock()
defer gs.frameworksLock.Unlock()
gs.Frameworks = frameworks
return nil
}
func (gs *GitRegoStore) versionHasSecurityFrameworks() bool {
// check if tag contains numbers
if !hasNumbers(gs.Tag) {
return true
}
tag := strings.Split(gs.Tag, "/")[1]
return tag >= earliestTagWithSecurityFrameworks
}
func (gs *GitRegoStore) setAttackTracks(respStr string) error {
attacktracks := []v1alpha1.AttackTrack{}
if err := JSONDecoder(respStr).Decode(&attacktracks); err != nil {
return err
}
gs.attackTracksLock.Lock()
defer gs.attackTracksLock.Unlock()
gs.AttackTracks = attacktracks
return nil
}
// Set controls set the controls list and attackTrackControls in gitRegoStore
func (gs *GitRegoStore) setControls(respStr string) error {
controls := []opapolicy.Control{}
if err := JSONDecoder(respStr).Decode(&controls); err != nil {
return err
}
gs.controlsLock.Lock()
defer gs.controlsLock.Unlock()
gs.Controls = controls
gs.setAttackTracksControls()
return nil
}
// GetAttackTracksControls sets controls that are related to attack tracks
func (gs *GitRegoStore) setAttackTracksControls() error {
allAttackTrackControls := []opapolicy.Control{}
for i, control := range gs.Controls {
controlCategories := control.GetAllAttackTrackCategories()
if controlCategories != nil && len(controlCategories) > 0 {
allAttackTrackControls = append(allAttackTrackControls, gs.Controls[i])
}
}
gs.attackTrackControlsLock.Lock()
defer gs.attackTrackControlsLock.Unlock()
gs.AttackTrackControls = allAttackTrackControls
return nil
}
func (gs *GitRegoStore) setRules(respStr string) error {
rules := &[]opapolicy.PolicyRule{}
if err := JSONDecoder(respStr).Decode(rules); err != nil {
return err
}
gs.rulesLock.Lock()
defer gs.rulesLock.Unlock()
gs.Rules = *rules
return nil
}
func (gs *GitRegoStore) setDefaultConfigInputs(respStr string) error {
defaultConfigInputs := armotypes.CustomerConfig{}
if err := JSONDecoder(respStr).Decode(&defaultConfigInputs); err != nil {
return err
}
gs.DefaultConfigInputsLock.Lock()
defer gs.DefaultConfigInputsLock.Unlock()
gs.DefaultConfigInputs = defaultConfigInputs
return nil
}
func (gs *GitRegoStore) setSystemPostureExceptionPolicies(respStr string) error {
exceptions := []armotypes.PostureExceptionPolicy{}
if err := JSONDecoder(respStr).Decode(&exceptions); err != nil {
return err
}
gs.systemPostureExceptionPoliciesLock.Lock()
defer gs.systemPostureExceptionPoliciesLock.Unlock()
gs.SystemPostureExceptionPolicies = exceptions
return nil
}
func (gs *GitRegoStore) setFrameworkControlRelations(respStr string) error {
df := dataframe.ReadCSV(strings.NewReader(respStr))
gs.frameworkRelationsLock.Lock()
gs.FrameworkControlRelations = df
gs.frameworkRelationsLock.Unlock()
return nil
}
func (gs *GitRegoStore) setControlRuleRelations(respStr string) error {
df := dataframe.ReadCSV(strings.NewReader(respStr))
gs.controlRelationsLock.Lock()
gs.ControlRuleRelations = df
gs.controlRelationsLock.Unlock()
return nil
}
// JSONDecoder returns JSON decoder for given string
func JSONDecoder(origin string) *json.Decoder {
dec := json.NewDecoder(strings.NewReader(origin))
dec.UseNumber()
return dec
}
func HttpGetter(httpClient *http.Client, fullURL string) (string, error) {
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
return "", err
}
resp, err := httpClient.Do(req)
if err != nil {
return "", err
}
respStr, err := HTTPRespToString(resp)
if err != nil {
return "", err
}
return respStr, nil
}
// HTTPRespToString parses the body as string and checks the HTTP status code, it closes the body reader at the end
// TODO: FIX BUG: status code is not being checked when the body is empty
func HTTPRespToString(resp *http.Response) (string, error) {
if resp == nil || resp.Body == nil {
return "", nil
}
strBuilder := strings.Builder{}
defer resp.Body.Close()
if resp.ContentLength > 0 {
strBuilder.Grow(int(resp.ContentLength))
}
bytesNum, err := io.Copy(&strBuilder, resp.Body)
respStr := strBuilder.String()
if err != nil {
respStrNewLen := len(respStr)
if respStrNewLen > 1024 {
respStrNewLen = 1024
}
return "", fmt.Errorf("HTTP request failed. URL: '%s', Read-ERROR: '%s', HTTP-CODE: '%s', BODY(top): '%s', HTTP-HEADERS: %v, HTTP-BODY-BUFFER-LENGTH: %v", resp.Request.URL.RequestURI(), err, resp.Status, respStr[:respStrNewLen], resp.Header, bytesNum)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
respStrNewLen := len(respStr)
if respStrNewLen > 1024 {
respStrNewLen = 1024
}
err = fmt.Errorf("HTTP request failed. URL: '%s', HTTP-ERROR: '%s', BODY: '%s', HTTP-HEADERS: %v, HTTP-BODY-BUFFER-LENGTH: %v", resp.Request.URL.RequestURI(), resp.Status, respStr[:respStrNewLen], resp.Header, bytesNum)
}
zap.L().Debug("In HTTPRespToString - request end succesfully",
zap.String("URL", resp.Request.URL.String()), zap.Int("contentLength", int(resp.ContentLength)))
return respStr, err
}
func isControlID(c string) bool {
compileRexOnce.Do(func() {
// compile regex only once
controlIDRegexCompiled = regexp.MustCompile(controlIDRegex)
})
return controlIDRegexCompiled.MatchString(c)
}
func hasNumbers(s string) bool {
for _, char := range s {
if char >= '0' && char <= '9' {
return true
}
}
return false
}