Completed
Pull Request — master (#769)
by
unknown
11:10
created

scan.contentConvertVinfos   F

Complexity

Conditions 19

Size

Total Lines 72
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

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