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

scan.*base.scanWp   C

Complexity

Conditions 9

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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