Completed
Pull Request — master (#769)
by
unknown
19:42 queued 07:52
created

scan.detectWpPlugin   B

Complexity

Conditions 8

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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