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

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