This repository was archived by the owner on Sep 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmain.go
455 lines (383 loc) · 11.6 KB
/
main.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Copyright 2015 clair 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 (
"bufio"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"sort"
"strconv"
"strings"
"time"
"github.com/coreos/clair/api/v1"
"github.com/coreos/clair/database"
"github.com/fatih/color"
"github.com/kr/text"
)
const (
postLayerURI = "/v1/layers"
getLayerFeaturesURI = "/v1/layers/%s?vulnerabilities"
httpPort = 9279
)
var (
flagEndpoint = flag.String("endpoint", "http://127.0.0.1:6060", "Address to Clair API")
flagMyAddress = flag.String("my-address", "127.0.0.1", "Address from the point of view of Clair")
flagMinimumSeverity = flag.String("minimum-severity", "Negligible", "Minimum severity of vulnerabilities to show (Unknown, Negligible, Low, Medium, High, Critical, Defcon1)")
flagColorMode = flag.String("color", "auto", "Colorize the output (always, auto, never)")
)
type vulnerabilityInfo struct {
vulnerability v1.Vulnerability
feature v1.Feature
severity database.Severity
}
type By func(v1, v2 vulnerabilityInfo) bool
func (by By) Sort(vulnerabilities []vulnerabilityInfo) {
ps := &sorter{
vulnerabilities: vulnerabilities,
by: by,
}
sort.Sort(ps)
}
type sorter struct {
vulnerabilities []vulnerabilityInfo
by func(v1, v2 vulnerabilityInfo) bool
}
func (s *sorter) Len() int {
return len(s.vulnerabilities)
}
func (s *sorter) Swap(i, j int) {
s.vulnerabilities[i], s.vulnerabilities[j] = s.vulnerabilities[j], s.vulnerabilities[i]
}
func (s *sorter) Less(i, j int) bool {
return s.by(s.vulnerabilities[i], s.vulnerabilities[j])
}
func main() {
os.Exit(intMain())
}
func intMain() int {
// Parse command-line arguments.
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] image-id\n\nOptions:\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if len(flag.Args()) != 1 {
flag.Usage()
return 1
}
imageName := flag.Args()[0]
minSeverity, err := database.NewSeverity(*flagMinimumSeverity)
if err != nil {
flag.Usage()
return 1
}
if *flagColorMode == "never" {
color.NoColor = true
} else if *flagColorMode == "always" {
color.NoColor = false
}
// Create a temporary folder.
tmpPath, err := ioutil.TempDir("", "analyze-local-image-")
if err != nil {
log.Fatalf("Could not create temporary folder: %s", err)
}
defer os.RemoveAll(tmpPath)
// Intercept SIGINT / SIGKILl signals.
interrupt := make(chan os.Signal)
signal.Notify(interrupt, os.Interrupt, os.Kill)
// Analyze the image.
analyzeCh := make(chan error, 1)
go func() {
analyzeCh <- AnalyzeLocalImage(imageName, minSeverity, *flagEndpoint, *flagMyAddress, tmpPath)
}()
select {
case <-interrupt:
return 130
case err := <-analyzeCh:
if err != nil {
log.Print(err)
return 1
}
}
return 0
}
func AnalyzeLocalImage(imageName string, minSeverity database.Severity, endpoint, myAddress, tmpPath string) error {
// Save image.
log.Printf("Saving %s to local disk (this may take some time)", imageName)
err := save(imageName, tmpPath)
if err != nil {
return fmt.Errorf("Could not save image: %s", err)
}
// Retrieve history.
log.Println("Retrieving image history")
layerIDs, err := historyFromManifest(tmpPath)
if err != nil {
layerIDs, err = historyFromCommand(imageName)
}
if err != nil || len(layerIDs) == 0 {
return fmt.Errorf("Could not get image's history: %s", err)
}
// Setup a simple HTTP server if Clair is not local.
if !strings.Contains(endpoint, "127.0.0.1") && !strings.Contains(endpoint, "localhost") {
allowedHost := strings.TrimPrefix(endpoint, "http://")
portIndex := strings.Index(allowedHost, ":")
if portIndex >= 0 {
allowedHost = allowedHost[:portIndex]
}
log.Printf("Setting up HTTP server (allowing: %s)\n", allowedHost)
ch := make(chan error)
go listenHTTP(tmpPath, allowedHost, ch)
select {
case err := <-ch:
return fmt.Errorf("An error occured when starting HTTP server: %s", err)
case <-time.After(100 * time.Millisecond):
break
}
tmpPath = "http://" + myAddress + ":" + strconv.Itoa(httpPort)
}
// Analyze layers.
log.Printf("Analyzing %d layers... \n", len(layerIDs))
for i := 0; i < len(layerIDs); i++ {
log.Printf("Analyzing %s\n", layerIDs[i])
if i > 0 {
err = analyzeLayer(endpoint, tmpPath+"/"+layerIDs[i]+"/layer.tar", layerIDs[i], layerIDs[i-1])
} else {
err = analyzeLayer(endpoint, tmpPath+"/"+layerIDs[i]+"/layer.tar", layerIDs[i], "")
}
if err != nil {
return fmt.Errorf("Could not analyze layer: %s", err)
}
}
// Get vulnerabilities.
log.Println("Retrieving image's vulnerabilities")
layer, err := getLayer(endpoint, layerIDs[len(layerIDs)-1])
if err != nil {
return fmt.Errorf("Could not get layer information: %s", err)
}
// Print report.
fmt.Printf("Clair report for image %s (%s)\n", imageName, time.Now().UTC())
if len(layer.Features) == 0 {
fmt.Printf("%s No features have been detected in the image. This usually means that the image isn't supported by Clair.\n", color.YellowString("NOTE:"))
return nil
}
isSafe := true
hasVisibleVulnerabilities := false
var vulnerabilities = make([]vulnerabilityInfo, 0)
for _, feature := range layer.Features {
if len(feature.Vulnerabilities) > 0 {
for _, vulnerability := range feature.Vulnerabilities {
severity := database.Severity(vulnerability.Severity)
isSafe = false
if minSeverity.Compare(severity) > 0 {
continue
}
hasVisibleVulnerabilities = true
vulnerabilities = append(vulnerabilities, vulnerabilityInfo{vulnerability, feature, severity})
}
}
}
// Sort vulnerabilitiy by severity.
priority := func(v1, v2 vulnerabilityInfo) bool {
return v1.severity.Compare(v2.severity) >= 0
}
By(priority).Sort(vulnerabilities)
for _, vulnerabilityInfo := range vulnerabilities {
vulnerability := vulnerabilityInfo.vulnerability
feature := vulnerabilityInfo.feature
severity := vulnerabilityInfo.severity
fmt.Printf("%s (%s)\n", vulnerability.Name, coloredSeverity(severity))
if vulnerability.Description != "" {
fmt.Printf("%s\n\n", text.Indent(text.Wrap(vulnerability.Description, 80), "\t"))
}
fmt.Printf("\tPackage: %s @ %s\n", feature.Name, feature.Version)
if vulnerability.FixedBy != "" {
fmt.Printf("\tFixed version: %s\n", vulnerability.FixedBy)
}
if vulnerability.Link != "" {
fmt.Printf("\tLink: %s\n", vulnerability.Link)
}
fmt.Printf("\tLayer: %s\n", feature.AddedBy)
fmt.Println("")
}
if isSafe {
fmt.Printf("%s No vulnerabilities were detected in your image\n", color.GreenString("Success!"))
} else if !hasVisibleVulnerabilities {
fmt.Printf("%s No vulnerabilities matching the minimum severity level were detected in your image\n", color.YellowString("NOTE:"))
} else {
return fmt.Errorf("A total of %d vulnerabilities have been detected in your image", len(vulnerabilities))
}
return nil
}
func save(imageName, path string) error {
var stderr bytes.Buffer
save := exec.Command("docker", "save", imageName)
save.Stderr = &stderr
extract := exec.Command("tar", "xf", "-", "-C"+path)
extract.Stderr = &stderr
pipe, err := extract.StdinPipe()
if err != nil {
return err
}
save.Stdout = pipe
err = extract.Start()
if err != nil {
return errors.New(stderr.String())
}
err = save.Run()
if err != nil {
return errors.New(stderr.String())
}
err = pipe.Close()
if err != nil {
return err
}
err = extract.Wait()
if err != nil {
return errors.New(stderr.String())
}
return nil
}
func historyFromManifest(path string) ([]string, error) {
mf, err := os.Open(path + "/manifest.json")
if err != nil {
return nil, err
}
defer mf.Close()
// https://github.com/docker/docker/blob/master/image/tarexport/tarexport.go#L17
type manifestItem struct {
Config string
RepoTags []string
Layers []string
}
var manifest []manifestItem
if err = json.NewDecoder(mf).Decode(&manifest); err != nil {
return nil, err
} else if len(manifest) != 1 {
return nil, err
}
var layers []string
for _, layer := range manifest[0].Layers {
layers = append(layers, strings.TrimSuffix(layer, "/layer.tar"))
}
return layers, nil
}
func historyFromCommand(imageName string) ([]string, error) {
var stderr bytes.Buffer
cmd := exec.Command("docker", "history", "-q", "--no-trunc", imageName)
cmd.Stderr = &stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return []string{}, err
}
err = cmd.Start()
if err != nil {
return []string{}, errors.New(stderr.String())
}
var layers []string
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
layers = append(layers, scanner.Text())
}
for i := len(layers)/2 - 1; i >= 0; i-- {
opp := len(layers) - 1 - i
layers[i], layers[opp] = layers[opp], layers[i]
}
return layers, nil
}
func listenHTTP(path, allowedHost string, ch chan error) {
restrictedFileServer := func(path, allowedHost string) http.Handler {
fc := func(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil && strings.EqualFold(host, allowedHost) {
http.FileServer(http.Dir(path)).ServeHTTP(w, r)
return
}
w.WriteHeader(403)
}
return http.HandlerFunc(fc)
}
ch <- http.ListenAndServe(":"+strconv.Itoa(httpPort), restrictedFileServer(path, allowedHost))
}
func analyzeLayer(endpoint, path, layerName, parentLayerName string) error {
payload := v1.LayerEnvelope{
Layer: &v1.Layer{
Name: layerName,
Path: path,
ParentName: parentLayerName,
Format: "Docker",
},
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
return err
}
request, err := http.NewRequest("POST", endpoint+postLayerURI, bytes.NewBuffer(jsonPayload))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != 201 {
body, _ := ioutil.ReadAll(response.Body)
return fmt.Errorf("Got response %d with message %s", response.StatusCode, string(body))
}
return nil
}
func getLayer(endpoint, layerID string) (v1.Layer, error) {
response, err := http.Get(endpoint + fmt.Sprintf(getLayerFeaturesURI, layerID))
if err != nil {
return v1.Layer{}, err
}
defer response.Body.Close()
if response.StatusCode != 200 {
body, _ := ioutil.ReadAll(response.Body)
err := fmt.Errorf("Got response %d with message %s", response.StatusCode, string(body))
return v1.Layer{}, err
}
var apiResponse v1.LayerEnvelope
if err = json.NewDecoder(response.Body).Decode(&apiResponse); err != nil {
return v1.Layer{}, err
} else if apiResponse.Error != nil {
return v1.Layer{}, errors.New(apiResponse.Error.Message)
}
return *apiResponse.Layer, nil
}
func coloredSeverity(severity database.Severity) string {
red := color.New(color.FgRed).SprintFunc()
yellow := color.New(color.FgYellow).SprintFunc()
white := color.New(color.FgWhite).SprintFunc()
switch severity {
case database.HighSeverity, database.CriticalSeverity:
return red(severity)
case database.MediumSeverity:
return yellow(severity)
default:
return white(severity)
}
}