commands.*ReportCmd.SetFlags   B
last analyzed

Complexity

Conditions 1

Size

Total Lines 93
Code Lines 75

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 75
dl 0
loc 93
rs 7.8181
c 0
b 0
f 0
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
/* Vuls - Vulnerability Scanner
2
Copyright (C) 2016  Future Corporation , Japan.
3
4
This program is free software: you can redistribute it and/or modify
5
it under the terms of the GNU General Public License as published by
6
the Free Software Foundation, either version 3 of the License, or
7
(at your option) any later version.
8
9
This program is distributed in the hope that it will be useful,
10
but WITHOUT ANY WARRANTY; without even the implied warranty of
11
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
GNU General Public License for more details.
13
14
You should have received a copy of the GNU General Public License
15
along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
*/
17
18
package commands
19
20
import (
21
	"context"
22
	"flag"
23
	"os"
24
	"path/filepath"
25
26
	c "github.com/future-architect/vuls/config"
27
	"github.com/future-architect/vuls/exploit"
28
	"github.com/future-architect/vuls/gost"
29
	"github.com/future-architect/vuls/models"
30
	"github.com/future-architect/vuls/oval"
31
	"github.com/future-architect/vuls/report"
32
	"github.com/future-architect/vuls/util"
33
	"github.com/google/subcommands"
34
	"github.com/k0kubun/pp"
35
	cvelog "github.com/kotakanbe/go-cve-dictionary/log"
36
)
37
38
// ReportCmd is subcommand for reporting
39
type ReportCmd struct {
40
	configPath  string
41
	cveDict     c.GoCveDictConf
42
	ovalDict    c.GovalDictConf
43
	gostConf    c.GostConf
44
	exploitConf c.ExploitConf
45
	httpConf    c.HTTPConf
46
}
47
48
// Name return subcommand name
49
func (*ReportCmd) Name() string { return "report" }
50
51
// Synopsis return synopsis
52
func (*ReportCmd) Synopsis() string { return "Reporting" }
53
54
// Usage return usage
55
func (*ReportCmd) Usage() string {
56
	return `report:
57
	report
58
		[-lang=en|ja]
59
		[-config=/path/to/config.toml]
60
		[-results-dir=/path/to/results]
61
		[-log-dir=/path/to/log]
62
		[-refresh-cve]
63
		[-cvss-over=7]
64
		[-diff]
65
		[-ignore-unscored-cves]
66
		[-ignore-unfixed]
67
		[-ignore-github-dismissed]
68
		[-to-email]
69
		[-to-http]
70
		[-to-slack]
71
		[-to-stride]
72
		[-to-hipchat]
73
		[-to-chatwork]
74
		[-to-telegram]
75
		[-to-localfile]
76
		[-to-s3]
77
		[-to-azure-blob]
78
		[-to-saas]
79
		[-format-json]
80
		[-format-xml]
81
		[-format-one-email]
82
		[-format-one-line-text]
83
		[-format-list]
84
		[-format-full-text]
85
		[-gzip]
86
		[-uuid]
87
		[-http-proxy=http://192.168.0.1:8080]
88
		[-debug]
89
		[-debug-sql]
90
		[-pipe]
91
		[-cvedb-type=sqlite3|mysql|postgres|redis|http]
92
		[-cvedb-sqlite3-path=/path/to/cve.sqlite3]
93
		[-cvedb-url=http://127.0.0.1:1323 or DB connection string]
94
		[-ovaldb-type=sqlite3|mysql|redis|http]
95
		[-ovaldb-sqlite3-path=/path/to/oval.sqlite3]
96
		[-ovaldb-url=http://127.0.0.1:1324 or DB connection string]
97
		[-gostdb-type=sqlite3|mysql|redis|http]
98
		[-gostdb-sqlite3-path=/path/to/gost.sqlite3]
99
		[-gostdb-url=http://127.0.0.1:1325 or DB connection string]
100
		[-exploitdb-type=sqlite3|mysql|redis|http]
101
		[-exploitdb-sqlite3-path=/path/to/exploitdb.sqlite3]
102
		[-exploitdb-url=http://127.0.0.1:1326 or DB connection string]
103
		[-http="http://vuls-report-server"]
104
105
		[RFC3339 datetime format under results dir]
106
`
107
}
108
109
// SetFlags set flag
110
func (p *ReportCmd) SetFlags(f *flag.FlagSet) {
111
	f.StringVar(&c.Conf.Lang, "lang", "en", "[en|ja]")
112
	f.BoolVar(&c.Conf.Debug, "debug", false, "debug mode")
113
	f.BoolVar(&c.Conf.DebugSQL, "debug-sql", false, "SQL debug mode")
114
115
	wd, _ := os.Getwd()
116
	defaultConfPath := filepath.Join(wd, "config.toml")
117
	f.StringVar(&p.configPath, "config", defaultConfPath, "/path/to/toml")
118
119
	defaultResultsDir := filepath.Join(wd, "results")
120
	f.StringVar(&c.Conf.ResultsDir, "results-dir", defaultResultsDir, "/path/to/results")
121
122
	defaultLogDir := util.GetDefaultLogDir()
123
	f.StringVar(&c.Conf.LogDir, "log-dir", defaultLogDir, "/path/to/log")
124
125
	f.BoolVar(&c.Conf.RefreshCve, "refresh-cve", false,
126
		"Refresh CVE information in JSON file under results dir")
127
128
	f.Float64Var(&c.Conf.CvssScoreOver, "cvss-over", 0,
129
		"-cvss-over=6.5 means reporting CVSS Score 6.5 and over (default: 0 (means report all))")
130
131
	f.BoolVar(&c.Conf.Diff, "diff", false,
132
		"Difference between previous result and current result ")
133
134
	f.BoolVar(&c.Conf.IgnoreUnscoredCves, "ignore-unscored-cves", false,
135
		"Don't report the unscored CVEs")
136
137
	f.BoolVar(&c.Conf.IgnoreUnfixed, "ignore-unfixed", false,
138
		"Don't report the unfixed CVEs")
139
140
	f.BoolVar(&c.Conf.IgnoreGitHubDismissed, "ignore-github-dismissed", false,
141
		"Don't report the dismissed CVEs on GitHub Security Alerts")
142
143
	f.StringVar(
144
		&c.Conf.HTTPProxy, "http-proxy", "",
145
		"http://proxy-url:port (default: empty)")
146
147
	f.BoolVar(&c.Conf.FormatJSON, "format-json", false, "JSON format")
148
	f.BoolVar(&c.Conf.FormatXML, "format-xml", false, "XML format")
149
	f.BoolVar(&c.Conf.FormatOneEMail, "format-one-email", false,
150
		"Send all the host report via only one EMail (Specify with -to-email)")
151
	f.BoolVar(&c.Conf.FormatOneLineText, "format-one-line-text", false,
152
		"One line summary in plain text")
153
	f.BoolVar(&c.Conf.FormatList, "format-list", false, "Display as list format")
154
	f.BoolVar(&c.Conf.FormatFullText, "format-full-text", false,
155
		"Detail report in plain text")
156
157
	f.BoolVar(&c.Conf.ToSlack, "to-slack", false, "Send report via Slack")
158
	f.BoolVar(&c.Conf.ToStride, "to-stride", false, "Send report via Stride")
159
	f.BoolVar(&c.Conf.ToHipChat, "to-hipchat", false, "Send report via hipchat")
160
	f.BoolVar(&c.Conf.ToChatWork, "to-chatwork", false, "Send report via chatwork")
161
	f.BoolVar(&c.Conf.ToTelegram, "to-telegram", false, "Send report via Telegram")
162
	f.BoolVar(&c.Conf.ToEmail, "to-email", false, "Send report via Email")
163
	f.BoolVar(&c.Conf.ToSyslog, "to-syslog", false, "Send report via Syslog")
164
	f.BoolVar(&c.Conf.ToLocalFile, "to-localfile", false, "Write report to localfile")
165
	f.BoolVar(&c.Conf.ToS3, "to-s3", false,
166
		"Write report to S3 (bucket/yyyyMMdd_HHmm/servername.json/xml/txt)")
167
	f.BoolVar(&c.Conf.ToHTTP, "to-http", false, "Send report via HTTP POST")
168
	f.BoolVar(&c.Conf.ToAzureBlob, "to-azure-blob", false,
169
		"Write report to Azure Storage blob (container/yyyyMMdd_HHmm/servername.json/xml/txt)")
170
	f.BoolVar(&c.Conf.ToSaas, "to-saas", false,
171
		"Upload report to Future Vuls(https://vuls.biz/) before report")
172
173
	f.BoolVar(&c.Conf.GZIP, "gzip", false, "gzip compression")
174
	f.BoolVar(&c.Conf.UUID, "uuid", false,
175
		"Auto generate of scan target servers and then write to config.toml and scan result")
176
	f.BoolVar(&c.Conf.Pipe, "pipe", false, "Use args passed via PIPE")
177
178
	f.StringVar(&p.cveDict.Type, "cvedb-type", "",
179
		"DB type of go-cve-dictionary (sqlite3, mysql, postgres, redis or http)")
180
	f.StringVar(&p.cveDict.SQLite3Path, "cvedb-sqlite3-path", "", "/path/to/sqlite3")
181
	f.StringVar(&p.cveDict.URL, "cvedb-url", "",
182
		"http://go-cve-dictionary.com:1323 or DB connection string")
183
184
	f.StringVar(&p.ovalDict.Type, "ovaldb-type", "",
185
		"DB type of goval-dictionary (sqlite3, mysql, postgres, redis or http)")
186
	f.StringVar(&p.ovalDict.SQLite3Path, "ovaldb-sqlite3-path", "", "/path/to/sqlite3")
187
	f.StringVar(&p.ovalDict.URL, "ovaldb-url", "",
188
		"http://goval-dictionary.com:1324 or DB connection string")
189
190
	f.StringVar(&p.gostConf.Type, "gostdb-type", "",
191
		"DB type of gost (sqlite3, mysql, postgres, redis or http)")
192
	f.StringVar(&p.gostConf.SQLite3Path, "gostdb-sqlite3-path", "", "/path/to/sqlite3")
193
	f.StringVar(&p.gostConf.URL, "gostdb-url", "",
194
		"http://gost.com:1325 or DB connection string")
195
196
	f.StringVar(&p.exploitConf.Type, "exploitdb-type", "",
197
		"DB type of exploit (sqlite3, mysql, postgres, redis or http)")
198
	f.StringVar(&p.exploitConf.SQLite3Path, "exploitdb-sqlite3-path", "", "/path/to/sqlite3")
199
	f.StringVar(&p.exploitConf.URL, "exploitdb-url", "",
200
		"http://exploit.com:1326 or DB connection string")
201
202
	f.StringVar(&p.httpConf.URL, "http", "", "-to-http http://vuls-report")
203
204
}
205
206
// Execute execute
207
func (p *ReportCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
208
	util.Log = util.NewCustomLogger(c.ServerInfo{})
209
	cvelog.SetLogger(c.Conf.LogDir, false, c.Conf.Debug, false)
210
211
	if err := c.Load(p.configPath, ""); err != nil {
212
		util.Log.Errorf("Error loading %s, %+v", p.configPath, err)
213
		return subcommands.ExitUsageError
214
	}
215
216
	c.Conf.CveDict.Overwrite(p.cveDict)
217
	c.Conf.OvalDict.Overwrite(p.ovalDict)
218
	c.Conf.Gost.Overwrite(p.gostConf)
219
	c.Conf.Exploit.Overwrite(p.exploitConf)
220
	c.Conf.HTTP.Overwrite(p.httpConf)
221
222
	var dir string
223
	var err error
224
	if c.Conf.Diff {
225
		dir, err = report.JSONDir([]string{})
226
	} else {
227
		dir, err = report.JSONDir(f.Args())
228
	}
229
	if err != nil {
230
		util.Log.Errorf("Failed to read from JSON: %+v", err)
231
		return subcommands.ExitFailure
232
	}
233
234
	// report
235
	reports := []report.ResultWriter{
236
		report.StdoutWriter{},
237
	}
238
239
	if c.Conf.ToSlack {
240
		reports = append(reports, report.SlackWriter{})
241
	}
242
243
	if c.Conf.ToStride {
244
		reports = append(reports, report.StrideWriter{})
245
	}
246
247
	if c.Conf.ToHipChat {
248
		reports = append(reports, report.HipChatWriter{})
249
	}
250
251
	if c.Conf.ToChatWork {
252
		reports = append(reports, report.ChatWorkWriter{})
253
	}
254
255
	if c.Conf.ToTelegram {
256
		reports = append(reports, report.TelegramWriter{})
257
	}
258
259
	if c.Conf.ToEmail {
260
		reports = append(reports, report.EMailWriter{})
261
	}
262
263
	if c.Conf.ToSyslog {
264
		reports = append(reports, report.SyslogWriter{})
265
	}
266
267
	if c.Conf.ToHTTP {
268
		reports = append(reports, report.HTTPRequestWriter{})
269
	}
270
271
	if c.Conf.ToLocalFile {
272
		reports = append(reports, report.LocalFileWriter{
273
			CurrentDir: dir,
274
		})
275
	}
276
277
	if c.Conf.ToS3 {
278
		if err := report.CheckIfBucketExists(); err != nil {
279
			util.Log.Errorf("Check if there is a bucket beforehand: %s, err: %+v",
280
				c.Conf.AWS.S3Bucket, err)
281
			return subcommands.ExitUsageError
282
		}
283
		reports = append(reports, report.S3Writer{})
284
	}
285
286
	if c.Conf.ToAzureBlob {
287
		if len(c.Conf.Azure.AccountName) == 0 {
288
			c.Conf.Azure.AccountName = os.Getenv("AZURE_STORAGE_ACCOUNT")
289
		}
290
291
		if len(c.Conf.Azure.AccountKey) == 0 {
292
			c.Conf.Azure.AccountKey = os.Getenv("AZURE_STORAGE_ACCESS_KEY")
293
		}
294
295
		if len(c.Conf.Azure.ContainerName) == 0 {
296
			util.Log.Error("Azure storage container name is required with -azure-container option")
297
			return subcommands.ExitUsageError
298
		}
299
		if err := report.CheckIfAzureContainerExists(); err != nil {
300
			util.Log.Errorf("Check if there is a container beforehand: %s, err: %+v",
301
				c.Conf.Azure.ContainerName, err)
302
			return subcommands.ExitUsageError
303
		}
304
		reports = append(reports, report.AzureBlobWriter{})
305
	}
306
307
	if c.Conf.ToSaas {
308
		if !c.Conf.UUID {
309
			util.Log.Errorf("If you use the -to-saas option, you need to enable the uuid option")
310
			return subcommands.ExitUsageError
311
		}
312
		reports = append(reports, report.SaasWriter{})
313
	}
314
315
	if !(c.Conf.FormatJSON || c.Conf.FormatOneLineText ||
316
		c.Conf.FormatList || c.Conf.FormatFullText || c.Conf.FormatXML) {
317
		c.Conf.FormatList = true
318
	}
319
320
	util.Log.Info("Validating config...")
321
	if !c.Conf.ValidateOnReport() {
322
		return subcommands.ExitUsageError
323
	}
324
325
	var loaded models.ScanResults
326
	if loaded, err = report.LoadScanResults(dir); err != nil {
327
		util.Log.Error(err)
328
		return subcommands.ExitFailure
329
	}
330
	util.Log.Infof("Loaded: %s", dir)
331
332
	var res models.ScanResults
333
	hasError := false
334
	for _, r := range loaded {
335
		if len(r.Errors) == 0 {
336
			res = append(res, r)
337
		} else {
338
			util.Log.Errorf("Ignored since errors occurred during scanning: %s, err: %v",
339
				r.ServerName, r.Errors)
340
			hasError = true
341
		}
342
	}
343
344
	if len(res) == 0 {
345
		return subcommands.ExitFailure
346
	}
347
348
	for _, r := range res {
349
		util.Log.Debugf("%s: %s",
350
			r.ServerInfo(),
351
			pp.Sprintf("%s", c.Conf.Servers[r.ServerName]))
352
	}
353
354
	if c.Conf.UUID {
355
		// Ensure UUIDs of scan target servers in config.toml
356
		if err := report.EnsureUUIDs(p.configPath, res); err != nil {
357
			util.Log.Errorf("Failed to ensure UUIDs. err: %+v", err)
358
			return subcommands.ExitFailure
359
		}
360
	}
361
362
	if !c.Conf.ToSaas {
363
		util.Log.Info("Validating db config...")
364
		if !c.Conf.ValidateOnReportDB() {
365
			return subcommands.ExitUsageError
366
		}
367
368
		if c.Conf.CveDict.URL != "" {
369
			if err := report.CveClient.CheckHealth(); err != nil {
370
				util.Log.Errorf("CVE HTTP server is not running. err: %+v", err)
371
				util.Log.Errorf("Run go-cve-dictionary as server mode before reporting or run with `-cvedb-type=sqlite3 -cvedb-sqlite3-path` option instead of -cvedb-url")
372
				return subcommands.ExitFailure
373
			}
374
		}
375
376
		if c.Conf.OvalDict.URL != "" {
377
			err := oval.Base{}.CheckHTTPHealth()
378
			if err != nil {
379
				util.Log.Errorf("OVAL HTTP server is not running. err: %+v", err)
380
				util.Log.Errorf("Run goval-dictionary as server mode before reporting or run with `-ovaldb-type=sqlite3 -ovaldb-sqlite3-path` option instead of -ovaldb-url")
381
				return subcommands.ExitFailure
382
			}
383
		}
384
385
		if c.Conf.Gost.URL != "" {
386
			util.Log.Infof("gost: %s", c.Conf.Gost.URL)
387
			err := gost.Base{}.CheckHTTPHealth()
388
			if err != nil {
389
				util.Log.Errorf("gost HTTP server is not running. err: %+v", err)
390
				util.Log.Errorf("Run gost as server mode before reporting or run with `-gostdb-type=sqlite3 -gostdb-sqlite3-path` option instead of -gostdb-url")
391
				return subcommands.ExitFailure
392
			}
393
		}
394
395
		if c.Conf.Exploit.URL != "" {
396
			err := exploit.CheckHTTPHealth()
397
			if err != nil {
398
				util.Log.Errorf("exploit HTTP server is not running. err: %+v", err)
399
				util.Log.Errorf("Run go-exploitdb as server mode before reporting")
400
				return subcommands.ExitFailure
401
			}
402
		}
403
		dbclient, locked, err := report.NewDBClient(report.DBClientConf{
404
			CveDictCnf:  c.Conf.CveDict,
405
			OvalDictCnf: c.Conf.OvalDict,
406
			GostCnf:     c.Conf.Gost,
407
			ExploitCnf:  c.Conf.Exploit,
408
			DebugSQL:    c.Conf.DebugSQL,
409
		})
410
		if locked {
411
			util.Log.Errorf("SQLite3 is locked. Close other DB connections and try again. err: %+v", err)
412
			return subcommands.ExitFailure
413
		}
414
		if err != nil {
415
			util.Log.Errorf("Failed to init DB Clients. err: %+v", err)
416
			return subcommands.ExitFailure
417
		}
418
		defer dbclient.CloseDB()
419
420
		if res, err = report.FillCveInfos(*dbclient, res, dir); err != nil {
421
			util.Log.Errorf("%+v", err)
422
			return subcommands.ExitFailure
423
		}
424
	}
425
426
	for _, w := range reports {
427
		if err := w.Write(res...); err != nil {
428
			util.Log.Errorf("Failed to report. err: %+v", err)
429
			return subcommands.ExitFailure
430
		}
431
	}
432
433
	if hasError {
434
		return subcommands.ExitFailure
435
	}
436
437
	return subcommands.ExitSuccess
438
}
439