/
action_mythril.go
276 lines (263 loc) · 7.77 KB
/
action_mythril.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
package action
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
path2 "path"
"strconv"
"strings"
"github.com/hamster-shared/aline-engine/consts"
"github.com/hamster-shared/aline-engine/logger"
"github.com/hamster-shared/aline-engine/model"
"github.com/hamster-shared/aline-engine/output"
"github.com/hamster-shared/aline-engine/utils"
)
// MythRilAction mythRil 合约检查
type MythRilAction struct {
path string
solcVersion string
ctx context.Context
output *output.Output
}
func NewMythRilAction(step model.Step, ctx context.Context, output *output.Output) *MythRilAction {
return &MythRilAction{
path: step.With["path"],
solcVersion: step.With["solc-version"],
ctx: ctx,
output: output,
}
}
func (a *MythRilAction) Pre() error {
stack := a.ctx.Value(STACK).(map[string]interface{})
workdir, ok := stack["workdir"].(string)
if !ok {
return errors.New("workdir is empty")
}
nodeModules := path2.Join(workdir, "node_modules")
files, err := os.ReadDir(nodeModules)
fileContent := ""
var fileNameList []string
if err != nil {
mythRilSolcJson := consts.MythRilSolcJson
fileContent = strings.ReplaceAll(mythRilSolcJson, "%s", "")
} else {
for _, file := range files {
if file.IsDir() {
fileNameList = append(fileNameList, file.Name())
}
}
if len(fileNameList) > 0 {
var reMappings string
for i, name := range fileNameList {
mappings := consts.MythRilSolcJsonReMappings
sprintf := fmt.Sprintf(mappings, name, name)
if i == 0 {
reMappings = reMappings + sprintf
} else {
reMappings = reMappings + "," + sprintf
}
}
mythRilSolcJson := consts.MythRilSolcJson
fileContent = fmt.Sprintf(mythRilSolcJson, reMappings)
} else {
mythRilSolcJson := consts.MythRilSolcJson
fileContent = strings.ReplaceAll(mythRilSolcJson, "%s", "")
}
}
create, err := os.Create(path2.Join(workdir, consts.MythRilSolcJsonName))
if err != nil {
return err
}
_, err = create.WriteString(fileContent)
if err != nil {
return err
}
create.Close()
return nil
}
func (a *MythRilAction) Hook() (*model.ActionResult, error) {
// a.output.NewStep("mythril-check")
stack := a.ctx.Value(STACK).(map[string]interface{})
workdir, ok := stack["workdir"].(string)
if !ok {
return nil, errors.New("workdir is empty")
}
jobName, ok := stack["name"].(string)
if !ok {
return nil, errors.New("get job name error")
}
jobId, ok := stack["id"].(string)
if !ok {
return nil, errors.New("get job id error")
}
userHomeDir, err := os.UserHomeDir()
if err != nil {
logger.Errorf("Failed to get home directory, the file will be saved to the current directory, err is %s", err.Error())
userHomeDir = "."
}
var absPathList []string
basePath := path2.Join(workdir, a.path)
absPathList = utils.GetSuffixFiles(basePath, consts.SolFileSuffix, absPathList)
destDir := path2.Join(userHomeDir, consts.ArtifactoryDir, jobName, consts.CheckName, jobId, consts.MythRilCheckOutputDir)
_, err = os.Stat(destDir)
if os.IsNotExist(err) {
err := os.MkdirAll(destDir, os.ModePerm)
if err != nil {
return nil, err
}
}
for _, path := range absPathList {
_, filenameOnly := utils.GetFilenameWithSuffixAndFilenameOnly(path)
dest := path2.Join(destDir, filenameOnly+consts.SuffixType)
redundantPath, err := utils.GetRedundantPath(basePath, path)
if err != nil {
return nil, err
}
commandTemplate := consts.MythRilCheck
command := fmt.Sprintf(commandTemplate, workdir, path2.Join(a.path, redundantPath), consts.MythRilSolcJsonName)
if a.solcVersion != "" {
command = command + " --solv " + a.solcVersion
}
fields := strings.Fields(command)
out, err := a.ExecuteCommand(fields, workdir)
if out == "" && err != nil {
return nil, err
}
create, err := os.Create(dest)
if err != nil {
return nil, err
}
_, err = create.WriteString(out)
if err != nil {
return nil, err
}
create.Close()
}
a.path = destDir
id, err := strconv.Atoi(jobId)
if err != nil {
return nil, err
}
actionResult := model.ActionResult{
Artifactorys: nil,
Reports: []model.Report{
{
Id: id,
Url: "",
Type: 2,
},
},
}
return &actionResult, err
}
func (a *MythRilAction) Post() error {
open, err := os.Open(a.path)
if err != nil {
return err
}
fileInfo, err := open.Stat()
if err != nil {
return err
}
isDir := fileInfo.IsDir()
if !isDir {
return errors.New("check result path is err")
}
fileInfos, err := open.Readdir(-1)
if err != nil {
return err
}
successFlag := true
var checkResultDetailsList []model.ContractCheckResultDetails[[]model.ContractStyleGuideValidationsReportDetails]
var total int
for _, info := range fileInfos {
path := path2.Join(a.path, info.Name())
var styleGuideValidationsReportDetailsList []model.ContractStyleGuideValidationsReportDetails
file, err := os.Open(path)
if err != nil {
return errors.New("file open fail")
}
defer file.Close()
line := bufio.NewReader(file)
for {
content, _, err := line.ReadLine()
if err == io.EOF {
break
}
s := string(content)
if strings.Contains(s, "The analysis was completed successfully") {
break
}
if strings.Contains(s, "====") {
break
}
var styleGuideValidationsReportDetails model.ContractStyleGuideValidationsReportDetails
styleGuideValidationsReportDetails.Tool = consts.MythRilCheckOutputDir
if strings.Contains(s, "Error:") || strings.Contains(s, "Note:") {
index := strings.Index(s, ":")
styleGuideValidationsReportDetails.Note = s[index+2:]
}
if strings.Contains(s, "-->") {
split := strings.Split(s, ":")
if len(split) < 3 {
continue
}
styleGuideValidationsReportDetails.Line = split[1]
styleGuideValidationsReportDetails.Column = split[2]
}
if styleGuideValidationsReportDetails.Note == "" && styleGuideValidationsReportDetails.Line == "" {
continue
}
if styleGuideValidationsReportDetails.Note == "" && len(styleGuideValidationsReportDetailsList) >= 1 {
styleGuideValidationsReportDetailsList[len(styleGuideValidationsReportDetailsList)-1].Line = styleGuideValidationsReportDetails.Line
styleGuideValidationsReportDetailsList[len(styleGuideValidationsReportDetailsList)-1].Column = styleGuideValidationsReportDetails.Column
} else {
styleGuideValidationsReportDetailsList = append(styleGuideValidationsReportDetailsList, styleGuideValidationsReportDetails)
}
successFlag = false
}
details := model.NewContractCheckResultDetails(strings.Replace(info.Name(), consts.SuffixType, consts.SolFileSuffix, 1), len(styleGuideValidationsReportDetailsList), styleGuideValidationsReportDetailsList)
total = total + details.Issue
checkResultDetailsList = append(checkResultDetailsList, details)
}
var result string
if successFlag {
result = consts.CheckSuccess.Result
} else {
result = consts.CheckFail.Result
}
checkResult := model.NewContractCheckResult(consts.ContractSecurityAnalysisReport.Name, result, consts.ContractSecurityAnalysisReport.Tool, checkResultDetailsList, total)
create, err := os.Create(path2.Join(a.path, consts.CheckResult))
fmt.Println(checkResult)
if err != nil {
return err
}
marshal, err := json.Marshal(checkResult)
if err != nil {
return err
}
_, err = create.WriteString(string(marshal))
if err != nil {
return err
}
create.Close()
return nil
}
func (a *MythRilAction) ExecuteCommand(commands []string, workdir string) (string, error) {
c := exec.CommandContext(a.ctx, commands[0], commands[1:]...) // mac linux
c.Dir = workdir
logger.Debugf("execute mythril check command: %s", strings.Join(commands, " "))
a.output.WriteCommandLine(strings.Join(commands, " "))
out, err := c.CombinedOutput()
fmt.Println(string(out))
a.output.WriteCommandLine(string(out))
if err != nil {
a.output.WriteLine(err.Error())
}
return string(out), err
}