/
harbor.go
231 lines (193 loc) · 6.12 KB
/
harbor.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
/*
Copyright (C) 2022 Tenable, 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 vulnerability
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/tenable/terrascan/pkg/iac-providers/output"
"go.uber.org/zap"
)
const (
registryUsername = "HARBOR_REGISTRY_USERNAME"
registryPassword = "HARBOR_REGISTRY_PASSWORD"
vulnerabilityHeader = "X-Accept-Vulnerabilities"
vulnerabilityHeaderValue = "application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0"
skipTLSVerify = "HARBOR_SKIP_TLS"
certificate = "HARBOR_REGISTRY_CACERT"
registryDomain = "HARBOR_REGISTRY_DOMAIN"
)
// ServerCaller interface with client methods
type ServerCaller interface {
Do(req *http.Request) (*http.Response, error)
}
// harborScanner holds external harbor registry methods
type harborScanner interface {
prepareRequest(serverURL string) (*http.Request, error)
sendRequest(caller ServerCaller, req *http.Request) ([]byte, error)
getClient() *http.Client
}
// scanner implementor for harborScanner interface
type hscanner struct{}
// Harbor Harbor container registry
type Harbor struct {
scanner harborScanner
}
func init() {
RegisterContainerRegistry("harbor", &Harbor{
scanner: hscanner{},
})
}
// prepareRequest prepares http request
func (hscanner) prepareRequest(serverURL string) (*http.Request, error) {
username := os.Getenv(registryUsername)
password := os.Getenv(registryPassword)
if username == "" || password == "" {
errorMsg := fmt.Errorf("incomplete authentication details")
zap.S().Error(errorMsg)
return nil, errorMsg
}
req, err := http.NewRequest(http.MethodGet, serverURL, nil)
if err != nil {
errorMsg := fmt.Errorf("error creating harbor server request: %v", err)
zap.S().Error(errorMsg)
return nil, errorMsg
}
req.Header.Add("accept", "application/json")
req.Header.Add(vulnerabilityHeader, vulnerabilityHeaderValue)
req.SetBasicAuth(username, password)
return req, nil
}
// getClient prepares http client
func (hscanner) getClient() *http.Client {
tlsConfig := &tls.Config{}
skipTLS := os.Getenv(skipTLSVerify)
if skipTLS != "" {
if strings.EqualFold(skipTLS, "true") {
tlsConfig.InsecureSkipVerify = true
}
}
cert := os.Getenv(certificate)
if cert != "" {
caCert, err := os.ReadFile(cert)
if err != nil {
errorMsg := fmt.Errorf("client certificate not found")
zap.S().Error(errorMsg)
} else {
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
}
}
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
}
}
// sendRequest sends request to harbor
func (hscanner) sendRequest(caller ServerCaller, req *http.Request) ([]byte, error) {
res, err := caller.Do(req)
if err != nil {
errorMsg := fmt.Errorf("error calling harbor server: %v", err)
zap.S().Error(errorMsg)
return nil, errorMsg
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
errorMsg := fmt.Errorf("error reading response from harbor: %v", err)
zap.S().Error(errorMsg)
return nil, err
}
if res.StatusCode != http.StatusOK {
errMsg := fmt.Errorf(string(body))
return nil, errMsg
}
return body, nil
}
// CheckRegistry verify provided image belongs to harbor registry
func (h *Harbor) checkRegistry(image string) bool {
reg := os.Getenv(registryDomain)
host := GetDomain(image)
return reg != "" && strings.EqualFold(reg, host)
}
// GetVulnerabilities - get vulnerabilities from harbor registry
func (h *Harbor) getVulnerabilities(container output.ContainerDetails, options map[string]interface{}) (vulnerabilities []output.Vulnerability) {
results, err := h.ScanImage(container.Image)
if err != nil {
zap.S().Errorf("error finding vulnerabilities for image %s : %v", container.Image, err)
return
}
if temp, ok := results[vulnerabilityHeaderValue]; ok {
if tempData, ok := temp.(map[string]interface{}); ok {
if tempResults, ok := tempData["vulnerabilities"]; ok {
mapResults, _ := tempResults.([]interface{})
for _, result := range mapResults {
vulnerability := output.Vulnerability{}
if data, ok := result.(map[string]interface{}); ok {
vulnerability.PrepareFromHarborImageScan(data)
vulnerabilities = append(vulnerabilities, vulnerability)
}
}
}
}
}
return
}
// ScanImage get the image scan result from harbor registry
func (h *Harbor) ScanImage(image string) (result map[string]interface{}, err error) {
imageDetails := ImageDetails{}
imageDetails = GetImageDetails(image, imageDetails)
if imageDetails.Tag == "" {
imageDetails.Tag = defaultTagValue
}
reference := imageDetails.Tag
if imageDetails.Digest != "" {
reference = imageDetails.Digest
}
project, repository := getProjectNameAndRepository(imageDetails.Repository)
serverURL := fmt.Sprintf("https://%s/api/v2.0/projects/%s/repositories/%s/artifacts/%s/additions/vulnerabilities",
imageDetails.Registry,
project,
repository,
reference)
client := h.scanner.getClient()
req, err := h.scanner.prepareRequest(serverURL)
if err != nil {
return nil, err
}
data, err := h.scanner.sendRequest(client, req)
if err != nil {
return nil, err
}
if err := json.Unmarshal(data, &result); err != nil {
errorMsg := fmt.Errorf("error unmarshaling harbor server response : %v", err)
zap.S().Error(errorMsg)
return nil, errorMsg
}
return result, nil
}
// getProjectNameAndRepository fetch project and repo name
func getProjectNameAndRepository(name string) (string, string) {
parts := strings.Split(name, "/")
if len(parts) >= 2 {
return parts[0], parts[1]
}
return "", ""
}