Completed
Pull Request — master (#769)
by
unknown
13:08 queued 01:57
created

scan.contentConvertVinfos   F

Complexity

Conditions 21

Size

Total Lines 76
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 49
dl 0
loc 76
rs 0
c 0
b 0
f 0
nop 2

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 scan.contentConvertVinfos 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 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 scan
19
20
import (
21
	"bufio"
22
	"encoding/json"
23
	"fmt"
24
	"net"
25
	"regexp"
26
	"strings"
27
	"time"
28
29
	"github.com/future-architect/vuls/config"
30
	"github.com/future-architect/vuls/models"
31
	"github.com/hashicorp/go-version"
32
	"github.com/sirupsen/logrus"
33
	"io/ioutil"
34
	"net/http"
35
)
36
37
type base struct {
38
	ServerInfo config.ServerInfo
39
	Distro     config.Distro
40
	Platform   models.Platform
41
	osPackages
42
43
	log  *logrus.Entry
44
	errs []error
45
}
46
47
//Command is for check dependence
48
type Command struct {
49
	Command string
50
	Name    string
51
}
52
53
func (l *base) scanWp() (err error) {
54
	if len(l.ServerInfo.WpPath) == 0 && len(l.ServerInfo.WpToken) == 0 {
55
		return nil
56
	}
57
	if len(l.ServerInfo.WpPath) == 0 {
58
		return fmt.Errorf("not found : WpPath")
59
	}
60
	if len(l.ServerInfo.WpToken) == 0 {
61
		return fmt.Errorf("not found : WpToken")
62
	}
63
64
	cmds := []Command{{Command: "wp cli", Name: "wp"}}
65
	for _, cmd := range cmds {
66
		if r := exec(l.ServerInfo, cmd.Command, noSudo); !r.isSuccess() {
67
			return fmt.Errorf("%s command not installed", cmd.Name)
68
		}
69
	}
70
71
	var vinfos []models.VulnInfo
72
	if vinfos, err = detectWp(l); err != nil {
73
		l.log.Errorf("Failed to scan wordpress: %s", err)
74
		return err
75
	}
76
	l.WpVulnInfos = map[string]models.VulnInfo{}
77
	for _, vinfo := range vinfos {
78
		l.WpVulnInfos[vinfo.CveID] = vinfo
79
	}
80
81
	return
82
}
83
84
//WpCveInfos is for wpvulndb's json
85
type WpCveInfos struct {
86
	ReleaseDate     string      `json:"release_date"`
87
	ChangelogURL    string      `json:"changelog_url"`
88
	Status          string      `json:"status"`
89
	LatestVersion   string      `json:"latest_version"`
90
	LastUpdated     string      `json:"last_updated"`
91
	Popular         bool        `json:"popular"`
92
	Vulnerabilities []WpCveInfo `json:"vulnerabilities"`
93
	Error           string      `json:"error"`
94
}
95
96
//WpCveInfo is for wpvulndb's json
97
type WpCveInfo struct {
98
	ID            int        `json:"id"`
99
	Title         string     `json:"title"`
100
	CreatedAt     string     `json:"created_at"`
101
	UpdatedAt     string     `json:"updated_at"`
102
	PublishedDate string     `json:"published_date"`
103
	VulnType      string     `json:"vuln_type"`
104
	References    References `json:"references"`
105
	FixedIn       string     `json:"fixed_in"`
106
}
107
108
//References is for wpvulndb's json
109
type References struct {
110
	URL     []string `json:"url"`
111
	Cve     []string `json:"cve"`
112
	Secunia []string `json:"secunia"`
113
}
114
115
func detectWp(c *base) (vinfos []models.VulnInfo, err error) {
116
	var coreVulns []models.VulnInfo
117
	if coreVulns, err = detectWpCore(c); err != nil {
118
		return
119
	}
120
	vinfos = append(vinfos, coreVulns...)
121
122
	var themeVulns []models.VulnInfo
123
	if themeVulns, err = detectWpTheme(c); err != nil {
124
		return
125
	}
126
	vinfos = append(vinfos, themeVulns...)
127
128
	var pluginVulns []models.VulnInfo
129
	if pluginVulns, err = detectWpPlugin(c); err != nil {
130
		return
131
	}
132
	vinfos = append(vinfos, pluginVulns...)
133
134
	return
135
}
136
137
func detectWpCore(c *base) (vinfos []models.VulnInfo, err error) {
138
	cmd := fmt.Sprintf("wp core version --path=%s", c.ServerInfo.WpPath)
139
140
	var coreVersion string
141
	var r execResult
142
	if r = exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
143
		tmp := strings.Split(r.Stdout, ".")
144
		coreVersion = strings.Join(tmp, "")
145
		coreVersion = strings.TrimRight(coreVersion, "\r\n")
146
		if len(coreVersion) == 0 {
147
			return
148
		}
149
	}
150
	if !r.isSuccess() {
151
		return vinfos, fmt.Errorf("%s", cmd)
152
	}
153
154
	url := fmt.Sprintf("https://wpvulndb.com/api/v3/wordpresses/%s", coreVersion)
155
	token := fmt.Sprintf("Token token=%s", c.ServerInfo.WpToken)
156
	var req *http.Request
157
	req, err = http.NewRequest("GET", url, nil)
158
	if err != nil {
159
		return
160
	}
161
	req.Header.Set("Authorization", token)
162
	client := new(http.Client)
163
	var resp *http.Response
164
	resp, err = client.Do(req)
165
	if err != nil {
166
		return
167
	}
168
	if resp.StatusCode != 200 && resp.StatusCode != 404 {
169
		return vinfos, fmt.Errorf("status: %s", resp.Status)
170
	}
171
	body, _ := ioutil.ReadAll(resp.Body)
172
	defer resp.Body.Close()
173
	if resp.StatusCode == 404 {
174
		var jsonError WpCveInfos
175
		if err = json.Unmarshal([]byte(string(body)), &jsonError); err != nil {
176
			return
177
		}
178
		if jsonError.Error == "HTTP Token: Access denied.\n" {
179
			c.log.Errorf("wordpress: HTTP Token: Access denied.")
180
		} else {
181
			return vinfos, fmt.Errorf("status: %s", resp.Status)
182
		}
183
	}
184
	coreConvertVinfos(string(body))
185
	return
186
}
187
188
func coreConvertVinfos(stdout string) (vinfos []models.VulnInfo, err error) {
189
	data := map[string]WpCveInfos{}
190
	if err = json.Unmarshal([]byte(stdout), &data); err != nil {
191
		var jsonError WpCveInfos
192
		if err = json.Unmarshal([]byte(stdout), &jsonError); err != nil {
193
			return
194
		}
195
	}
196
	for _, i := range data {
197
		if len(i.Vulnerabilities) == 0 {
198
			continue
199
		}
200
		for _, vulnerability := range i.Vulnerabilities {
201
			if len(vulnerability.References.Cve) == 0 {
202
				continue
203
			}
204
			NotFixedYet := false
205
			if len(vulnerability.FixedIn) == 0 {
206
				NotFixedYet = true
207
			}
208
			var cveIDs []string
209
			for _, cveNumber := range vulnerability.References.Cve {
210
				cveIDs = append(cveIDs, "CVE-"+cveNumber)
211
			}
212
213
			for _, cveID := range cveIDs {
214
				vinfos = append(vinfos, models.VulnInfo{
215
					CveID: cveID,
216
					CveContents: models.NewCveContents(
217
						models.CveContent{
218
							CveID: cveID,
219
							Title: vulnerability.Title,
220
						},
221
					),
222
					AffectedPackages: models.PackageStatuses{
223
						{
224
							NotFixedYet: NotFixedYet,
225
						},
226
					},
227
				})
228
			}
229
		}
230
	}
231
	return
232
}
233
234
//WpStatus is for wp command
235
type WpStatus struct {
236
	Name    string `json:"name"`
237
	Status  string `json:"status"`
238
	Update  string `json:"update"`
239
	Version string `json:"version"`
240
}
241
242
func detectWpTheme(c *base) (vinfos []models.VulnInfo, err error) {
243
	cmd := fmt.Sprintf("wp theme list --path=%s --format=json", c.ServerInfo.WpPath)
244
245
	var themes []WpStatus
246
	var r execResult
247
	if r = exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
248
		if err = json.Unmarshal([]byte(r.Stdout), &themes); err != nil {
249
			return
250
		}
251
	}
