-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
232 lines (191 loc) · 5.34 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
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var (
namespace = flag.String("n", "default", "namespace")
refreshSeconds = flag.Int("r", 60, "refresh pods loop in seconds")
refreshDuration = flag.Int("e", 86400, "rescan image after in seconds")
listener = flag.Bool("l", true, "start listener")
registryFilter = flag.String("rr", "", "registry filter")
clairLocation = flag.String("c", "clair", "clair endpoint")
username = flag.String("u", "", "username")
password = flag.String("p", "", "password")
imagesCache map[string]*containerScan
mutex = &sync.Mutex{}
jobs chan []string
ipAddress string
)
type containerScanResult struct {
Containers []*containerScan
}
type containerScan struct {
LastCheck time.Time
Image string
ScanStarted bool
Report containerVulnerabilityReport
}
type containerVulnerabilityReport struct {
Unapproved []string `json:"unapproved"`
Vulnerabilities []containerVulnerabilityInfo `json:"vulnerabilities"`
}
type containerVulnerabilityInfo struct {
FeatureName string `json:"featurename"`
FeatureVersion string `json:"featureversion"`
Vulnerability string `json:"vulnerability"`
Namespace string `json:"namespace"`
Description string `json:"description"`
Link string `json:"link"`
Severity string `json:"severity"`
FixedBy string `json:"fixedby"`
}
func main() {
flag.Parse()
log.SetFlags(log.Llongfile)
var err error
ipAddress, err = GetDefaultIP()
if err != nil {
log.Fatal(err)
}
log.Printf("Current IP Address %s\n", ipAddress)
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
log.Printf("Authorization - %s:%s", *username, *password)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if *username != "" {
if u, p, ok := r.BasicAuth(); ok {
if u != *username || p != *password {
http.Error(w, "", http.StatusUnauthorized)
return
}
} else {
http.Error(w, "", http.StatusUnauthorized)
return
}
}
// dirty read
var containerImages []*containerScan
for _, v := range imagesCache {
containerImages = append(containerImages, v)
}
imagesBytes, err := json.Marshal(containerScanResult{Containers: containerImages})
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(imagesBytes)
})
if *listener {
go func() {
log.Fatal(http.ListenAndServe(":8080", nil))
}()
}
initScanWorker()
for {
var images []string
pods, err := clientset.CoreV1().Pods(*namespace).List(metav1.ListOptions{})
if err != nil {
log.Println(err.Error())
continue
}
for _, pod := range pods.Items {
for _, container := range pod.Spec.Containers {
images = append(images, container.Image)
}
}
jobs <- images
time.Sleep(time.Duration(*refreshSeconds) * time.Second)
}
}
func initScanWorker() {
jobs = make(chan []string)
go scanWorker()
imagesCache = make(map[string]*containerScan)
}
func scanWorker() {
for {
select {
case imagesToScan := <-jobs:
for _, image := range imagesToScan {
if imagesCache[image] == nil {
imagesCache[image] = &containerScan{Image: image}
log.Printf("Created new ContainerScan %s\n", image)
}
scan := imagesCache[image]
timeResult := scan.LastCheck.IsZero() || time.Now().UTC().After(scan.LastCheck.Add(time.Duration(*refreshDuration)*time.Second))
if timeResult && !scan.ScanStarted {
scan.ScanStarted = true
log.Printf("Starting ContainerScan Job %s\n", image)
result, err := scanContainer(image)
scan.Report = result
if err != nil {
log.Println(err)
}
scan.ScanStarted = false
scan.LastCheck = time.Now().UTC()
log.Printf("ContainerScan %s updated\n", scan.Image)
}
}
imagesCacheReconsiled := make(map[string]*containerScan)
for _, i := range imagesToScan {
imagesCacheReconsiled[i] = imagesCache[i]
}
imagesCache = imagesCacheReconsiled
}
}
}
func scanContainer(image string) (containerVulnerabilityReport, error) {
mutex.Lock()
log.Printf("ScanningContainer %s\n", image)
defer mutex.Unlock()
var err error
var data containerVulnerabilityReport
if len(*registryFilter) > 0 {
if !strings.HasPrefix(image, *registryFilter) {
log.Println("Skipping security scan")
return data, err
}
}
out, err := exec.Command("docker", "pull", image).Output()
log.Println(string(out))
if err != nil {
return data, err
}
if _, err := os.Stat("report.json"); err == nil {
_ = os.Remove("report.json")
}
out, _ = exec.Command("/usr/local/bin/clair-scanner", "-c", *clairLocation, "--ip", ipAddress, "-r", "report.json", "-t", "Medium", image).Output()
log.Println(string(out))
if _, err := os.Stat("report.json"); os.IsNotExist(err) {
return data, fmt.Errorf("no report found for image %s", image)
}
out, err = ioutil.ReadFile("report.json")
if err != nil {
log.Println(err)
return data, err
}
if err = json.Unmarshal(out, &data); err != nil {
log.Println(err)
}
return data, err
}