Passed
Pull Request — master (#769)
by
unknown
20:23 queued 08:32
created

scan.*base.getErrs   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
nop 0
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
		var tmpVinfos []models.VulnInfo
255
		if tmpVinfos, err = contentHTTPRequest(c, theme, url); err != nil {
256
			return
257
		}
258
		vinfos = append(vinfos, tmpVinfos...)
259
	}
260
	return
261
}
262
263
func detectWpPlugin(c *base) (vinfos []models.VulnInfo, err error) {
264
	cmd := fmt.Sprintf("wp plugin list --path=%s --format=json", c.ServerInfo.WpPath)
265
266
	var plugins []WpStatus
267
	var r execResult
268
	if r := exec(c.ServerInfo, cmd, noSudo); r.isSuccess() {
269
		if err = json.Unmarshal([]byte(r.Stdout), &plugins); err != nil {
270
			return
271
		}
272
	}
273
	if !r.isSuccess() {
274
		return vinfos, fmt.Errorf("%s", cmd)
275
	}
276
277
	for _, plugin := range plugins {
278
		url := fmt.Sprintf("https://wpvulndb.com/api/v3/plugins/%s", plugin.Name)
279
		var tmpVinfos []models.VulnInfo
280
		if tmpVinfos, err = contentHTTPRequest(c, plugin, url); err != nil {
281
			return
282
		}
283
		vinfos = append(vinfos, tmpVinfos...)
284
	}
285
	return
286
}
287
288
func contentHTTPRequest(c *base, content WpStatus, url string) (vinfos []models.VulnInfo, err error) {
289
	token := fmt.Sprintf("Token token=%s", c.ServerInfo.WpToken)
290
	var req *http.Request
291
	req, err = http.NewRequest("GET", url, nil)
292
	if err != nil {
293
		return
294
	}
295
	req.Header.Set("Authorization", token)
296
	client := new(http.Client)
297
	var resp *http.Response
298
	resp, err = client.Do(req)
299
	if err != nil {
300
		return
301
	}
302
	body, _ := ioutil.ReadAll(resp.Body)
303
	defer resp.Body.Close()
304
	if resp.StatusCode != 200 && resp.StatusCode != 404 {
305
		return vinfos, fmt.Errorf("status: %s", resp.Status)
306
	} else if resp.StatusCode == 404 {
307
		var jsonError WpCveInfos
308
		if err = json.Unmarshal(body, &jsonError); err != nil {
309
			return
310
		}
311
		if jsonError.Error == "HTTP Token: Access denied.\n" {
312
			return vinfos, fmt.Errorf("wordpress: HTTP Token: Access denied")
313
		} else if jsonError.Error == "Not found" {
314
			c.log.Infof("wordpress: %s not found", content.Name)
315
		} else {
316
			return vinfos, fmt.Errorf("status: %s", resp.Status)
317
		}
318
	}
319
	if vinfos, err = contentConvertVinfos(string(body), content); err != nil {
320
		return
321
	}
322
	return
323
}
324
325
func contentConvertVinfos(stdout string, content WpStatus) (vinfos []models.VulnInfo, err error) {
326
	data := map[string]WpCveInfos{}
327
	if err = json.Unmarshal([]byte(stdout), &data); err != nil {
328
		var jsonError WpCveInfos
329
		if err = json.Unmarshal([]byte(stdout), &jsonError); err != nil {
330
			return
331
		}
332
	}
333
334
	for _, e := range data {
335
		if len(e.Vulnerabilities) == 0 {
336
			continue
337
		}
338
		for _, vulnerability := range e.Vulnerabilities {
339
			if len(vulnerability.References.Cve) == 0 {
340
				continue
341
			}
342
343
			var cveIDs []string
344
			for _, cveNumber := range vulnerability.References.Cve {
345
				cveIDs = append(cveIDs, "CVE-"+cveNumber)
346
			}
347
348
			if len(vulnerability.FixedIn) == 0 {
349
				for _, cveID := range cveIDs {
350
					vinfos = append(vinfos, models.VulnInfo{
351
						CveID: cveID,
352
						CveContents: models.NewCveContents(
353
							models.CveContent{
354
								CveID: cveID,
355
								Title: vulnerability.Title,
356
							},
357
						),
358
						AffectedPackages: models.PackageStatuses{
359
							{
360
								NotFixedYet: true,
361
							},
362
						},
363
					})
364
				}
365
			}
366
			var v1 *version.Version
367
			v1, err = version.NewVersion(content.Version)
368
			if err != nil {
369
				return
370
			}
371
			var v2 *version.Version
372
			v2, err = version.NewVersion(vulnerability.FixedIn)
373
			if err != nil {
374
				return
375
			}
376
			if v1.LessThan(v2) {
377
				for _, cveID := range cveIDs {
378
					vinfos = append(vinfos, models.VulnInfo{
379
						CveID: cveID,
380
						CveContents: models.NewCveContents(
381
							models.CveContent{
382
								CveID: cveID,
383
								Title: vulnerability.Title,
384
							},
385
						),
386
						AffectedPackages: models.PackageStatuses{
387
							{
388
								NotFixedYet: false,
389
							},
390
						},
391
					})
392
				}
393
			}
394
		}
395
	}
396
	return
397
}
398
399
func (l *base) wpConvertToModel() models.VulnInfos {
400
	return l.WpVulnInfos
401
}
402
403
func (l *base) exec(cmd string, sudo bool) execResult {
404
	return exec(l.ServerInfo, cmd, sudo, l.log)
405
}
406
407
func (l *base) setServerInfo(c config.ServerInfo) {
408
	l.ServerInfo = c
409
}
410
411
func (l *base) getServerInfo() config.ServerInfo {
412
	return l.ServerInfo
413
}
414
415
func (l *base) setDistro(fam, rel string) {
416
	d := config.Distro{
417
		Family:  fam,
418
		Release: rel,
419
	}
420
	l.Distro = d
421
422
	s := l.getServerInfo()
423
	s.Distro = d
424
	l.setServerInfo(s)
425
}
426
427
func (l *base) getDistro() config.Distro {
428
	return l.Distro
429
}
430
431
func (l *base) setPlatform(p models.Platform) {
432
	l.Platform = p
433
}
434
435
func (l *base) getPlatform() models.Platform {
436
	return l.Platform
437
}
438
439
func (l *base) runningKernel() (release, version string, err error) {
440
	r := l.exec("uname -r", noSudo)
441
	if !r.isSuccess() {
442
		return "", "", fmt.Errorf("Failed to SSH: %s", r)
443
	}
444
	release = strings.TrimSpace(r.Stdout)
445
446
	switch l.Distro.Family {
447
	case config.Debian:
448
		r := l.exec("uname -a", noSudo)
449
		if !r.isSuccess() {
450
			return "", "", fmt.Errorf("Failed to SSH: %s", r)
451
		}
452
		ss := strings.Fields(r.Stdout)
453
		if 6 < len(ss) {
454
			version = ss[6]
455
		}
456
	}
457
	return
458
}
459
460
func (l *base) allContainers() (containers []config.Container, err error) {
461
	switch l.ServerInfo.ContainerType {
462
	case "", "docker":
463
		stdout, err := l.dockerPs("-a --format '{{.ID}} {{.Names}} {{.Image}}'")
464
		if err != nil {
465
			return containers, err
466
		}
467
		return l.parseDockerPs(stdout)
468
	case "lxd":
469
		stdout, err := l.lxdPs("-c n")
470
		if err != nil {
471
			return containers, err
472
		}
473
		return l.parseLxdPs(stdout)
474
	case "lxc":
475
		stdout, err := l.lxcPs("-1")
476
		if err != nil {
477
			return containers, err
478
		}
479
		return l.parseLxcPs(stdout)
480
	default:
481
		return containers, fmt.Errorf(
482
			"Not supported yet: %s", l.ServerInfo.ContainerType)
483
	}
484
}
485
486
func (l *base) runningContainers() (containers []config.Container, err error) {
487
	switch l.ServerInfo.ContainerType {
488
	case "", "docker":
489
		stdout, err := l.dockerPs("--format '{{.ID}} {{.Names}} {{.Image}}'")
490
		if err != nil {
491
			return containers, err
492
		}
493
		return l.parseDockerPs(stdout)
494
	case "lxd":
495
		stdout, err := l.lxdPs("volatile.last_state.power=RUNNING -c n")
496
		if err != nil {
497
			return containers, err
498
		}
499
		return l.parseLxdPs(stdout)
500
	case "lxc":
501
		stdout, err := l.lxcPs("-1 --running")
502
		if err != nil {
503
			return containers, err
504
		}
505
		return l.parseLxcPs(stdout)
506
	default:
507
		return containers, fmt.Errorf(
508
			"Not supported yet: %s", l.ServerInfo.ContainerType)
509
	}
510
}
511
512
func (l *base) exitedContainers() (containers []config.Container, err error) {
513
	switch l.ServerInfo.ContainerType {
514
	case "", "docker":
515
		stdout, err := l.dockerPs("--filter 'status=exited' --format '{{.ID}} {{.Names}} {{.Image}}'")
516
		if err != nil {
517
			return containers, err
518
		}
519
		return l.parseDockerPs(stdout)
520
	case "lxd":
521
		stdout, err := l.lxdPs("volatile.last_state.power=STOPPED -c n")
522
		if err != nil {
523
			return containers, err
524
		}
525
		return l.parseLxdPs(stdout)
526
	case "lxc":
527
		stdout, err := l.lxcPs("-1 --stopped")
528
		if err != nil {
529
			return containers, err
530
		}
531
		return l.parseLxcPs(stdout)
532
	default:
533
		return containers, fmt.Errorf(
534
			"Not supported yet: %s", l.ServerInfo.ContainerType)
535
	}
536
}
537
538
func (l *base) dockerPs(option string) (string, error) {
539
	cmd := fmt.Sprintf("docker ps %s", option)
540
	r := l.exec(cmd, noSudo)
541
	if !r.isSuccess() {
542
		return "", fmt.Errorf("Failed to SSH: %s", r)
543
	}
544
	return r.Stdout, nil
545
}
546
547
func (l *base) lxdPs(option string) (string, error) {
548
	cmd := fmt.Sprintf("lxc list %s", option)
549
	r := l.exec(cmd, noSudo)
550
	if !r.isSuccess() {
551
		return "", fmt.Errorf("failed to SSH: %s", r)
552
	}
553
	return r.Stdout, nil
554
}
555
556
func (l *base) lxcPs(option string) (string, error) {
557
	cmd := fmt.Sprintf("lxc-ls %s 2>/dev/null", option)
558
	r := l.exec(cmd, sudo)
559
	if !r.isSuccess() {
560
		return "", fmt.Errorf("failed to SSH: %s", r)
561
	}
562
	return r.Stdout, nil
563
}
564
565
func (l *base) parseDockerPs(stdout string) (containers []config.Container, err error) {
566
	lines := strings.Split(stdout, "\n")
567
	for _, line := range lines {
568
		fields := strings.Fields(line)
569
		if len(fields) == 0 {
570
			break
571
		}
572
		if len(fields) != 3 {
573
			return containers, fmt.Errorf("Unknown format: %s", line)
574
		}
575
		containers = append(containers, config.Container{
576
			ContainerID: fields[0],
577
			Name:        fields[1],
578
			Image:       fields[2],
579
		})
580
	}
581
	return
582
}
583
584
func (l *base) parseLxdPs(stdout string) (containers []config.Container, err error) {
585
	lines := strings.Split(stdout, "\n")
586
	for i, line := range lines[3:] {
587
		if i%2 == 1 {
588
			continue
589
		}
590
		fields := strings.Fields(strings.Replace(line, "|", " ", -1))
591
		if len(fields) == 0 {
592
			break
593
		}
594
		if len(fields) != 1 {
595
			return containers, fmt.Errorf("Unknown format: %s", line)
596
		}
597
		containers = append(containers, config.Container{
598
			ContainerID: fields[0],
599
			Name:        fields[0],
600
		})
601
	}
602
	return
603
}
604
605
func (l *base) parseLxcPs(stdout string) (containers []config.Container, err error) {
606
	lines := strings.Split(stdout, "\n")
607
	for _, line := range lines {
608
		fields := strings.Fields(line)
609
		if len(fields) == 0 {
610
			break
611
		}
612
		containers = append(containers, config.Container{
613
			ContainerID: fields[0],
614
			Name:        fields[0],
615
		})
616
	}
617
	return
618
}
619
620
// ip executes ip command and returns IP addresses
621
func (l *base) ip() ([]string, []string, error) {
622
	// e.g.
623
	// 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
624
	// 2: eth0    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
625
	// 2: eth0    inet6 fe80::5054:ff:fe2a:864c/64 scope link \       valid_lft forever preferred_lft forever
626
	r := l.exec("/sbin/ip -o addr", noSudo)
627
	if !r.isSuccess() {
628
		return nil, nil, fmt.Errorf("Failed to detect IP address: %v", r)
629
	}
630
	ipv4Addrs, ipv6Addrs := l.parseIP(r.Stdout)
631
	return ipv4Addrs, ipv6Addrs, nil
632
}
633
634
// parseIP parses the results of ip command
635
func (l *base) parseIP(stdout string) (ipv4Addrs []string, ipv6Addrs []string) {
636
	lines := strings.Split(stdout, "\n")
637
	for _, line := range lines {
638
		fields := strings.Fields(line)
639
		if len(fields) < 4 {
640
			continue
641
		}
642
		ip, _, err := net.ParseCIDR(fields[3])
643
		if err != nil {
644
			continue
645
		}
646
		if !ip.IsGlobalUnicast() {
647
			continue
648
		}
649
		if ipv4 := ip.To4(); ipv4 != nil {
650
			ipv4Addrs = append(ipv4Addrs, ipv4.String())
651
		} else {
652
			ipv6Addrs = append(ipv6Addrs, ip.String())
653
		}
654
	}
655
	return
656
}
657
658
func (l *base) detectPlatform() {
659
	if l.getServerInfo().Mode.IsOffline() {
660
		l.setPlatform(models.Platform{Name: "unknown"})
661
		return
662
	}
663
	ok, instanceID, err := l.detectRunningOnAws()
664
	if err != nil {
665
		l.setPlatform(models.Platform{Name: "other"})
666
		return
667
	}
668
	if ok {
669
		l.setPlatform(models.Platform{
670
			Name:       "aws",
671
			InstanceID: instanceID,
672
		})
673
		return
674
	}
675
676
	//TODO Azure, GCP...
677
	l.setPlatform(models.Platform{Name: "other"})
678
	return
679
}
680
681
func (l *base) detectRunningOnAws() (ok bool, instanceID string, err error) {
682
	if r := l.exec("type curl", noSudo); r.isSuccess() {
683
		cmd := "curl --max-time 1 --noproxy 169.254.169.254 http://169.254.169.254/latest/meta-data/instance-id"
684
		r := l.exec(cmd, noSudo)
685
		if r.isSuccess() {
686
			id := strings.TrimSpace(r.Stdout)
687
			if !l.isAwsInstanceID(id) {
688
				return false, "", nil
689
			}
690
			return true, id, nil
691
		}
692
693
		switch r.ExitStatus {
694
		case 28, 7:
695
			// Not running on AWS
696
			//  7   Failed to connect to host.
697
			// 28  operation timeout.
698
			return false, "", nil
699
		}
700
	}
701
702
	if r := l.exec("type wget", noSudo); r.isSuccess() {
703
		cmd := "wget --tries=3 --timeout=1 --no-proxy -q -O - http://169.254.169.254/latest/meta-data/instance-id"
704
		r := l.exec(cmd, noSudo)
705
		if r.isSuccess() {
706
			id := strings.TrimSpace(r.Stdout)
707
			if !l.isAwsInstanceID(id) {
708
				return false, "", nil
709
			}
710
			return true, id, nil
711
		}
712
713
		switch r.ExitStatus {
714
		case 4, 8:
715
			// Not running on AWS
716
			// 4   Network failure
717
			// 8   Server issued an error response.
718
			return false, "", nil
719
		}
720
	}
721
	return false, "", fmt.Errorf(
722
		"Failed to curl or wget to AWS instance metadata on %s. container: %s",
723
		l.ServerInfo.ServerName, l.ServerInfo.Container.Name)
724
}
725
726
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html
727
var awsInstanceIDPattern = regexp.MustCompile(`^i-[0-9a-f]+$`)
728
729
func (l *base) isAwsInstanceID(str string) bool {
730
	return awsInstanceIDPattern.MatchString(str)
731
}
732
733
func (l *base) convertToModel() models.ScanResult {
734
	ctype := l.ServerInfo.ContainerType
735
	if l.ServerInfo.Container.ContainerID != "" && ctype == "" {
736
		ctype = "docker"
737
	}
738
	container := models.Container{
739
		ContainerID: l.ServerInfo.Container.ContainerID,
740
		Name:        l.ServerInfo.Container.Name,
741
		Image:       l.ServerInfo.Container.Image,
742
		Type:        ctype,
743
	}
744
745
	errs := []string{}
746
	for _, e := range l.errs {
747
		errs = append(errs, fmt.Sprintf("%s", e))
748
	}
749
750
	return models.ScanResult{
751
		JSONVersion:   models.JSONVersion,
752
		ServerName:    l.ServerInfo.ServerName,
753
		ScannedAt:     time.Now(),
754
		ScanMode:      l.ServerInfo.Mode.String(),
755
		Family:        l.Distro.Family,
756
		Release:       l.Distro.Release,
757
		Container:     container,
758
		Platform:      l.Platform,
759
		IPv4Addrs:     l.ServerInfo.IPv4Addrs,
760
		IPv6Addrs:     l.ServerInfo.IPv6Addrs,
761
		ScannedCves:   l.VulnInfos,
762
		RunningKernel: l.Kernel,
763
		Packages:      l.Packages,
764
		SrcPackages:   l.SrcPackages,
765
		Optional:      l.ServerInfo.Optional,
766
		Errors:        errs,
767
	}
768
}
769
770
func (l *base) setErrs(errs []error) {
771
	l.errs = errs
772
}
773
774
func (l *base) getErrs() []error {
775
	return l.errs
776
}
777
778
const (
779
	systemd  = "systemd"
780
	upstart  = "upstart"
781
	sysVinit = "init"
782
)
783
784
// https://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem
785
func (l *base) detectInitSystem() (string, error) {
786
	var f func(string) (string, error)
787
	f = func(cmd string) (string, error) {
788
		r := l.exec(cmd, sudo)
789
		if !r.isSuccess() {
790
			return "", fmt.Errorf("Failed to stat %s: %s", cmd, r)
791
		}
792
		scanner := bufio.NewScanner(strings.NewReader(r.Stdout))
793
		scanner.Scan()
794
		line := strings.TrimSpace(scanner.Text())
795
		if strings.Contains(line, "systemd") {
796
			return systemd, nil
797
		} else if strings.Contains(line, "upstart") {
798
			return upstart, nil
799
		} else if strings.Contains(line, "File: ‘/proc/1/exe’ -> ‘/sbin/init’") ||
800
			strings.Contains(line, "File: `/proc/1/exe' -> `/sbin/init'") {
801
			return f("stat /sbin/init")
802
		} else if line == "File: ‘/sbin/init’" ||
803
			line == "File: `/sbin/init'" {
804
			r := l.exec("/sbin/init --version", noSudo)
805
			if r.isSuccess() {
806
				if strings.Contains(r.Stdout, "upstart") {
807
					return upstart, nil
808
				}
809
			}
810
			return sysVinit, nil
811
		}
812
		return "", fmt.Errorf("Failed to detect a init system: %s", line)
813
	}
814
	return f("stat /proc/1/exe")
815
}
816
817
func (l *base) detectServiceName(pid string) (string, error) {
818
	cmd := fmt.Sprintf("systemctl status --quiet --no-pager %s", pid)
819
	r := l.exec(cmd, noSudo)
820
	if !r.isSuccess() {
821
		return "", fmt.Errorf("Failed to stat %s: %s", cmd, r)
822
	}
823
	return l.parseSystemctlStatus(r.Stdout), nil
824
}
825
826
func (l *base) parseSystemctlStatus(stdout string) string {
827
	scanner := bufio.NewScanner(strings.NewReader(stdout))
828
	scanner.Scan()
829
	line := scanner.Text()
830
	ss := strings.Fields(line)
831
	if len(ss) < 2 || strings.HasPrefix(line, "Failed to get unit for PID") {
832
		return ""
833
	}
834
	return ss[1]
835
}
836