252
	if !r.isSuccess() {
253
		return vinfos, fmt.Errorf("%s", cmd)
254
	}
255
256
	for _, theme := range themes {
257
		url := fmt.Sprintf("https://wpvulndb.com/api/v3/themes/%s", theme.Name)
258
		token := fmt.Sprintf("Token token=%s", c.ServerInfo.WpToken)
259
		var req *http.Request
260
		req, err = http.NewRequest("GET", url, nil)
261
		if err != nil {
262
			return
263
		}
264
		req.Header.Set("Authorization", token)
265
		client := new(http.Client)
266
		var resp *http.Response
267
		resp, err = client.Do(req)
268
		if err != nil {
269
			return
270
		}
271
		if resp.StatusCode != 200 && resp.StatusCode != 404 {
272
			return vinfos, fmt.Errorf("status: %s", resp.Status)
273
		}
274
		body, _ := ioutil.ReadAll(resp.Body)
275
		defer resp.Body.Close()
276
		if resp.StatusCode == 404 {
277
			var jsonError WpCveInfos
278
			if err = json.Unmarshal([]byte(string(body)), &jsonError); err != nil {
279
				return
280
			}
281
			if jsonError.Error == "HTTP Token: Access denied.\n" {
282
				c.log.Errorf("wordpress: HTTP Token: Access denied.")
283
			} else if jsonError.Error == "Not found" {
284
				c.log.Errorf("wordpress: %s not found", theme.Name)
285
			} else {
286
				return vinfos, fmt.Errorf("status: %s", resp.Status)
287
			}
288
		}
289
		contentConvertVinfos(string(body), theme)
290
	}
