forked from vulsio/go-cpe-dictionary
/
nvd.go
303 lines (277 loc) · 8.34 KB
/
nvd.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
package nvd
import (
"bytes"
"compress/gzip"
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"math"
"net/http"
"strconv"
"time"
"github.com/cheggaaa/pb"
"github.com/labstack/gommon/log"
"github.com/parnurzeal/gorequest"
gocpe "github.com/sadayuki-matsuno/go-cpe"
c "github.com/sadayuki-matsuno/go-cpe-dictionary/config"
"github.com/sadayuki-matsuno/go-cpe-dictionary/db"
"github.com/sadayuki-matsuno/go-cpe-dictionary/models"
"github.com/sadayuki-matsuno/go-cpe-dictionary/util"
)
// CpeDictionary has cpe-item list
// https://nvd.nist.gov/cpe.cfm
type CpeDictionary struct {
Items []struct {
Name string `xml:"name,attr"`
Cpe23Item struct {
Name string `xml:"name,attr"`
} `xml:"cpe23-item"`
} `xml:"cpe-item"`
}
// V3Feed : NvdV3Feed
// https://scap.nist.gov/schema/nvd/feed/0.1/nvd_cve_feed_json_0.1_beta.schema
type V3Feed struct {
CVEItems []struct {
Configurations struct {
Nodes []struct {
Cpe []struct {
Cpe22URI string `json:"cpe22Uri"`
Cpe23URI string `json:"cpe23Uri"`
} `json:"cpe"`
} `json:"nodes"`
} `json:"configurations"`
} `json:"CVE_Items"`
}
// FetchAndInsertCPE : FetchAndInsertCPE
func FetchAndInsertCPE(driver db.DB) (err error) {
if err = FetchAndInsertCpeDictioanry(driver); err != nil {
return fmt.Errorf("Failed to fetch cpe dictionary. err : %s", err)
}
if err = FetchAndInsertV3Feed(driver); err != nil {
return fmt.Errorf("Failed to fetch nvd v3 feed. err : %s", err)
}
return nil
}
// FetchAndInsertCpeDictioanry : FetchCPE
func FetchAndInsertCpeDictioanry(driver db.DB) (err error) {
var cpeDictionary CpeDictionary
var body string
var errs []error
var resp *http.Response
url := "http://static.nvd.nist.gov/feeds/xml/cpe/dictionary/official-cpe-dictionary_v2.3.xml.gz"
resp, body, errs = gorequest.New().Proxy(c.Conf.HTTPProxy).Get(url).End()
if len(errs) > 0 || resp.StatusCode != 200 {
return fmt.Errorf("HTTP error. errs: %v, url: %s", errs, url)
}
b := bytes.NewBufferString(body)
reader, err := gzip.NewReader(b)
defer reader.Close()
if err != nil {
return fmt.Errorf("Failed to decompress NVD feedfile. url: %s, err: %s", url, err)
}
bytes, err := ioutil.ReadAll(reader)
if err != nil {
return fmt.Errorf("Failed to Read NVD feedfile. url: %s, err: %s", url, err)
}
if err = xml.Unmarshal(bytes, &cpeDictionary); err != nil {
return fmt.Errorf("Failed to unmarshal. url: %s, err: %s", url, err)
}
var cpes []models.CategorizedCpe
if cpes, err = ConvertNvdCpeDictionaryToModel(cpeDictionary); err != nil {
return err
}
if err = driver.InsertCpes(cpes); err != nil {
return fmt.Errorf("Failed to insert cpes. err : %s", err)
}
return nil
}
// FetchAndInsertV3Feed : FetchAndInsertV3Feed
func FetchAndInsertV3Feed(driver db.DB) (err error) {
startYear := 2002
var years []int
if years, err = GetYearsUntilThisYear(startYear); err != nil {
return err
}
urlBlocks := MakeFeedURLBlocks(years, 3)
for _, urls := range urlBlocks {
var nvds []V3Feed
if nvds, err = fetchFeedFileConcurrently(urls); err != nil {
return fmt.Errorf("Failed to get feeds. err : %s", err)
}
var cpes []models.CategorizedCpe
if cpes, err = ConvertNvdV3FeedToModel(nvds); err != nil {
return err
}
if err = driver.InsertCpes(cpes); err != nil {
return fmt.Errorf("Failed to insert cpes. err : %s", err)
}
}
return nil
}
// GetYearsUntilThisYear : GetYearsUntilThisYear
func GetYearsUntilThisYear(startYear int) (years []int, err error) {
var thisYear int
if thisYear, err = strconv.Atoi(time.Now().Format("2006")); err != nil {
return years, fmt.Errorf("Failed to convert this year. err : %s", err)
}
years = make([]int, thisYear-startYear+1)
for i := range years {
years[i] = startYear + i
}
return years, nil
}
// MakeFeedURLBlocks : MakeFeedURLBlocks
func MakeFeedURLBlocks(years []int, n int) (urlBlocks [][]string) {
// http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-2016.xml.gz
formatTemplate := "https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-%d.json.gz"
blockNum := int(math.Ceil(float64(len(years)) / float64(n)))
urlBlocks = make([][]string, blockNum, blockNum)
var i int
for j := range urlBlocks {
var urls []string
for k := 0; k < n; k++ {
urls = append(urls, fmt.Sprintf(formatTemplate, years[i]))
i++
if len(years) <= i {
break
}
}
urlBlocks[j] = urls
}
return urlBlocks
}
func fetchFeedFileConcurrently(urls []string) (nvds []V3Feed, err error) {
reqChan := make(chan string, len(urls))
resChan := make(chan V3Feed, len(urls))
errChan := make(chan error, len(urls))
defer close(reqChan)
defer close(resChan)
defer close(errChan)
go func() {
for _, url := range urls {
reqChan <- url
}
}()
concurrency := len(urls)
tasks := util.GenWorkers(concurrency)
for range urls {
tasks <- func() {
select {
case url := <-reqChan:
log.Infof("Fetching... %s", url)
nvd, err := fetchFeedFile(url)
if err != nil {
errChan <- err
return
}
resChan <- nvd
}
}
}
errs := []error{}
bar := pb.New(len(urls))
bar.Start()
timeout := time.After(10 * 60 * time.Second)
for range urls {
select {
case nvd := <-resChan:
nvds = append(nvds, nvd)
case err := <-errChan:
errs = append(errs, err)
case <-timeout:
return nvds, fmt.Errorf("Timeout Fetching Nvd")
}
bar.Increment()
}
bar.Finish()
// bar.FinishPrint("Finished to fetch CVE information from JVN.")
if 0 < len(errs) {
return nvds, fmt.Errorf("%s", errs)
}
return nvds, nil
}
func fetchFeedFile(url string) (nvd V3Feed, err error) {
var body string
var errs []error
var resp *http.Response
resp, body, errs = gorequest.New().Proxy(c.Conf.HTTPProxy).Get(url).End()
// defer resp.Body.Close()
if len(errs) > 0 || resp == nil || resp.StatusCode != 200 {
return nvd, fmt.Errorf(
"HTTP error. errs: %v, url: %s", errs, url)
}
b := bytes.NewBufferString(body)
reader, err := gzip.NewReader(b)
defer reader.Close()
if err != nil {
return nvd, fmt.Errorf(
"Failed to decompress NVD feedfile. url: %s, err: %s", url, err)
}
bytes, err := ioutil.ReadAll(reader)
if err != nil {
return nvd, fmt.Errorf(
"Failed to Read NVD feedfile. url: %s, err: %s", url, err)
}
if err = json.Unmarshal(bytes, &nvd); err != nil {
return nvd, fmt.Errorf(
"Failed to unmarshal. url: %s, err: %s", url, err)
}
return nvd, nil
}
// ConvertNvdCpeDictionaryToModel :
func ConvertNvdCpeDictionaryToModel(nvd CpeDictionary) (cpes []models.CategorizedCpe, err error) {
for _, item := range nvd.Items {
var cpeItem *gocpe.Item
if cpeItem, err = gocpe.NewItemFromFormattedString(item.Cpe23Item.Name); err != nil {
return cpes, err
}
cpes = append(cpes, models.CategorizedCpe{
Cpe22URI: cpeItem.Uri(),
Cpe23URI: cpeItem.Formatted(),
Part: cpeItem.Part().String(),
Vendor: cpeItem.Vendor().String(),
Product: cpeItem.Product().String(),
Version: cpeItem.Version().String(),
Update: cpeItem.Update().String(),
Edition: cpeItem.Edition().String(),
Language: cpeItem.Language().String(),
SoftwareEdition: cpeItem.SwEdition().String(),
TargetSoftware: cpeItem.TargetSw().String(),
TargetHardware: cpeItem.TargetHw().String(),
Other: cpeItem.Other().String(),
})
}
return cpes, nil
}
// ConvertNvdV3FeedToModel :
func ConvertNvdV3FeedToModel(nvds []V3Feed) (cpes []models.CategorizedCpe, err error) {
for _, nvd := range nvds {
for _, item := range nvd.CVEItems {
for _, node := range item.Configurations.Nodes {
for _, cpe := range node.Cpe {
var cpeItem *gocpe.Item
if cpeItem, err = gocpe.NewItemFromFormattedString(cpe.Cpe23URI); err != nil {
return cpes, err
}
cpes = append(cpes, models.CategorizedCpe{
Cpe22URI: cpeItem.Uri(),
Cpe23URI: cpeItem.Formatted(),
Part: cpeItem.Part().String(),
Vendor: cpeItem.Vendor().String(),
Product: cpeItem.Product().String(),
Version: cpeItem.Version().String(),
Update: cpeItem.Update().String(),
Edition: cpeItem.Edition().String(),
Language: cpeItem.Language().String(),
SoftwareEdition: cpeItem.SwEdition().String(),
TargetSoftware: cpeItem.TargetSw().String(),
TargetHardware: cpeItem.TargetHw().String(),
Other: cpeItem.Other().String(),
})
}
}
}
}
return cpes, nil
}