-
Notifications
You must be signed in to change notification settings - Fork 110
/
scap.go
294 lines (256 loc) · 7.34 KB
/
scap.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
/*
Copyright © 2020 Red Hat Inc.
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 (
"bufio"
"context"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/subchen/go-xmldom"
"github.com/ghodss/yaml"
"k8s.io/client-go/kubernetes"
"github.com/openshift/compliance-operator/pkg/utils"
)
const (
contentFileTimeout = 3600
)
// For OpenSCAP content as an XML data stream. Implements ResourceFetcher.
type scapContentDataStream struct {
// Client for Gets
client *kubernetes.Clientset
// Staging objects
dataStream *utils.XMLDocument
resources []string
found map[string][]byte
}
func (c *scapContentDataStream) LoadSource(path string) error {
f, err := openNonEmptyFile(path)
if err != nil {
return err
}
// #nosec
defer f.Close()
xml, err := parseContent(f)
if err != nil {
return err
}
c.dataStream = xml
return nil
}
func parseContent(f *os.File) (*utils.XMLDocument, error) {
return utils.ParseContent(bufio.NewReader(f))
}
// Returns the file, but only after it has been created by the other init container.
// This avoids a race.
func openNonEmptyFile(filename string) (*os.File, error) {
readFileTimeoutChan := make(chan *os.File, 1)
// gosec complains that the file is passed through an evironment variable. But
// this is not a security issue because none of the files are user-provided
cleanFileName := filepath.Clean(filename)
go func() {
for {
// Note that we're cleaning the filename path above.
// #nosec
file, err := os.Open(cleanFileName)
if err == nil {
fileinfo, err := file.Stat()
// Only try to use the file if it already has contents.
if err == nil && fileinfo.Size() > 0 {
readFileTimeoutChan <- file
}
} else if !os.IsNotExist(err) {
fmt.Println(err)
os.Exit(1)
}
time.Sleep(1 * time.Second)
}
}()
select {
case file := <-readFileTimeoutChan:
fmt.Printf("File '%s' found, using.\n", filename)
return file, nil
case <-time.After(time.Duration(contentFileTimeout) * time.Second):
fmt.Println("Timeout. Aborting.")
os.Exit(1)
}
// We shouldn't get here.
return nil, nil
}
func (c *scapContentDataStream) FigureResources(profile string) error {
found := getResourcePaths(c.dataStream, profile)
if len(found) == 0 {
fmt.Printf("no valid checks found in datastream\n")
}
// Always stage the clusteroperators/openshift-apiserver object for version detection.
paths := []string{"/apis/config.openshift.io/v1/clusteroperators/openshift-apiserver"}
paths = append(paths, found...)
c.resources = paths
return nil
}
const (
endPointTag = "ocp-api-endpoint"
endPointTagEnd = endPointTag + "\">"
codeTag = "</code>"
)
// getPathsFromRuleWarning finds the API endpoint from in. The expected structure is:
//
// <warning category="general" lang="en-US"><code class="ocp-api-endpoint">/apis/config.openshift.io/v1/oauths/cluster
// </code></warning>
func getPathFromWarningXML(in string) string {
DBG("%s", in)
apiIndex := strings.Index(in, endPointTag)
if apiIndex == -1 {
return ""
}
apiValueBeginIndex := apiIndex + len(endPointTagEnd)
apiValueEndIndex := strings.Index(in[apiValueBeginIndex:], codeTag)
if apiValueEndIndex == -1 {
return ""
}
return in[apiValueBeginIndex : apiValueBeginIndex+apiValueEndIndex]
}
// Collect the resource paths for objects that this scan needs to obtain.
// The profile will have a series of "selected" checks that we grab all of the path info from.
func getResourcePaths(ds *utils.XMLDocument, profile string) []string {
out := []string{}
selectedChecks := []string{}
// First we find the Profile node, to locate the enabled checks.
DBG("Using profile %s", profile)
nodes := ds.Root.Query("//Profile")
for _, node := range nodes {
profileID := node.GetAttributeValue("id")
if profileID != profile {
continue
}
checks := node.GetChildren("select")
for _, check := range checks {
if check.GetAttributeValue("selected") != "true" {
continue
}
if idRef := check.GetAttributeValue("idref"); idRef != "" {
DBG("selected: %v", idRef)
selectedChecks = append(selectedChecks, idRef)
}
}
}
checkDefinitions := ds.Root.Query("//Rule")
if len(checkDefinitions) == 0 {
DBG("WARNING: No rules to query (invalid datastream)")
return out
}
// For each of our selected checks, collect the required path info.
for _, checkID := range selectedChecks {
var found *xmldom.Node
for _, rule := range checkDefinitions {
if rule.GetAttributeValue("id") == checkID {
found = rule
break
}
}
if found == nil {
DBG("WARNING: Couldn't find a check for id %s", checkID)
continue
}
// This node is called "warning" and contains the path info. It's not an actual "warning" for us here.
warning := found.GetChild("warning")
if warning == nil {
DBG("Couldn't find 'warning' child of check %s", checkID)
continue
}
apiPath := getPathFromWarningXML(warning.XML())
if len(apiPath) == 0 {
continue
}
out = append(out, apiPath)
}
return out
}
func (c *scapContentDataStream) FetchResources() error {
found, err := fetch(c.client, c.resources)
if err != nil {
return err
}
c.found = found
return nil
}
func fetch(client *kubernetes.Clientset, objects []string) (map[string][]byte, error) {
results := map[string][]byte{}
for _, uri := range objects {
err := func() error {
LOG("Fetching URI: '%s'", uri)
req := client.RESTClient().Get().RequestURI(uri)
stream, err := req.Stream(context.TODO())
if err != nil {
return err
}
defer stream.Close()
body, err := ioutil.ReadAll(stream)
if err != nil {
return err
}
if len(body) == 0 {
DBG("no data in request body")
return nil
}
yamlBody, err := yaml.JSONToYAML(body)
if err != nil {
return err
}
results[uri] = yamlBody
return nil
}()
if err != nil {
return nil, err
}
}
return results, nil
}
func (c *scapContentDataStream) SaveResources(to string) error {
return saveResources(to, c.found)
}
func saveResources(rootDir string, data map[string][]byte) error {
for apiPath, fileContents := range data {
saveDir, saveFile, err := getSaveDirectoryAndFileName(rootDir, apiPath)
savePath := path.Join(saveDir, saveFile)
LOG("Saving fetched resource to: '%s'", savePath)
if err != nil {
return err
}
err = os.MkdirAll(saveDir, 0700)
if err != nil {
return err
}
err = ioutil.WriteFile(savePath, fileContents, 0600)
if err != nil {
return err
}
}
return nil
}
// Returns the absolute directory path (including rootDir) and filename for the given apiPath.
func getSaveDirectoryAndFileName(rootDir string, apiPath string) (string, string, error) {
base := path.Base(apiPath)
if base == "." || base == "/" {
return "", "", fmt.Errorf("bad object path: %s", apiPath)
}
subDirs := path.Dir(apiPath)
if subDirs == "." {
return "", "", fmt.Errorf("bad object path: %s", apiPath)
}
return path.Join(rootDir, subDirs), base, nil
}