291
	return
292
}
293
294
func detectWpPlugin(c *base) (vinfos []models.VulnInfo, err error) {
295
	cmd := fmt.Sprintf("wp plugin list --path=%s --format=json", c.ServerInfo.WpPath)
296
297
	var plugins []WpStatus
298
	var r execResult
299
	if r := exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
300
		if err = json.Unmarshal([]byte(r.Stdout), &plugins); err != nil {
301
			return
302
		}
303
	}
304
	if !r.isSuccess() {
305
		return vinfos, fmt.Errorf("%s", cmd)
306
	}
307
308
	for _, plugin := range plugins {
309
		url := fmt.Sprintf("https://wpvulndb.com/api/v3/plugins/%s", plugin.Name)
310
		token := fmt.Sprintf("Token token=%s", c.ServerInfo.WpToken)
311
		var req *http.Request
312
		req, err = http.NewRequest("GET", url, nil)
313
		if err != nil {
314
			return
315
		}
316
		req.Header.Set("Authorization", token)
317
		client := new(http.Client)
318
		var resp *http.Response
319
		resp, err = client.Do(req)
320
		if err != nil {
321
			return
322
		}
323
		if resp.StatusCode != 200 && resp.StatusCode != 404 {
324
			return vinfos, fmt.Errorf("status: %s", resp.Status)
325
		}
326
		body, _ := ioutil.ReadAll(resp.Body)
327
		defer resp.Body.Close()
328
		if resp.StatusCode == 404 {
329
			var jsonError WpCveInfos
330
			if err = json.Unmarshal([]byte(string(body)), &jsonError); err != nil {
331
				return
332
			}
333
			if jsonError.Error == "HTTP Token: Access denied.\n" {
334
				c.log.Errorf("wordpress: HTTP Token: Access denied.")
335
			} else if jsonError.Error == "Not found" {
336
				c.log.Errorf("wordpress: %s not found", plugin.Name)
337
			} else {
338
				return vinfos, fmt.Errorf("status: %s", resp.Status)
339
			}
340
		}
341
		contentConvertVinfos(string(body), plugin)
342
	}
343
	return
