/
nvd_nist_utils.go
222 lines (189 loc) · 6.34 KB
/
nvd_nist_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
package utils
import (
"encoding/json"
"fmt"
"github.com/rs/zerolog"
"net"
"net/http"
"strings"
"time"
)
type NVDNistResponse struct {
ResultsPerPage int `json:"resultsPerPage"`
StartIndex int `json:"startIndex"`
TotalResults int `json:"totalResults"`
Format string `json:"format"`
Version string `json:"version"`
Timestamp string `json:"timestamp"`
Vulnerabilities []NVDNistResponseCVEItem `json:"vulnerabilities"`
}
type NVDNistResponseCVEItem struct {
CVE NVDNistResponseCVE `json:"cve"`
}
type NVDNistResponseCVE struct {
Id string `json:"id"`
SourceIdentifier string `json:"sourceIdentifier"`
Published string `json:"published"`
LastModified string `json:"lastModified"`
VulnStatus string `json:"vulnStatus"`
Descriptions []struct {
Lang string `json:"lang"`
Value string `json:"value"`
} `json:"descriptions"`
Metrics struct {
CvssMetricV2 []NVDNistResponseCVEMetrics `json:"cvssMetricV2,omitempty"`
CvssMetricV3 []NVDNistResponseCVEMetrics `json:"cvssMetricV31,omitempty"`
} `json:"metrics"`
}
type NVDNistResponseCVEMetrics struct {
CvssData struct {
BaseScore float64 `json:"baseScore"`
BaseSeverity string `json:"baseSeverity"`
} `json:"cvssData"`
}
type FakeCVEParam struct {
Id string
Description string
Severity string
Score float64
}
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . NVDNistUtilsInterface
type NVDNistUtilsInterface interface {
GetCVEs(vendor, product string, logger zerolog.Logger) ([]NVDNistResponseCVEItem, error)
}
type NVDNistUtils struct {
ResultsPerPage int
BaseUrl string
Client http.Client
ApiKey string
}
var timeout = 70 * time.Second
func dialTimeout(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
}
func NewNVDNistUtils(nvdNistApiKey string) NVDNistUtils {
return NVDNistUtils{
ResultsPerPage: 500,
BaseUrl: "https://services.nvd.nist.gov/rest/json/cves/2.0?virtualMatchString=cpe:2.3:a",
Client: http.Client{
Transport: &http.Transport{
Dial: dialTimeout,
},
},
ApiKey: nvdNistApiKey,
}
}
func DoRequestWithRetry(req *http.Request, client *http.Client, logger zerolog.Logger) (*http.Response, error) {
var resp *http.Response
var err error
for i := 0; i < 3; i++ {
resp, err = client.Do(req)
if err == nil {
break
}
logger.Warn().Err(err).Msg("Error making request to NVD Nist API, retrying...")
time.Sleep(5 * time.Second)
}
return resp, err
}
func (nvd NVDNistUtils) GetCVEs(vendor, product string, logger zerolog.Logger) ([]NVDNistResponseCVEItem, error) {
var cves []NVDNistResponseCVEItem
url := fmt.Sprintf("%s:%s:%s&resultsPerPage=%d", nvd.BaseUrl, vendor, product, nvd.ResultsPerPage)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return []NVDNistResponseCVEItem{}, fmt.Errorf("error creating NVD Nist API request\n%w", err)
}
req.Header.Set("User-Agent", "cve-notification-app")
req.Header.Add("apiKey", nvd.ApiKey)
resp, err := DoRequestWithRetry(req, &nvd.Client, logger)
if err != nil {
if strings.Contains(err.Error(), "Client.Timeout exceeded") {
return []NVDNistResponseCVEItem{}, fmt.Errorf("NVD Nist API request timeout exceeded\n%w", err)
}
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return []NVDNistResponseCVEItem{}, fmt.Errorf("NVD Nist API request failed with status code %d", resp.StatusCode)
}
var initialResponse NVDNistResponse
err = json.NewDecoder(resp.Body).Decode(&initialResponse)
if err != nil {
return []NVDNistResponseCVEItem{}, fmt.Errorf("error decoding initial NVD Nist API response\n%w", err)
}
totalResults := initialResponse.TotalResults
logger.Log().Msgf("Total Results: %d", totalResults)
cves = append(cves, initialResponse.Vulnerabilities...)
// Calculate the number of requests needed
numRequests := totalResults / nvd.ResultsPerPage
if totalResults%nvd.ResultsPerPage != 0 {
numRequests++
}
logger.Log().Msgf("Number of Requests: %d", numRequests)
// Make additional requests for remaining results
for i := 1; i < numRequests; i++ {
startIndex := i * nvd.ResultsPerPage
url := fmt.Sprintf("%s:%s:%s&resultsPerPage=%d&startIndex=%d", nvd.BaseUrl, vendor, product, nvd.ResultsPerPage, startIndex)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return []NVDNistResponseCVEItem{}, fmt.Errorf("error creating NVD Nist API request\n%w", err)
}
req.Header.Set("User-Agent", "cve-notification-app")
req.Header.Add("apiKey", nvd.ApiKey)
resp, err := DoRequestWithRetry(req, &nvd.Client, logger)
if err != nil {
return []NVDNistResponseCVEItem{}, fmt.Errorf("error making request to NVD Nist API\n%w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return []NVDNistResponseCVEItem{}, fmt.Errorf("NVD Nist API request failed with status code %d", resp.StatusCode)
}
var additionalResponse NVDNistResponse
err = json.NewDecoder(resp.Body).Decode(&additionalResponse)
if err != nil {
return []NVDNistResponseCVEItem{}, fmt.Errorf("error decoding NVD Nist API response\n%w", err)
}
cves = append(cves, additionalResponse.Vulnerabilities...)
}
return cves, nil
}
func GenerateFakeCVE(params []FakeCVEParam) []NVDNistResponseCVEItem {
var cveItems []NVDNistResponseCVEItem
for _, elem := range params {
item := NVDNistResponseCVEItem{
CVE: NVDNistResponseCVE{
Id: elem.Id,
SourceIdentifier: "",
Published: "",
LastModified: "",
VulnStatus: "",
Descriptions: []struct {
Lang string `json:"lang"`
Value string `json:"value"`
}{
{
Lang: "en",
Value: elem.Description,
},
},
Metrics: struct {
CvssMetricV2 []NVDNistResponseCVEMetrics `json:"cvssMetricV2,omitempty"`
CvssMetricV3 []NVDNistResponseCVEMetrics `json:"cvssMetricV31,omitempty"`
}{
CvssMetricV2: []NVDNistResponseCVEMetrics{
{
CvssData: struct {
BaseScore float64 `json:"baseScore"`
BaseSeverity string `json:"baseSeverity"`
}{
BaseScore: elem.Score,
BaseSeverity: elem.Severity,
},
},
},
},
},
}
cveItems = append(cveItems, item)
}
return cveItems
}