This repository was archived by the owner on Dec 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathcpe2cve.go
321 lines (290 loc) · 8.05 KB
/
cpe2cve.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Copyright (c) Facebook, Inc. and its affiliates.
//
// 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 main
import (
"encoding/csv"
"flag"
"fmt"
"io"
"os"
"path"
"runtime"
"runtime/pprof"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/facebookincubator/flog"
"github.com/facebookincubator/nvdtools/cvefeed"
"github.com/facebookincubator/nvdtools/stats"
"github.com/facebookincubator/nvdtools/wfn"
)
func processAll(in <-chan []string, out chan<- []string, caches map[string]*cvefeed.Cache, cfg config, nlines *uint64) {
cpesAt := cfg.CPEsAt - 1
for rec := range in {
if cpesAt >= len(rec) {
flog.Errorf("not enough fields in input (%d)", len(rec))
continue
}
if stats.AreLogged() {
stats.IncrementCounter("line.total")
}
cpeList := strings.Split(rec[cpesAt], cfg.InRecordSeparator)
cpes := make([]*wfn.Attributes, 0, len(cpeList))
for _, uri := range cpeList {
if stats.AreLogged() {
stats.IncrementCounter("cpe.total")
}
attr, err := wfn.Parse(uri)
if err != nil {
flog.Errorf("couldn't parse uri %q: %v", uri, err)
continue
}
cpes = append(cpes, attr)
}
rec[cpesAt] = strings.Join(cpeList, cfg.OutRecordSeparator)
// if performance seems to be the issue, we could try to make these cache.Get's concurrent:
//
// wg := sync.WaitGroup{}
// for provider, cache := range caches {
// provider, cache := provider, cache
// wg.Add(1)
// go func() {
// defer wg.Done()
// for _, matches := range cache.Get(cpes) {
// ...
for provider, cache := range caches {
for _, matches := range cache.Get(cpes) {
ml := len(matches.CPEs)
if stats.AreLogged() {
stats.IncrementCounterBy("cpe.match", int64(ml))
if ml != 0 {
stats.IncrementCounter("line.match")
}
}
matchingCPEs := make([]string, ml)
for i, attr := range matches.CPEs {
if attr == nil {
flog.Errorf("%s matches nil CPE", matches.CVE.ID())
continue
}
matchingCPEs[i] = (*wfn.Attributes)(attr).BindToURI()
}
rec2 := make([]string, len(rec))
copy(rec2, rec)
cvss := matches.CVE.CVSSv3BaseScore()
if cvss == 0 {
cvss = matches.CVE.CVSSv2BaseScore()
}
rec2 = cfg.EraseFields.appendAt(
rec2,
cfg.CVEsAt-1, matches.CVE.ID(),
cfg.MatchesAt-1, strings.Join(matchingCPEs, cfg.OutRecordSeparator),
cfg.CWEsAt-1, strings.Join(matches.CVE.CWEs(), cfg.OutRecordSeparator),
cfg.CVSS2At-1, fmt.Sprintf("%.1f", matches.CVE.CVSSv2BaseScore()),
cfg.CVSS3At-1, fmt.Sprintf("%.1f", matches.CVE.CVSSv3BaseScore()),
cfg.CVSSAt-1, fmt.Sprintf("%.1f", cvss),
cfg.ProviderAt-1, provider,
)
out <- rec2
}
}
n := atomic.AddUint64(nlines, 1)
if n > 0 {
if n%10000 == 0 {
flog.V(1).Infoln(n, "lines processed")
} else if n%1000 == 0 {
flog.V(2).Infoln(n, "lines processed")
} else if n%100 == 0 {
flog.V(3).Infoln(n, "lines processed")
}
}
}
}
func processInput(in io.Reader, out io.Writer, caches map[string]*cvefeed.Cache, cfg config) chan struct{} {
done := make(chan struct{})
procIn := make(chan []string)
procOut := make(chan []string)
r := csv.NewReader(in)
r.Comma = rune(cfg.InFieldSeparator[0])
w := csv.NewWriter(out)
w.Comma = rune(cfg.OutFieldSeparator[0])
// spawn processing goroutines
var linesProcessed uint64
var procWG sync.WaitGroup
procWG.Add(cfg.NumProcessors)
for i := 0; i < cfg.NumProcessors; i++ {
go func() {
processAll(procIn, procOut, caches, cfg, &linesProcessed)
procWG.Done()
}()
}
// write processed results in background
go func() {
for rec := range procOut {
if err := w.Write(rec); err != nil {
flog.Errorf("write error: %v", err)
}
w.Flush()
}
if err := w.Error(); err != nil {
flog.Errorf("write error: %v", err)
}
close(done)
}()
start := time.Now()
// main goroutine reads input and sends it to processors
for line := 1; ; line++ {
rec, err := r.Read()
if err != nil {
if err == io.EOF {
break
}
flog.Errorf("read error at line %d: %v", line, err)
}
procIn <- rec
}
close(procIn)
procWG.Wait()
close(procOut)
flog.V(1).Infof("processed %d lines in %v", linesProcessed, time.Since(start))
return done
}
func init() {
flog.AddFlags(flag.CommandLine, nil)
stats.AddFlags()
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [flags] nvd_feed.xml.gz...\n", path.Base(os.Args[0]))
fmt.Fprintf(os.Stderr, "flags:\n")
flag.PrintDefaults()
if flog.V(1) {
writeConfigFileDefinition(os.Stderr)
}
os.Exit(1)
}
flag.Set("logtostderr", "true")
}
func main() {
// we do it like this because if we exit in Main, deferred functions don't get called
os.Exit(Main())
}
func Main() int {
var cfg config
cfg.addFlags()
provider := flag.String("provider", "", "feed provider. used as a provider name for the feeds passed in through the command line")
cfgFile := flag.String("config", "", "path to a config file (JSON or TOML); see usage to see how it's configured (pass -v=1 flag for verbose help). Mutually exclusive with command line flags => when used, other flags are ignored")
flag.Parse()
var err error
if *cfgFile != "" {
// override config from config file
cfg, err = readConfigFile(*cfgFile)
}
if err == nil {
// add all feeds from cmdline
cfg.addFeedsFromArgs(*provider, flag.Args()...)
err = cfg.validate()
}
if err != nil {
flog.Error(err)
flag.Usage()
}
start := time.Now()
if stats.AreLogged() {
defer func(start time.Time) {
stats.TrackTime("run.time", start, time.Second)
stats.WriteAndLogError()
}(start)
}
flog.V(1).Info("loading NVD feeds...")
var overrides cvefeed.Dictionary
dicts := map[string]cvefeed.Dictionary{} // provider -> dictionary
for provider, files := range cfg.Feeds {
dict, err := cvefeed.LoadJSONDictionary(files...)
if err != nil {
flog.Errorf("failed to load dictionary for provider %s: %v", provider, err)
}
dicts[provider] = dict
}
allEmpty := true
for _, dict := range dicts {
if len(dict) != 0 {
allEmpty = false
break
}
}
if allEmpty {
flog.Error(fmt.Errorf("all dictionaries are empty"))
return -1
}
overrides, err = cvefeed.LoadJSONDictionary(cfg.FeedOverrides...)
if err != nil {
flog.Error(err)
return -1
}
flog.V(1).Infof("...done in %v", time.Since(start))
if len(overrides) != 0 {
start = time.Now()
flog.V(1).Info("applying overrides...")
for _, dict := range dicts {
dict.Override(overrides)
}
flog.V(1).Infof("...done in %v", time.Since(start))
}
caches := map[string]*cvefeed.Cache{}
for provider, dict := range dicts {
caches[provider] = cvefeed.NewCache(dict).SetRequireVersion(cfg.RequireVersion).SetMaxSize(cfg.CacheSize)
}
if cfg.IndexDict {
start = time.Now()
flog.V(1).Info("indexing dictionaries...")
for provider, cache := range caches {
cache.Idx = cvefeed.NewIndex(dicts[provider])
if flog.V(2) {
var named, total int
for k, v := range cache.Idx {
if k != wfn.Any {
named += len(v)
}
total += len(v)
}
flog.Infof("%d out of %d records are named", named, total)
}
}
flog.V(1).Infof("...done in %v", time.Since(start))
}
if cfg.CPUProfile != "" {
f, err := os.Create(cfg.CPUProfile)
if err != nil {
flog.Error(err)
return 1
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
done := processInput(os.Stdin, os.Stdout, caches, cfg)
if cfg.MemoryProfile != "" {
f, err := os.Create(cfg.MemoryProfile)
if err != nil {
flog.Error(err)
return 1
}
runtime.GC()
if err = pprof.WriteHeapProfile(f); err != nil {
flog.Errorf("couldn't write heap profile: %v", err)
}
f.Close()
}
<-done
return 0
}