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

scan.detectWp   A

Complexity

Conditions 4

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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