-
Notifications
You must be signed in to change notification settings - Fork 21
/
utils.go
229 lines (199 loc) · 6.09 KB
/
utils.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
// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// 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 exploitdb
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/cenkalti/backoff"
log "github.com/sirupsen/logrus"
exploitmodels "github.com/vulsio/go-exploitdb/models"
"github.com/openclarity/vmclarity/scanner/families/exploits/common"
)
// genWorkers generates goroutine
// http://qiita.com/na-o-ys/items/65373132b1c5bc973cca
// code taken from https://github.com/future-architect/vuls/blob/bfe0db77b4e16e3099a1e58b8db8f18120a11117/util/util.go#L16
func genWorkers(num int) chan<- func() {
tasks := make(chan func())
for i := 0; i < num; i++ {
go func() {
defer func() {
if p := recover(); p != nil {
log.Errorf("run time panic: %+v", p)
}
}()
for f := range tasks {
f()
}
}()
}
return tasks
}
// stringToArray convert comma separated string into string array.
// example: str1,str2,str3 => [str1,str2,str3]
func stringToArray(str string) []string {
if str == "" {
return nil
}
// remove whitespaces.
str = strings.ReplaceAll(str, " ", "")
cveIDs := strings.Split(str, ",")
return cveIDs
}
func (a *Scanner) getExploitsFromCVEIDs(cveIDs []string) ([]common.Exploit, error) {
var ret []common.Exploit
prefix, err := url.JoinPath(a.config.BaseURL, "cves")
if err != nil {
return nil, fmt.Errorf("failed to join URLPath: %w", err)
}
responses, err := getExploitsViaHTTP(cveIDs, prefix)
if err != nil {
return nil, fmt.Errorf("failed to get exploits via HTTP: %w", err)
}
for _, res := range responses {
exps := []exploitmodels.Exploit{}
if err := json.Unmarshal([]byte(res.json), &exps); err != nil {
return nil, fmt.Errorf("failed to unmarshal json: %w", err)
}
exploits := convertToCommonExploits(exps, res.request.cveID)
ret = append(ret, exploits...)
}
return ret, nil
}
type exploitResponse struct {
request exploitRequest
json string
}
type exploitRequest struct {
cveID string
}
const (
globalTimeoutMin = 10
taskTimeoutSec = 30
)
func getExploitsViaHTTP(cveIDs []string, urlPrefix string) ([]exploitResponse, error) {
var responses []exploitResponse
numCVEs := len(cveIDs)
resChan := make(chan exploitResponse, numCVEs)
errChan := make(chan error, numCVEs)
defer close(resChan)
defer close(errChan)
concurrency := 10
tasks := genWorkers(concurrency)
for _, cveID := range cveIDs {
// declare a new variable to prevent the loop variable
// affecting the closure function below.
cveid := cveID
// Pass task to concurrent workers for processing
tasks <- func() {
req := exploitRequest{cveID: cveid}
URL, err := url.JoinPath(urlPrefix, cveid)
if err != nil {
errChan <- err
return
}
log.Debugf("HTTP Request to %s", URL)
httpGetExploit(URL, req, resChan, errChan)
}
}
timeout := time.After(globalTimeoutMin * time.Minute)
var errs []error
for i := 0; i < numCVEs; i++ {
select {
case res := <-resChan:
responses = append(responses, res)
case err := <-errChan:
errs = append(errs, err)
case <-timeout:
return nil, errors.New("timeout fetching exploits")
}
}
if len(errs) != 0 {
return nil, fmt.Errorf("failed to fetch exploit: %v", errs)
}
return responses, nil
}
func httpGetExploit(url string, req exploitRequest, resChan chan<- exploitResponse, errChan chan<- error) {
var body string
var resp *http.Response
var maxRetries uint64 = 3
requestFn := func() error {
ctx, cancel := context.WithTimeout(context.Background(), taskTimeoutSec*time.Second)
defer cancel()
r, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
resp, err = http.DefaultClient.Do(r.WithContext(ctx)) // nolint:bodyclose
if err != nil {
return fmt.Errorf("failed to send GET request to url: %s: %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("received error response to GET request to url: %s, resp: %v: %w", url, resp, err)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
body = string(b)
return nil
}
notifyFn := func(err error, t time.Duration) {
log.Warnf("Failed to HTTP GET. retrying in %s seconds: %+v", t, err)
}
err := backoff.RetryNotify(requestFn, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), maxRetries), notifyFn)
if err != nil {
errChan <- fmt.Errorf("HTTP Error %w", err)
return
}
resChan <- exploitResponse{
request: req,
json: body,
}
}
// convertToCommonExploits converts exploit model to vmclarity model.
func convertToCommonExploits(es []exploitmodels.Exploit, cveID string) []common.Exploit {
// nolint:prealloc
var exploits []common.Exploit
for _, e := range es {
exp := common.Exploit{
// Exploit DB calculates a unique ID like this:
// https://github.com/vulsio/go-exploitdb/blob/master/fetcher/inthewild.go#L110
// which takes into account the URL, CVEID and some
// other fields which are specific to the SourceDB
// type. For now we'll use the same thing, but we may
// want to standardise how we generate that ID across
// all our Exploit scanners so that if multiple
// scanners find the same exploit from the same source
// DB we can match them together and de-duplicate.
ID: e.ExploitUniqueID,
Name: "",
Title: "",
Description: e.Description,
CveID: cveID,
URLs: []string{e.URL},
SourceDB: string(e.ExploitType),
}
exploits = append(exploits, exp)
}
return exploits
}