forked from neuvector/neuvector
/
repository.go
319 lines (273 loc) · 9.57 KB
/
repository.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
package rest
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/julienschmidt/httprouter"
log "github.com/sirupsen/logrus"
"github.com/neuvector/neuvector/controller/access"
"github.com/neuvector/neuvector/controller/api"
"github.com/neuvector/neuvector/controller/common"
"github.com/neuvector/neuvector/controller/rpc"
"github.com/neuvector/neuvector/controller/scan"
"github.com/neuvector/neuvector/share"
scanUtils "github.com/neuvector/neuvector/share/scan"
)
const (
repositoryDefaultTag = "latest"
maxRepoScanTasks = 8
repoScanTimeout = time.Minute * 20
repoScanLingeringDuration = time.Second * 30
repoScanLongPollTimeout = time.Second * 30
)
var repoScanMgr *longpollOnceMgr
type repoScanKey struct {
api.RESTScanRepoReq
token string
}
type repoScanResult struct {
errCode int
errMsg string
report *api.RESTScanRepoReport
}
func getImageName(req *api.RESTScanRepoReq) string {
return fmt.Sprintf("%s:%s", req.Repository, req.Tag)
}
func newRepoScanMgr() {
repoScanMgr = NewLongPollOnceMgr(repoScanLongPollTimeout, repoScanLingeringDuration, maxRepoScanTasks)
}
// Normalize the request if the registry URL is added to the repo field
func fixRegRepoForAdmCtrl(result *share.ScanResult) {
if result.Registry == "" && result.Repository != "" {
var proto string
regRepoTag := result.Repository
for _, proto = range []string{"http://", "https://"} {
if strings.HasPrefix(regRepoTag, proto) {
regRepoTag = regRepoTag[len(proto):]
break
}
}
if proto == "" {
proto = "https://"
}
if ss := strings.Split(regRepoTag, "/"); len(ss) > 1 {
// see splitDockerDomain() in https://github.com/docker/distribution/blob/release/2.7/reference/normalize.go
if !strings.ContainsAny(ss[0], ".:") && ss[0] != "localhost" {
// there is no registry info in regRepoTag, like "library/centos"
} else {
// there is registry info in regRepoTag, like "docker.io/library/centos" or "10.1.127.3:5000/......" or "localhost/........"
result.Registry = fmt.Sprintf("%s%s/", proto, ss[0])
result.Repository = strings.Join(ss[1:], "/")
}
} else if len(ss) == 1 {
// there is no registry info in regRepoTag, like "centos". Adm ctrl always prefix library, so keep the behavior same here
// if the local image is 'centos', then it is scanned as 'centos' but store the result as 'library/centos'
result.Repository = fmt.Sprintf("library/%s", ss[0])
}
}
}
type repoScanTask struct {
}
func (r *repoScanTask) Run(arg interface{}) interface{} {
req := arg.(*api.RESTScanRepoReq)
log.WithFields(log.Fields{
"registry": req.Registry, "image": getImageName(req),
}).Info("Scan repository start")
var rsr repoScanResult
var proxy string
var err error
// if local image, no need proxy
if req.Registry != "" {
proxy = scan.GetProxy(req.Registry)
}
// default: always scan secrets
scanSecrets := true
ctx, cancel := context.WithTimeout(context.Background(), repoScanTimeout)
defer cancel()
scanReq := &share.ScanImageRequest{
Registry: req.Registry,
Username: req.Username,
Password: req.Password,
Repository: req.Repository,
Tag: req.Tag,
Proxy: proxy,
ScanLayers: req.ScanLayers,
ScanSecrets: scanSecrets,
BaseImage: req.BaseImage,
}
result, err := rpc.ScanImage("", ctx, scanReq)
if result == nil {
// rpc request not made
rsr.errCode = api.RESTErrClusterRPCError
rsr.errMsg = err.Error()
log.WithFields(log.Fields{
"registry": req.Registry, "image": getImageName(req), "error": rsr.errMsg,
}).Error("RPC request fail")
} else if result.Error != share.ScanErrorCode_ScanErrNone {
rsr.errCode = api.RESTErrFailRepoScan
rsr.errMsg = scanUtils.ScanErrorToStr(result.Error)
log.WithFields(log.Fields{
"registry": req.Registry, "image": getImageName(req), "error": rsr.errMsg,
}).Error("Failed to scan repository")
} else {
log.WithFields(log.Fields{
"registry": req.Registry, "image": getImageName(req),
}).Info("Scan repository finish")
// store the scan result so it can be used by admission control
fixRegRepoForAdmCtrl(result)
scanner.StoreRepoScanResult(result)
// build image compliance list and filter the list
cpf := &complianceProfileFilter{filter: make(map[string][]string)}
if cp, filter, err := cacher.GetComplianceProfile(share.DefaultComplianceProfileName, access.NewReaderAccessControl()); err != nil {
log.WithFields(log.Fields{"profile": share.DefaultComplianceProfileName}).Error("Compliance profile not found")
} else {
cpf = &complianceProfileFilter{
disableSystem: cp.DisableSystem, filter: filter, object: &share.CLUSRegistryImageSummary{ImageID: result.ImageID},
}
}
rpt := common.ScanRepoResult2REST(result, cpf.filter)
rpt.Checks = filterComplianceChecks(rpt.Checks, cpf)
vpf := cacher.GetVulnerabilityProfileInterface(share.DefaultVulnerabilityProfileName)
rpt.Vuls = vpf.FilterVulnerabilities(rpt.Vuls, []api.RESTIDName{api.RESTIDName{DisplayName: fmt.Sprintf("%s:%s", rpt.Repository, rpt.Tag)}}, "")
rsr.report = rpt
}
return &rsr
}
func handlerScanRepositoryReq(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug("")
defer r.Body.Close()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
} else if !acc.Authorize(&share.CLUSCIScanDummy{}, nil) {
restRespAccessDenied(w, login)
return
}
if licenseAllowScan() != true {
restRespError(w, http.StatusBadRequest, api.RESTErrLicenseFail)
return
}
body, _ := ioutil.ReadAll(r.Body)
var data api.RESTScanRepoReqData
err := json.Unmarshal(body, &data)
if err != nil || data.Request == nil {
log.WithFields(log.Fields{"error": err}).Error("Request error")
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
// reg.Request.Registry == "", scan local image
req := data.Request
if req.Registry != "" {
u, err := scanUtils.ParseRegistryURI(req.Registry)
if err != nil {
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest,
"Invalid Registry URL")
return
}
req.Registry = u
}
if req.Repository == "" {
log.WithFields(log.Fields{"error": err}).Error("No repository name provided")
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest,
"No repository name provided")
return
}
// Add "library" for dockerhub if not exist
if dockerRegistries.Contains(req.Registry) && strings.Index(req.Repository, "/") == -1 {
req.Repository = fmt.Sprintf("library/%s", req.Repository)
}
if req.Tag == "" {
req.Tag = repositoryDefaultTag
}
// If request is from a different login session, a new scan is triggered even for the same image.
var task repoScanTask
key := repoScanKey{
RESTScanRepoReq: *req,
token: login.getToken(),
}
job, err := repoScanMgr.NewJob(key, &task, req)
switch err {
case errTooManyJobs:
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrFailRepoScan,
fmt.Sprintf("Maximum concurrent scan limit (%v) reached.", maxRepoScanTasks))
return
case errDuplicateJob:
// If a request is already polling the scan, reject the new request from the same session.
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrFailRepoScan,
"Duplicated repository scan request.")
return
}
result, _ := job.Poll()
if result == nil {
log.WithFields(log.Fields{
"registry": req.Registry, "image": getImageName(req),
}).Debug("Keep waiting ...")
w.WriteHeader(http.StatusNotModified)
} else {
ret := result.(*repoScanResult)
if ret.errCode == api.RESTErrClusterRPCError {
restRespError(w, http.StatusInternalServerError, ret.errCode)
} else if ret.errCode != 0 {
restRespErrorMessage(w, http.StatusInternalServerError, ret.errCode, ret.errMsg)
} else {
resp := &api.RESTScanRepoReportData{Report: ret.report}
restRespSuccess(w, r, resp, acc, login, &data, "Request repository scan")
}
}
}
func handlerScanRepositorySubmit(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug("")
defer r.Body.Close()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
} else if !acc.Authorize(&share.CLUSCIScanDummy{}, nil) {
restRespAccessDenied(w, login)
return
}
if licenseAllowScan() != true {
restRespError(w, http.StatusBadRequest, api.RESTErrLicenseFail)
return
}
body, _ := ioutil.ReadAll(r.Body)
var data api.RESTScanRepoSubmitData
err := json.Unmarshal(body, &data)
if err != nil || data.Result == nil {
log.WithFields(log.Fields{"error": err}).Error("Request error")
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
result := data.Result
// Sanity check
if result.ImageID == "" || result.Digest == "" || result.Repository == "" || result.Tag == "" {
log.Error("Missing image metadate in the request")
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, "Missing image metadate in the request")
return
}
if result.Vuls == nil {
result.Vuls = make([]*share.ScanVulnerability, 0)
}
if result.Modules == nil {
result.Modules = make([]*share.ScanModule, 0)
}
if result.SetIdPerms == nil {
result.SetIdPerms = make([]*share.ScanSetIdPermLog, 0)
}
if result.Envs == nil {
result.Envs = make([]string, 0)
}
if result.Cmds == nil {
result.Cmds = make([]string, 0)
}
if result.Labels == nil {
result.Labels = make(map[string]string)
}
if err := scanner.StoreRepoScanResult(result); err != nil {
log.WithFields(log.Fields{"error": err}).Error("Store repo scan result error")
}
restRespSuccess(w, r, nil, acc, login, &data, "Summit repository scan result")
}