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