Completed
Push — master ( 76037c...7585f9 )
by kota
09:11 queued 01:58
created

commands.*ServerCmd.Execute   F

Complexity

Conditions 16

Size

Total Lines 89
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 61
dl 0
loc 89
rs 2.4
c 0
b 0
f 0
nop 3

How to fix   Long Method    Complexity   

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:

Complexity

Complex classes like commands.*ServerCmd.Execute often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/* Vuls - Vulnerability Scanner
2
Copyright (C) 2016  Future Architect, Inc. 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
	"fmt"
24
	"net/http"
25
	"os"
26
	"path/filepath"
27
28
	// "github.com/future-architect/vuls/Server"
29
30
	c "github.com/future-architect/vuls/config"
31
	"github.com/future-architect/vuls/exploit"
32
	"github.com/future-architect/vuls/gost"
33
	"github.com/future-architect/vuls/oval"
34
	"github.com/future-architect/vuls/report"
35
	"github.com/future-architect/vuls/server"
36
	"github.com/future-architect/vuls/util"
37
	"github.com/google/subcommands"
38
	cvelog "github.com/kotakanbe/go-cve-dictionary/log"
39
)
40
41
// ServerCmd is subcommand for server
42
type ServerCmd struct {
43
	configPath  string
44
	listen      string
45
	cveDict     c.GoCveDictConf
46
	ovalDict    c.GovalDictConf
47
	gostConf    c.GostConf
48
	exploitConf c.ExploitConf
49
}
50
51
// Name return subcommand name
52
func (*ServerCmd) Name() string { return "server" }
53
54
// Synopsis return synopsis
55
func (*ServerCmd) Synopsis() string { return "Server" }
56
57
// Usage return usage
58
func (*ServerCmd) Usage() string {
59
	return `Server:
60
	Server
61
		[-lang=en|ja]
62
		[-config=/path/to/config.toml]
63
		[-log-dir=/path/to/log]
64
		[-cvss-over=7]
65
		[-ignore-unscored-cves]
66
		[-ignore-unfixed]
67
		[-to-localfile]
68
		[-format-json]
69
		[-http-proxy=http://192.168.0.1:8080]
70
		[-debug]
71
		[-debug-sql]
72
		[-listen=localhost:5515]
73
		[-cvedb-type=sqlite3|mysql|postgres|redis|http]
74
		[-cvedb-sqlite3-path=/path/to/cve.sqlite3]
75
		[-cvedb-url=http://127.0.0.1:1323 or DB connection string]
76
		[-ovaldb-type=sqlite3|mysql|redis|http]
77
		[-ovaldb-sqlite3-path=/path/to/oval.sqlite3]
78
		[-ovaldb-url=http://127.0.0.1:1324 or DB connection string]
79
		[-gostdb-type=sqlite3|mysql|redis|http]
80
		[-gostdb-sqlite3-path=/path/to/gost.sqlite3]
81
		[-gostdb-url=http://127.0.0.1:1325 or DB connection string]
82
		[-exploitdb-type=sqlite3|mysql|redis|http]
83
		[-exploitdb-sqlite3-path=/path/to/exploitdb.sqlite3]
84
		[-exploitdb-url=http://127.0.0.1:1326 or DB connection string]
85
86
		[RFC3339 datetime format under results dir]
87
`
88
}
89
90
// SetFlags set flag
91
func (p *ServerCmd) SetFlags(f *flag.FlagSet) {
92
	f.StringVar(&c.Conf.Lang, "lang", "en", "[en|ja]")
93
	f.BoolVar(&c.Conf.Debug, "debug", false, "debug mode")
94
	f.BoolVar(&c.Conf.DebugSQL, "debug-sql", false, "SQL debug mode")
95
96
	wd, _ := os.Getwd()
97
	defaultConfPath := filepath.Join(wd, "config.toml")
98
	f.StringVar(&p.configPath, "config", defaultConfPath, "/path/to/toml")
99
100
	defaultResultsDir := filepath.Join(wd, "results")
101
	f.StringVar(&c.Conf.ResultsDir, "results-dir", defaultResultsDir, "/path/to/results")
102
103
	defaultLogDir := util.GetDefaultLogDir()
104
	f.StringVar(&c.Conf.LogDir, "log-dir", defaultLogDir, "/path/to/log")
105
106
	f.Float64Var(&c.Conf.CvssScoreOver, "cvss-over", 0,
107
		"-cvss-over=6.5 means Servering CVSS Score 6.5 and over (default: 0 (means Server all))")
108
109
	f.BoolVar(&c.Conf.IgnoreUnscoredCves, "ignore-unscored-cves", false,
110
		"Don't Server the unscored CVEs")
111
112
	f.BoolVar(&c.Conf.IgnoreUnfixed, "ignore-unfixed", false,
113
		"Don't Server the unfixed CVEs")
114
115
	f.StringVar(&c.Conf.HTTPProxy, "http-proxy", "",
116
		"http://proxy-url:port (default: empty)")
117
118
	f.BoolVar(&c.Conf.FormatJSON, "format-json", false, "JSON format")
119
120
	f.BoolVar(&c.Conf.ToLocalFile, "to-localfile", false, "Write report to localfile")
121
	f.StringVar(&p.listen, "listen", "localhost:5515",
122
		"host:port (default: localhost:5515)")
123
124
	f.StringVar(&p.cveDict.Type, "cvedb-type", "",
125
		"DB type of go-cve-dictionary (sqlite3, mysql, postgres, redis or http)")
126
	f.StringVar(&p.cveDict.SQLite3Path, "cvedb-sqlite3-path", "", "/path/to/sqlite3")
127
	f.StringVar(&p.cveDict.URL, "cvedb-url", "",
128
		"http://go-cve-dictionary.com:1323 or DB connection string")
129
130
	f.StringVar(&p.ovalDict.Type, "ovaldb-type", "",
131
		"DB type of goval-dictionary (sqlite3, mysql, postgres, redis or http)")
132
	f.StringVar(&p.ovalDict.SQLite3Path, "ovaldb-sqlite3-path", "", "/path/to/sqlite3")
133
	f.StringVar(&p.ovalDict.URL, "ovaldb-url", "",
134
		"http://goval-dictionary.com:1324 or DB connection string")
135
136
	f.StringVar(&p.gostConf.Type, "gostdb-type", "",
137
		"DB type of gost (sqlite3, mysql, postgres, redis or http)")
138
	f.StringVar(&p.gostConf.SQLite3Path, "gostdb-sqlite3-path", "", "/path/to/sqlite3")
139
	f.StringVar(&p.gostConf.URL, "gostdb-url", "",
140
		"http://gost.com:1325 or DB connection string")
141
142
	f.StringVar(&p.exploitConf.Type, "exploitdb-type", "",
143
		"DB type of exploit (sqlite3, mysql, postgres, redis or http)")
144
	f.StringVar(&p.exploitConf.SQLite3Path, "exploitdb-sqlite3-path", "", "/path/to/sqlite3")
145
	f.StringVar(&p.exploitConf.URL, "exploitdb-url", "",
146
		"http://exploit.com:1326 or DB connection string")
147
}
148
149
// Execute execute
150
func (p *ServerCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
151
	util.Log = util.NewCustomLogger(c.ServerInfo{})
152
	cvelog.SetLogger(c.Conf.LogDir, false, c.Conf.Debug, false)
153
154
	if err := c.Load(p.configPath, ""); err != nil {
155
		util.Log.Errorf("Error loading %s, %s", p.configPath, err)
156
		return subcommands.ExitUsageError
157
	}
158
159
	c.Conf.CveDict.Overwrite(p.cveDict)
160
	c.Conf.OvalDict.Overwrite(p.ovalDict)
161
	c.Conf.Gost.Overwrite(p.gostConf)
162
	c.Conf.Exploit.Overwrite(p.exploitConf)
163
164
	util.Log.Info("Validating config...")
165
	if !c.Conf.ValidateOnReport() {
166
		return subcommands.ExitUsageError
167
	}
168
169
	util.Log.Info("Validating db config...")
170
	if !c.Conf.ValidateOnReportDB() {
171
		return subcommands.ExitUsageError
172
	}
173
174
	if c.Conf.CveDict.URL != "" {
175
		if err := report.CveClient.CheckHealth(); err != nil {
176
			util.Log.Errorf("CVE HTTP server is not running. err: %s", err)
177
			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")
178
			return subcommands.ExitFailure
179
		}
180
	}
181
182
	if c.Conf.OvalDict.URL != "" {
183
		err := oval.Base{}.CheckHTTPHealth()
184
		if err != nil {
185
			util.Log.Errorf("OVAL HTTP server is not running. err: %s", err)
186
			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")
187
			return subcommands.ExitFailure
188
		}
189
	}
190
191
	if c.Conf.Gost.URL != "" {
192
		util.Log.Infof("gost: %s", c.Conf.Gost.URL)
193
		err := gost.Base{}.CheckHTTPHealth()
194
		if err != nil {
195
			util.Log.Errorf("gost HTTP server is not running. err: %s", err)
196
			util.Log.Errorf("Run gost as server mode before reporting or run with `-gostdb-type=sqlite3 -gostdb-sqlite3-path` option instead of -gostdb-url")
197
			return subcommands.ExitFailure
198
		}
199
	}
200
201
	if c.Conf.Exploit.URL != "" {
202
		err := exploit.CheckHTTPHealth()
203
		if err != nil {
204
			util.Log.Errorf("exploit HTTP server is not running. err: %s", err)
205
			util.Log.Errorf("Run go-exploitdb as server mode before reporting")
206
			return subcommands.ExitFailure
207
		}
208
	}
209
210
	dbclient, locked, err := report.NewDBClient(report.DBClientConf{
211
		CveDictCnf:  c.Conf.CveDict,
212
		OvalDictCnf: c.Conf.OvalDict,
213
		GostCnf:     c.Conf.Gost,
214
		ExploitCnf:  c.Conf.Exploit,
215
		DebugSQL:    c.Conf.DebugSQL,
216
	})
217
	if locked {
218
		util.Log.Errorf("SQLite3 is locked. Close other DB connections and try again: %s", err)
219
		return subcommands.ExitFailure
220
	}
221
222
	if err != nil {
223
		util.Log.Errorf("Failed to init DB Clients: %s", err)
224
		return subcommands.ExitFailure
225
	}
226
227
	defer dbclient.CloseDB()
228
229
	http.Handle("/vuls", server.VulsHandler{DBclient: *dbclient})
230
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
231
		fmt.Fprintf(w, "ok")
232
	})
233
	util.Log.Infof("Listening on %s", p.listen)
234
	if err := http.ListenAndServe(p.listen, nil); err != nil {
235
		util.Log.Errorf("Failed to start server: %s", err)
236
		return subcommands.ExitFailure
237
	}
238
	return subcommands.ExitSuccess
239
}
240