/
vulnerability.go
181 lines (164 loc) · 5.61 KB
/
vulnerability.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
// Copyright 2023 sigma
//
// 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 scan
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/aquasecurity/trivy/pkg/types"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/go-sigma/sigma/pkg/configs"
"github.com/go-sigma/sigma/pkg/consts"
"github.com/go-sigma/sigma/pkg/dal/dao"
"github.com/go-sigma/sigma/pkg/dal/models"
"github.com/go-sigma/sigma/pkg/modules/workq"
"github.com/go-sigma/sigma/pkg/modules/workq/definition"
"github.com/go-sigma/sigma/pkg/types/enums"
"github.com/go-sigma/sigma/pkg/utils"
"github.com/go-sigma/sigma/pkg/utils/compress"
"github.com/go-sigma/sigma/pkg/utils/ptr"
"github.com/go-sigma/sigma/pkg/utils/token"
)
func init() {
workq.TopicHandlers[enums.DaemonVulnerability.String()] = definition.Consumer{
Handler: decorator(runnerVulnerability),
MaxRetry: 6,
Concurrency: 1,
Timeout: time.Minute * 10,
}
}
// reportVulnerability ...
type reportVulnerability struct {
Critical int64 `json:"critical"`
High int64 `json:"high"`
Medium int64 `json:"medium"`
Low int64 `json:"low"`
}
func runnerVulnerability(ctx context.Context, artifact *models.Artifact, statusChan chan decoratorArtifactStatus) error {
defer close(statusChan)
statusChan <- decoratorArtifactStatus{Daemon: enums.DaemonVulnerability, Status: enums.TaskCommonStatusDoing, Message: ""}
config := ptr.To(configs.GetConfiguration())
userService := dao.NewUserServiceFactory().New()
userObj, err := userService.GetByUsername(ctx, consts.UserInternal)
if err != nil {
return err
}
tokenService, err := token.NewTokenService(config.Auth.Jwt.PrivateKey)
if err != nil {
return err
}
authorization, err := tokenService.New(userObj.ID, config.Auth.Jwt.Ttl)
if err != nil {
return err
}
image := fmt.Sprintf("%s/%s@%s", utils.TrimHTTP(config.HTTP.InternalEndpoint), artifact.Repository.Name, artifact.Digest)
filename := fmt.Sprintf("%s.trivy.json", uuid.New().String())
cmd := exec.Command("trivy", "image")
if strings.HasPrefix(config.HTTP.InternalEndpoint, "https://") {
cmd.Args = append(cmd.Args, "--insecure")
}
cmd.Args = append(cmd.Args, "-q", "--format", "json", "--parallel", "2", "--scanners", "vuln", "--output", filename,
"--skip-db-update", "--skip-java-db-update")
if utils.IsDir("/opt/trivy") {
cmd.Args = append(cmd.Args, "--offline-scan", "--cache-dir", "/opt/trivy")
}
cmd.Args = append(cmd.Args, image)
cmd.Env = append(cmd.Env, fmt.Sprintf("TRIVY_REGISTRY_TOKEN=%s", authorization))
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
log.Info().Str("artifactDigest", artifact.Digest).Str("command", cmd.String()).Msg("Start scan artifact")
defer func() {
if utils.IsFile(filename) {
err := os.Remove(filename)
if err != nil {
log.Error().Err(err).Msg("Remove file failed")
}
}
}()
if err != nil {
log.Error().Err(err).Msg("Run trivy failed")
statusChan <- decoratorArtifactStatus{
Daemon: enums.DaemonVulnerability,
Status: enums.TaskCommonStatusFailed,
Stdout: stdout.Bytes(),
Stderr: stderr.Bytes(),
Message: fmt.Sprintf("Run trivy failed: %s", err.Error()),
}
return err
}
var trivyObj types.Report
fileContent, err := os.Open(filename)
if err != nil {
log.Error().Err(err).Str("filename", filename).Msg("Open trivy file failed")
statusChan <- decoratorArtifactStatus{
Daemon: enums.DaemonVulnerability,
Status: enums.TaskCommonStatusFailed,
Stdout: []byte(""),
Stderr: []byte(""),
Message: fmt.Sprintf("Open trivy file(%s) failed: %v", filename, err),
}
return err
}
err = json.NewDecoder(fileContent).Decode(&trivyObj)
if err != nil {
log.Error().Err(err).Str("filename", filename).Msg("Decode trivy file failed")
statusChan <- decoratorArtifactStatus{
Daemon: enums.DaemonVulnerability,
Status: enums.TaskCommonStatusFailed,
Stdout: []byte(""),
Stderr: []byte(""),
Message: fmt.Sprintf("Decode trivy file(%s) failed: %v", filename, err),
}
return err
}
var report reportVulnerability
for _, result := range trivyObj.Results {
for _, v := range result.Vulnerabilities {
switch v.Severity {
case "CRITICAL":
report.Critical++
case "HIGH":
report.High++
case "MEDIUM":
report.Medium++
case "LOW":
report.Low++
}
}
}
reportBytes, err := json.Marshal(report)
if err != nil {
log.Error().Err(err).Msg("Marshal report failed")
statusChan <- decoratorArtifactStatus{Daemon: enums.DaemonVulnerability, Status: enums.TaskCommonStatusFailed, Message: err.Error()}
return err
}
compressed, err := compress.Compress(filename)
if err != nil {
log.Error().Err(err).Msg("Compress file failed")
statusChan <- decoratorArtifactStatus{Daemon: enums.DaemonVulnerability, Status: enums.TaskCommonStatusFailed, Message: err.Error()}
return err
}
log.Info().Str("artifactDigest", artifact.Digest).Msg("Success scan artifact")
statusChan <- decoratorArtifactStatus{Daemon: enums.DaemonVulnerability, Status: enums.TaskCommonStatusSuccess, Message: "", Raw: compressed, Result: reportBytes}
return nil
}