-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathvulndb_controller.go
More file actions
282 lines (246 loc) · 11.5 KB
/
vulndb_controller.go
File metadata and controls
282 lines (246 loc) · 11.5 KB
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
package controllers
import (
"fmt"
"net/url"
"strconv"
"strings"
"time"
"github.com/l3montree-dev/devguard/config"
"github.com/l3montree-dev/devguard/database/models"
"github.com/l3montree-dev/devguard/dtos"
"github.com/l3montree-dev/devguard/normalize"
"github.com/l3montree-dev/devguard/shared"
"github.com/l3montree-dev/devguard/transformer"
"github.com/l3montree-dev/devguard/utils"
"github.com/l3montree-dev/devguard/vulndb"
"github.com/l3montree-dev/devguard/vulndb/scan"
"github.com/labstack/echo/v4"
"github.com/package-url/packageurl-go"
)
type VulnDBController struct {
cveRepository shared.CveRepository
maliciousPackageChecker shared.MaliciousPackageChecker
affectedComponentRepository shared.AffectedComponentRepository
componentRepository shared.ComponentRepository
componentService shared.ComponentService
fixedVersionResolver shared.FixedVersionResolver
dependencyVulnRepository shared.DependencyVulnRepository
}
func NewVulnDBController(cveRepository shared.CveRepository, maliciousPackageChecker shared.MaliciousPackageChecker, affectedComponentRepository shared.AffectedComponentRepository, componentRepository shared.ComponentRepository, componentService shared.ComponentService, fixedVersionResolver shared.FixedVersionResolver, dependencyVulnRepository shared.DependencyVulnRepository) *VulnDBController {
return &VulnDBController{
cveRepository: cveRepository,
maliciousPackageChecker: maliciousPackageChecker,
affectedComponentRepository: affectedComponentRepository,
componentRepository: componentRepository,
componentService: componentService,
fixedVersionResolver: fixedVersionResolver,
dependencyVulnRepository: dependencyVulnRepository,
}
}
// @Summary List all CVEs with pagination
// @Tags CVE Database
// @Description Get a paginated list of CVEs with optional filtering and sorting
// @Tags CVE
// @Produce json
// @Param page query int false "Page number"
// @Param limit query int false "Number of items per page"
// @Param sort query string false "Sort by field, e.g. 'sort[cve]=asc"
// @Param filter query string false "Filter query, e.g. 'filterQuery[cvss][is greater than]=4'"
// @Param confidentialityRequirements query string false "Confidentiality Requirements (low, medium, high), default is medium"
// @Param integrityRequirements query string false "Integrity Requirements (low, medium, high), default is medium"
// @Param availabilityRequirements query string false "Availability Requirements (low, medium, high), default is medium"
// @Success 200 {object} object{pageSize=int,page=int,total=int,data=[]models.CVE} "A paginated list of CVEs"
// @Failure 500 {object} object{message=string} "Internal server error"
// @Router /vulndb [get]
func (c VulnDBController) ListPaged(ctx shared.Context) error {
pagedResp, err := c.cveRepository.FindAllListPaged(
ctx.Request().Context(), nil,
shared.GetPageInfo(ctx),
shared.GetFilterQuery(ctx),
shared.GetSortQuery(ctx),
)
if err != nil {
return echo.NewHTTPError(500, "could not get CVEs").WithInternal(err)
}
env := shared.GetEnvironmental(ctx)
for i, cve := range pagedResp.Data {
risk, vector := vulndb.RiskCalculation(cve, env)
pagedResp.Data[i].Vector = vector
pagedResp.Data[i].Risk = risk
}
return ctx.JSON(200, pagedResp)
}
// @Summary Get a specific CVE by ID
// @Tags CVE Database
// @Description Retrieve details of a specific CVE by its ID, including risk and vector calculations
// @Tags CVE
// @Produce json
// @Param cveID path string true "CVE ID"
// @Param confidentialityRequirements query string false "Confidentiality Requirements (low, medium, high), default is medium"
// @Param integrityRequirements query string false "Integrity Requirements (low, medium, high), default is medium"
// @Param availabilityRequirements query string false "Availability Requirements (low, medium, high), default is medium"
// @Success 200 {object} models.CVE "Details of the specified CVE"
// @Failure 500 {object} object{message=string} "Internal server error"
// @Router /vulndb/{cveID}/ [get]
func (c VulnDBController) Read(ctx shared.Context) error {
cve, err := c.cveRepository.FindCVE(
ctx.Request().Context(), nil,
shared.GetParam(ctx, "cveID"),
)
if err != nil {
return echo.NewHTTPError(500, "could not get CVEs").WithInternal(err)
}
e := shared.GetEnvironmental(ctx)
risk, vector := vulndb.RiskCalculation(cve, e)
cve.Risk = risk
cve.Vector = vector
return ctx.JSON(200, cve)
}
// @Summary Inspect a package URL (PURL) for vulnerabilities
// @Description Analyze a given PURL, determine its match context, and return affected components and related vulnerabilities
// @Tags VulnDB
// @Produce json
// @Param purl path string true "Package URL (PURL) to inspect"
// @Success 200 {object} object "Inspection result including PURL, match context, affected components, and vulnerabilities"
// @Failure 400 {object} object{message=string} "Invalid PURL provided"
// @Failure 500 {object} object{message=string} "Internal server error"
// @Router /vulndb/purl/{purl}/ [get]
func (c VulnDBController) PURLInspect(ctx shared.Context) error {
purlString := shared.GetParam(ctx, "purl")
purlString, err := url.PathUnescape(purlString)
if err != nil {
return echo.NewHTTPError(400, "invalid URL encoding in PURL").WithInternal(err)
}
//delete the last slash if exists
purlString = strings.TrimSuffix(purlString, "/")
purl, err := packageurl.FromString(purlString)
if err != nil {
return echo.NewHTTPError(400, "invalid PURL").WithInternal(err)
}
matchCtx := normalize.ParsePurlForMatching(purl)
purlComparer := scan.NewPurlComparer(c.cveRepository.GetDB(ctx.Request().Context(), nil))
affectedComponents, err := purlComparer.GetAffectedComponents(ctx.Request().Context(), purl)
if err != nil {
return echo.NewHTTPError(500, "failed to retrieve affected components for PURL").WithInternal(err)
}
vulns, err := purlComparer.GetVulns(ctx.Request().Context(), purl)
if err != nil {
return echo.NewHTTPError(500, "failed to retrieve vulnerabilities for PURL").WithInternal(err)
}
_, maliciousPackage, err := c.maliciousPackageChecker.IsMalicious(ctx.Request().Context(), purl.Type, fmt.Sprintf("%s/%s", purl.Namespace, purl.Name), purl.Version)
if err != nil {
return echo.NewHTTPError(400, "failed to check if package is malicious").WithInternal(err)
}
var componentDTO *dtos.ComponentDTO
comp := models.Component{ID: purlString}
if err := c.componentRepository.GetDB(ctx.Request().Context(), nil).Preload("ComponentProject").First(&comp, "id = ?", purlString).Error; err != nil {
// Component not in DB yet — fetch license and project info on-demand and create it
comp, _ = c.componentService.GetLicense(ctx.Request().Context(), comp)
comp, _ = c.componentService.FetchComponentProject(ctx.Request().Context(), comp)
_ = c.componentRepository.SaveBatch(ctx.Request().Context(), nil, []models.Component{comp})
} else if comp.ComponentProject == nil {
// Component exists but has no project info yet — fetch it now
comp, _ = c.componentService.FetchComponentProject(ctx.Request().Context(), comp)
_ = c.componentRepository.SaveBatch(ctx.Request().Context(), nil, []models.Component{comp})
}
if comp.ComponentProject != nil || comp.License != nil {
dto := transformer.ComponentModelToDTO(comp)
componentDTO = &dto
}
return ctx.JSON(200, struct {
PURL string `json:"purl"`
MatchContext *normalize.PurlMatchContext `json:"matchContext"`
Component *dtos.ComponentDTO `json:"component"`
AffectedComponents []dtos.AffectedComponentDTO `json:"affectedComponents"`
Vulns []dtos.VulnInPackageDTO `json:"vulns"`
MaliciousPackage *dtos.OSV `json:"maliciousPackage"`
}{
PURL: purl.ToString(),
MatchContext: matchCtx,
Component: componentDTO,
AffectedComponents: utils.Map(affectedComponents, transformer.AffectedComponentToDTO),
Vulns: utils.Map(vulns, transformer.VulnInPackageToDTO),
MaliciousPackage: maliciousPackage,
})
}
// returns a list of cve ids sorted by the creation date as well as the total amount of entries
// query parameter offset: offset the fetched data by the provided amount
// query parameter limit: limit the amount of entries in the data
func (c VulnDBController) ListIDsByCreationDate(ctx shared.Context) error {
type listIDsRow struct {
CVEID string `gorm:"column:cve"`
CreatedAt time.Time `gorm:"column:created_at"`
}
type responseDTO struct {
Count int `json:"total"`
CVEData []listIDsRow `json:"data"`
}
// use an offset to query only a part of the data
offset := 0
offsetParam := ctx.QueryParam("offset")
if offsetParam != "" {
var err error
offset, err = strconv.Atoi(offsetParam)
if err != nil || offset < 0 {
return echo.NewHTTPError(400, "invalid offset value").WithInternal(err)
}
}
var err error
results := make([]listIDsRow, 0, 1<<18)
// use optional limit parameter to limit the amount of fetched data
limit := 0
limitParam := ctx.QueryParam("limit")
if limitParam != "" {
limit, err = strconv.Atoi(limitParam)
if err != nil || limit <= 0 {
return echo.NewHTTPError(400, "invalid limit value").WithInternal(err)
}
sql := `SELECT cve,created_at FROM cves ORDER BY created_at DESC OFFSET ? LIMIT ?;`
err = c.cveRepository.GetDB(ctx.Request().Context(), nil).Raw(sql, offset, limit).Find(&results).Error
} else {
sql := `SELECT cve,created_at FROM cves ORDER BY created_at DESC OFFSET ?;`
err = c.cveRepository.GetDB(ctx.Request().Context(), nil).Raw(sql, offset).Find(&results).Error
}
if err != nil {
return echo.NewHTTPError(500, "could not get cve ids").WithInternal(err)
}
// build the response and return it
response := responseDTO{
Count: len(results),
CVEData: results,
}
return ctx.JSON(200, response)
}
type ecosystemRow struct {
Ecosystem string `gorm:"ecosystem" json:"ecosystem"`
Count int `gorm:"count" json:"count"`
}
// return the number of vulnerabilities in affected packages per ecosystem
func (c VulnDBController) GetCVEEcosystemDistribution(ctx shared.Context) error {
cveResults := make([]ecosystemRow, 0, 1024)
maliciousPackageResults := make([]ecosystemRow, 0, 64)
// get the amount of CVEs in affected packages per ecosystem
cveSQL := `SELECT LOWER(b.ecosystem) as ecosystem, COUNT(*) FROM cve_affected_component a
LEFT JOIN affected_components b ON b.id = a.affected_component_id
GROUP BY LOWER(b.ecosystem);`
err := c.affectedComponentRepository.GetDB(ctx.Request().Context(), nil).Raw(cveSQL).Find(&cveResults).Error
if err != nil {
return echo.NewHTTPError(500, "could not fetch data from database").WithInternal(err)
}
// do the same thing for malicious packages
maliciousPackagesSQL := `SELECT LOWER(b.ecosystem) as ecosystem, COUNT(*) FROM malicious_packages a
LEFT JOIN malicious_affected_components b ON a.id = b.malicious_package_id
GROUP BY LOWER(b.ecosystem);`
err = c.affectedComponentRepository.GetDB(ctx.Request().Context(), nil).Raw(maliciousPackagesSQL).Find(&maliciousPackageResults).Error
if err != nil {
return echo.NewHTTPError(500, "could not fetch data from database").WithInternal(err)
}
// group the results in a map by cutting the ecosystem identifier before the ':'
ecosystemToAmount := make(map[string]int, len(cveResults))
for _, row := range append(cveResults, maliciousPackageResults...) {
key, _, _ := strings.Cut(row.Ecosystem, ":")
ecosystemToAmount[key] += row.Count
}
// convert the result in a map and return it
return ctx.JSONPretty(200, ecosystemToAmount, config.PrettyJSONIndent)
}