344
}
345
346
func contentConvertVinfos(stdout string, content WpStatus) (vinfos []models.VulnInfo, err error) {
347
	data := map[string]WpCveInfos{}
348
	if err = json.Unmarshal([]byte(stdout), &data); err != nil {
349
		var jsonError WpCveInfos
350
		if err = json.Unmarshal([]byte(stdout), &jsonError); err != nil {
351
			return
352
		}
353
	}
354
355
	for _, i := range data {
356
		if len(i.Vulnerabilities) == 0 {
357
			continue
358
		}
359
		for _, vulnerability := range i.Vulnerabilities {
360
			if len(vulnerability.References.Cve) == 0 {
361
				continue
362
			}
363
			if len(vulnerability.FixedIn) == 0 {
364
				var cveIDs []string
365
				for _, cveNumber := range vulnerability.References.Cve {
366
					cveIDs = append(cveIDs, "CVE-"+cveNumber)
367
				}
368
369
				for _, cveID := range cveIDs {
370
					vinfos = append(vinfos, models.VulnInfo{
371
						CveID: cveID,
372
						CveContents: models.NewCveContents(
373
							models.CveContent{
374
								CveID: cveID,
375
								Title: vulnerability.Title,
376
							},
377
						),
378
						AffectedPackages: models.PackageStatuses{
379
							{
380
								NotFixedYet: true,
381
							},
382
						},
383
					})
384
				}
385
			}
386
			var v1 *version.Version
387
			v1, err = version.NewVersion(content.Version)
388
			if err != nil {
389
				return
390
			}
391
			var v2 *version.Version
392
			v2, err = version.NewVersion(vulnerability.FixedIn)
393
			if err != nil {
394
				return
395
			}
396
			if v1.LessThan(v2) {
397
				var cveIDs []string
398
				for _, cveNumber := range vulnerability.References.Cve {
399
					cveIDs = append(cveIDs, "CVE-"+cveNumber)
400
				}
401
402
				for _, cveID := range cveIDs {
403
					vinfos = append(vinfos, models.VulnInfo{
404
						CveID: cveID,
405
						CveContents: models.NewCveContents(
406
							models.CveContent{
407
								CveID: cveID,
408
								Title: vulnerability.Title,
409
							},
410
						),
411
						AffectedPackages: models.PackageStatuses{
412
							{
413
								NotFixedYet: false,
414
							},
415
						},
416
					})
417
				}
418
			}
419
		}
420
	}
421
	return
422
}
423
424
func (l *base) wpConvertToModel() models.VulnInfos {
425
	return l.WpVulnInfos
426
}
427
428
func (l *base) exec(cmd string, sudo bool) execResult {
429
	return exec(l.ServerInfo, cmd, sudo, l.log)
430
}
431
432
func (l *base) setServerInfo(c config.ServerInfo) {
433
	l.ServerInfo = c
434
}
435
436
func (l *base) getServerInfo() config.ServerInfo {
437
	return l.ServerInfo
438
}
439
440
func (l *base) setDistro(fam, rel string) {
441
	d := config.Distro{
442
		Family:  fam,
443
		Release: rel,
444
	}
445
	l.Distro = d
446
447
	s := l.getServerInfo()
448
	s.Distro = d
449
	l.setServerInfo(s)
450
}
451
452
func (l *base) getDistro() config.Distro {
453
	return l.Distro
454
}
455
456
func (l *base) setPlatform(p models.Platform) {
457
	l.Platform = p
458
}
459
460
func (l *base) getPlatform() models.Platform {
461
	return l.Platform
462
}
463
464
func (l *base) runningKernel() (release, version string, err error) {
465
	r := l.exec("uname -r", noSudo)
466
	if !r.isSuccess() {
467
		return "", "", fmt.Errorf("Failed to SSH: %s", r)
468
	}
469
	release = strings.TrimSpace(r.Stdout)
470
471
	switch l.Distro.Family {
472
	case config.Debian:
473
		r := l.exec("uname -a", noSudo)
474
		if !r.isSuccess() {
475
			return "", "", fmt.Errorf("Failed to SSH: %s", r)
476
		}
477
		ss := strings.Fields(r.Stdout)
478
		if 6 < len(ss) {
479
			version = ss[6]
480
		}
481
	}
482
	return
483
}
484
485
func (l *base) allContainers() (containers []config.Container, err error) {
486
	switch l.ServerInfo.ContainerType {
487
	case "", "docker":
488
		stdout, err := l.dockerPs("-a --format '{{.ID}} {{.Names}} {{.Image}}'")
489
		if err != nil {
490
			return containers, err
491
		}
492
		return l.parseDockerPs(stdout)
493
	case "lxd":
494
		stdout, err := l.lxdPs("-c n")
495
		if err != nil {
496
			return containers, err
497
		}
498
		return l.parseLxdPs(stdout)
499
	case "lxc":
500
		stdout, err := l.lxcPs("-1")
501
		if err != nil {
502
			return containers, err
503
		}
504
		return l.parseLxcPs(stdout)
505
	default:
506
		return containers, fmt.Errorf(
507
			"Not supported yet: %s", l.ServerInfo.ContainerType)
508
	}
509
}
510
511
func (l *base) runningContainers() (containers []config.Container, err error) {
512
	switch l.ServerInfo.ContainerType {
513
	case "", "docker":
514
		stdout, err := l.dockerPs("--format '{{.ID}} {{.Names}} {{.Image}}'")
515
		if err != nil {
516
			return containers, err
517
		}
518
		return l.parseDockerPs(stdout)
519
	case "lxd":
520
		stdout, err := l.lxdPs("volatile.last_state.power=RUNNING -c n")
521
		if err != nil {
522
			return containers, err
523
		}
524
		return l.parseLxdPs(stdout)
525
	case "lxc":
526
		stdout, err := l.lxcPs("-1 --running")
527
		if err != nil {
528
			return containers, err
529
		}
530
		return l.parseLxcPs(stdout)
531
	default:
532
		return containers, fmt.Errorf(
533
			"Not supported yet: %s", l.ServerInfo.ContainerType)
534
	}
535
}
536
537
func (l *base) exitedContainers() (containers []config.Container, err error) {
538
	switch l.ServerInfo.ContainerType {
539
	case "", "docker":
540
		stdout, err := l.dockerPs("--filter 'status=exited' --format '{{.ID}} {{.Names}} {{.Image}}'")
541
		if err != nil {
542
			return containers, err
543
		}
544
		return l.parseDockerPs(stdout)
545
	case "lxd":
546
		stdout, err := l.lxdPs("volatile.last_state.power=STOPPED -c n")
547
		if err != nil {
548
			return containers, err
549
		}
550
		return l.parseLxdPs(stdout)
551
	case "lxc":
552
		stdout, err := l.lxcPs("-1 --stopped")
553
		if err != nil {
554
			return containers, err
555
		}
556
		return l.parseLxcPs(stdout)
557
	default:
558
		return containers, fmt.Errorf(
559
			"Not supported yet: %s", l.ServerInfo.ContainerType)
560
	}
561
}
562
563
func (l *base) dockerPs(option string) (string, error) {
564
	cmd := fmt.Sprintf("docker ps %s", option)
565
	r := l.exec(cmd, noSudo)
566
	if !r.isSuccess() {
567
		return "", fmt.Errorf("Failed to SSH: %s", r)
568
	}
569
	return r.Stdout, nil
570
}
571
572
func (l *base) lxdPs(option string) (string, error) {
573
	cmd := fmt.Sprintf("lxc list %s", option)
574
	r := l.exec(cmd, noSudo)
575
	if !r.isSuccess() {
576
		return "", fmt.Errorf("failed to SSH: %s", r)
577
	}
578
	return r.Stdout, nil
579
}
580
581
func (l *base) lxcPs(option string) (string, error) {
582
	cmd := fmt.Sprintf("lxc-ls %s 2>/dev/null", option)
583
	r := l.exec(cmd, sudo)
584
	if !r.isSuccess() {
585
		return "", fmt.Errorf("failed to SSH: %s", r)
586
	}
587
	return r.Stdout, nil
588
}
589
590
func (l *base) parseDockerPs(stdout string) (containers []config.Container, err error) {
591
	lines := strings.Split(stdout, "\n")
592
	for _, line := range lines {
593
		fields := strings.Fields(line)
594
		if len(fields) == 0 {
595
			break
596
		}
597
		if len(fields) != 3 {
598
			return containers, fmt.Errorf("Unknown format: %s", line)
599
		}
600
		containers = append(containers, config.Container{
601
			ContainerID: fields[0],
602
			Name:        fields[1],
603
			Image:       fields[2],
604
		})
605
	}
606
	return
607
}
608
609
func (l *base) parseLxdPs(stdout string) (containers []config.Container, err error) {
610
	lines := strings.Split(stdout, "\n")
611
	for i, line := range lines[3:] {
612
		if i%2 == 1 {
613
			continue
614
		}
615
		fields := strings.Fields(strings.Replace(line, "|", " ", -1))
616
		if len(fields) == 0 {
617
			break
618
		}
619
		if len(fields) != 1 {
620
			return containers, fmt.Errorf("Unknown format: %s", line)
621
		}
622
		containers = append(containers, config.Container{
623
			ContainerID: fields[0],
624
			Name:        fields[0],
625
		})
626
	}
627
	return
628
}
629
630
func (l *base) parseLxcPs(stdout string) (containers []config.Container, err error) {
631
	lines := strings.Split(stdout, "\n")
632
	for _, line := range lines {
633
		fields := strings.Fields(line)
634
		if len(fields) == 0 {
635
			break
636
		}
637
		containers = append(containers, config.Container{
638
			ContainerID: fields[0],
639
			Name:        fields[0],
640
		})
641
	}
642
	return
643
}
644
645
// ip executes ip command and returns IP addresses
646
func (l *base) ip() ([]string, []string, error) {
647
	// e.g.
648
	// 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000\    link/ether 52:54:00:2a:86:4c brd ff:ff:ff:ff:ff:ff
649
	// 2: eth0    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
650
	// 2: eth0    inet6 fe80::5054:ff:fe2a:864c/64 scope link \       valid_lft forever preferred_lft forever
651
	r := l.exec("/sbin/ip -o addr", noSudo)
652
	if !r.isSuccess() {
653
		return nil, nil, fmt.Errorf("Failed to detect IP address: %v", r)
654
	}
655
	ipv4Addrs, ipv6Addrs := l.parseIP(r.Stdout)
656
	return ipv4Addrs, ipv6Addrs, nil
657
}
658
659
// parseIP parses the results of ip command
660
func (l *base) parseIP(stdout string) (ipv4Addrs []string, ipv6Addrs []string) {
661
	lines := strings.Split(stdout, "\n")
662
	for _, line := range lines {
663
		fields := strings.Fields(line)
664
		if len(fields) < 4 {
665
			continue
666
		}
667
		ip, _, err := net.ParseCIDR(fields[3])
668
		if err != nil {
669
			continue
670
		}
671
		if !ip.IsGlobalUnicast() {
672
			continue
673
		}
674
		if ipv4 := ip.To4(); ipv4 != nil {
675
			ipv4Addrs = append(ipv4Addrs, ipv4.String())
676
		} else {
677
			ipv6Addrs = append(ipv6Addrs, ip.String())
678
		}
679
	}
680
	return
681
}
682
683
func (l *base) detectPlatform() {
684
	if l.getServerInfo().Mode.IsOffline() {
685
		l.setPlatform(models.Platform{Name: "unknown"})
686
		return
687
	}
688
	ok, instanceID, err := l.detectRunningOnAws()
689
	if err != nil {
690
		l.setPlatform(models.Platform{Name: "other"})
691
		return
692
	}
693
	if ok {
694
		l.setPlatform(models.Platform{
695
			Name:       "aws",
696
			InstanceID: instanceID,
697
		})
698
		return
699
	}
700
701
	//TODO Azure, GCP...
702
	l.setPlatform(models.Platform{Name: "other"})
703
	return
704
}
705
706
func (l *base) detectRunningOnAws() (ok bool, instanceID string, err error) {
707
	if r := l.exec("type curl", noSudo); r.isSuccess() {
708
		cmd := "curl --max-time 1 --noproxy 169.254.169.254 http://169.254.169.254/latest/meta-data/instance-id"
709
		r := l.exec(cmd, noSudo)
710
		if r.isSuccess() {
711
			id := strings.TrimSpace(r.Stdout)
712
			if !l.isAwsInstanceID(id) {
713
				return false, "", nil
714
			}
715
			return true, id, nil
716
		}
717
718
		switch r.ExitStatus {
719
		case 28, 7:
720
			// Not running on AWS
721
			//  7   Failed to connect to host.
722
			// 28  operation timeout.
723
			return false, "", nil
724
		}
725
	}
726
727
	if r := l.exec("type wget", noSudo); r.isSuccess() {
728
		cmd := "wget --tries=3 --timeout=1 --no-proxy -q -O - http://169.254.169.254/latest/meta-data/instance-id"
729
		r := l.exec(cmd, noSudo)
730
		if r.isSuccess() {
731
			id := strings.TrimSpace(r.Stdout)
732
			if !l.isAwsInstanceID(id) {
733
				return false, "", nil
734
			}
735
			return true, id, nil
736
		}
737
738
		switch r.ExitStatus {
739
		case 4, 8:
740
			// Not running on AWS
741
			// 4   Network failure
742
			// 8   Server issued an error response.
743
			return false, "", nil
744
		}
745
	}
746
	return false, "", fmt.Errorf(
747
		"Failed to curl or wget to AWS instance metadata on %s. container: %s",
748
		l.ServerInfo.ServerName, l.ServerInfo.Container.Name)
749
}
750
751
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html
752
var awsInstanceIDPattern = regexp.MustCompile(`^i-[0-9a-f]+$`)
753
754
func (l *base) isAwsInstanceID(str string) bool {
755
	return awsInstanceIDPattern.MatchString(str)
756
}
757
758
func (l *base) convertToModel() models.ScanResult {
759
	ctype := l.ServerInfo.ContainerType
760
	if l.ServerInfo.Container.ContainerID != "" && ctype == "" {
761
		ctype = "docker"
762
	}
763
	container := models.Container{
764
		ContainerID: l.ServerInfo.Container.ContainerID,
765
		Name:        l.ServerInfo.Container.Name,
766
		Image:       l.ServerInfo.Container.Image,
767
		Type:        ctype,
768
	}
769
770
	errs := []string{}
771
	for _, e := range l.errs {
772
		errs = append(errs, fmt.Sprintf("%s", e))
773
	}
774
775
	return models.ScanResult{
776
		JSONVersion:   models.JSONVersion,
777
		ServerName:    l.ServerInfo.ServerName,
778
		ScannedAt:     time.Now(),
779
		ScanMode:      l.ServerInfo.Mode.String(),
780
		Family:        l.Distro.Family,
781
		Release:       l.Distro.Release,
782
		Container:     container,
783
		Platform:      l.Platform,
784
		IPv4Addrs:     l.ServerInfo.IPv4Addrs,
785
		IPv6Addrs:     l.ServerInfo.IPv6Addrs,
786
		ScannedCves:   l.VulnInfos,
787
		RunningKernel: l.Kernel,
788
		Packages:      l.Packages,
789
		SrcPackages:   l.SrcPackages,
790
		Optional:      l.ServerInfo.Optional,
791
		Errors:        errs,
792
	}
793
}
794
795
func (l *base) setErrs(errs []error) {
796
	l.errs = errs
797
}
798
799
func (l *base) getErrs() []error {
800
	return l.errs
801
}
802
803
const (
804
	systemd  = "systemd"
805
	upstart  = "upstart"
806
	sysVinit = "init"
807
)
808
809
// https://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem
810
func (l *base) detectInitSystem() (string, error) {
811
	var f func(string) (string, error)
812
	f = func(cmd string) (string, error) {
813
		r := l.exec(cmd, sudo)
814
		if !r.isSuccess() {
815
			return "", fmt.Errorf("Failed to stat %s: %s", cmd, r)
816
		}
817
		scanner := bufio.NewScanner(strings.NewReader(r.Stdout))
818
		scanner.Scan()
819
		line := strings.TrimSpace(scanner.Text())
820
		if strings.Contains(line, "systemd") {
821
			return systemd, nil
822
		} else if strings.Contains(line, "upstart") {
823
			return upstart, nil
824
		} else if strings.Contains(line, "File: ‘/proc/1/exe’ -> ‘/sbin/init’") ||
825
			strings.Contains(line, "File: `/proc/1/exe' -> `/sbin/init'") {
826
			return f("stat /sbin/init")
827
		} else if line == "File: ‘/sbin/init’" ||
828
			line == "File: `/sbin/init'" {
829
			r := l.exec("/sbin/init --version", noSudo)
830
			if r.isSuccess() {
831
				if strings.Contains(r.Stdout, "upstart") {
832
					return upstart, nil
833
				}
834
			}
835
			return sysVinit, nil
836
		}
837
		return "", fmt.Errorf("Failed to detect a init system: %s", line)
838
	}
839
	return f("stat /proc/1/exe")
840
}
841
842
func (l *base) detectServiceName(pid string) (string, error) {
843
	cmd := fmt.Sprintf("systemctl status --quiet --no-pager %s", pid)
844
	r := l.exec(cmd, noSudo)
845
	if !r.isSuccess() {
846
		return "", fmt.Errorf("Failed to stat %s: %s", cmd, r)
847
	}
848
	return l.parseSystemctlStatus(r.Stdout), nil
849
}
850
851
func (l *base) parseSystemctlStatus(stdout string) string {
852
	scanner := bufio.NewScanner(strings.NewReader(stdout))
853
	scanner.Scan()
854
	line := scanner.Text()
855
	ss := strings.Fields(line)
856
	if len(ss) < 2 || strings.HasPrefix(line, "Failed to get unit for PID") {
857
		return ""
858
	}
859
	return ss[1]
860
}
861