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

scan.detectWpPlugin   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 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/k0kubun/pp"
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
50
	var unsecures []models.VulnInfo
51
	if unsecures, err = detectWp(l.ServerInfo); err != nil {
52
		l.log.Errorf("Failed to scan wordpress: %s", err)
53
		return err
54
	}
55
	for _, i := range unsecures {
56
		l.VulnInfos[i.CveID] = i
57
	}
58
59
	return err
60
}
61
62
//CveInfos hoge
63
type CveInfos struct {
64
	ReleaseDate     string    `json:"release_date"`
65
	ChangelogURL    string    `json:"changelog_url"`
66
	Status          string    `json:"status"`
67
	Vulnerabilities []CveInfo `json:"vulnerabilities"`
68
}
69
70
//CveInfo hoge
71
type CveInfo struct {
72
	ID            int        `json:"id"`
73
	Title         string     `json:"title"`
74
	CreatedAt     string     `json:"created_at"`
75
	UpdatedAt     string     `json:"updated_at"`
76
	PublishedDate string     `json:"Published_date"`
77
	VulnType      string     `json:"Vuln_type"`
78
	References    References `json:"references"`
79
	FixedIn       string     `json:"fixed_in"`
80
}
81
82
//References hoge
83
type References struct {
84
	URL []string `json:"url"`
85
	Cve []string `json:"cve"`
86
}
87
88
func detectWp(c config.ServerInfo) (rs []models.VulnInfo, err error) {
89
90
	var coreVuln []models.VulnInfo
91
	if coreVuln, err = detectWpCore(c); err != nil {
92
		return
93
	}
94
	for _, i := range coreVuln {
95
		rs = append(rs, i)
96
	}
97
98
	var themeVuln []models.VulnInfo
99
	if themeVuln, err = detectWpTheme(c); err != nil {
100
		return
101
	}
102
	for _, i := range themeVuln {
103
		rs = append(rs, i)
104
	}
105
106
	var pluginVuln []models.VulnInfo
107
	if pluginVuln, err = detectWpPlugin(c); err != nil {
108
		return
109
	}
110
	for _, i := range pluginVuln {
111
		rs = append(rs, i)
112
	}
113
	return
114
}
115
116
func detectWpCore(c config.ServerInfo) (rs []models.VulnInfo, err error){
117
	cmd := fmt.Sprintf("wp core version --path=%s", c.WpPath)
118
119
	var coreVersion string
120
	if r := exec(c, cmd, noSudo); r.isSuccess() {
121
		tmp := strings.Split(r.Stdout, ".")
122
		coreVersion = strings.Join(tmp, "")
123
		coreVersion = strings.TrimRight(coreVersion, "\r\n")
124
		if len(coreVersion) == 0 {
125
			return
126
		}
127
		pp.Print(coreVersion)
128
	}
129
	cmd = fmt.Sprintf("curl -H 'Authorization: Token token=%s' https://wpvulndb.com/api/v3/wordpresses/%s", c.WpToken, coreVersion)
130
	if r := exec(c, cmd, noSudo); r.isSuccess() {
131
		data := map[string]CveInfos{}
132
		if err = json.Unmarshal([]byte(r.Stdout), &data); err != nil {
133
			return
134
		}
135
		for _, i := range data {
136
			for _, e := range i.Vulnerabilities {
137
				for _, k := range e.References.Cve {
138
					k = "CVE-" + k
139
					pp.Print(k)
140
				}
141
142
				rs = append(rs, models.VulnInfo{
143
					CveID: e.References.Cve[0],
144
				})
145
			}
146
		}
147
		pp.Print(data)
148
	}
149
	return
150
}
151
152
func detectWpTheme(c config.ServerInfo) (rs []models.VulnInfo, err error) {
153
	return
154
}
155
156
func detectWpPlugin(c config.ServerInfo) (rs []models.VulnInfo, err error) {
157
	return
158
}
159
160
func (l *base) exec(cmd string, sudo bool) execResult {
161
	return exec(l.ServerInfo, cmd, sudo, l.log)
162
}
163
164
func (l *base) setServerInfo(c config.ServerInfo) {
165
	l.ServerInfo = c
166
}
167
168
func (l *base) getServerInfo() config.ServerInfo {
169
	return l.ServerInfo
170
}
171
172
func (l *base) setDistro(fam, rel string) {
173
	d := config.Distro{
174
		Family:  fam,
175
		Release: rel,
176
	}
177
	l.Distro = d
178
179
	s := l.getServerInfo()
180
	s.Distro = d
181
	l.setServerInfo(s)
182
}
183
184
func (l *base) getDistro() config.Distro {
185
	return l.Distro
186
}
187
188
func (l *base) setPlatform(p models.Platform) {
189
	l.Platform = p
190
}
191
192
func (l *base) getPlatform() models.Platform {
193
	return l.Platform
194
}
195
196
func (l *base) runningKernel() (release, version string, err error) {
197
	r := l.exec("uname -r", noSudo)
198
	if !r.isSuccess() {
199
		return "", "", fmt.Errorf("Failed to SSH: %s", r)
200
	}
201
	release = strings.TrimSpace(r.Stdout)
202
203
	switch l.Distro.Family {
204
	case config.Debian:
205
		r := l.exec("uname -a", noSudo)
206
		if !r.isSuccess() {
207
			return "", "", fmt.Errorf("Failed to SSH: %s", r)
208
		}
209
		ss := strings.Fields(r.Stdout)
210
		if 6 < len(ss) {
211
			version = ss[6]
212
		}
213
	}
214
	return
215
}
216
217
func (l *base) allContainers() (containers []config.Container, err error) {
218
	switch l.ServerInfo.ContainerType {
219
	case "", "docker":
220
		stdout, err := l.dockerPs("-a --format '{{.ID}} {{.Names}} {{.Image}}'")
221
		if err != nil {
222
			return containers, err
223
		}
224
		return l.parseDockerPs(stdout)
225
	case "lxd":
226
		stdout, err := l.lxdPs("-c n")
227
		if err != nil {
228
			return containers, err
229
		}
230
		return l.parseLxdPs(stdout)
231
	case "lxc":
232
		stdout, err := l.lxcPs("-1")
233
		if err != nil {
234
			return containers, err
235
		}
236
		return l.parseLxcPs(stdout)
237
	default:
238
		return containers, fmt.Errorf(
239
			"Not supported yet: %s", l.ServerInfo.ContainerType)
240
	}
241
}
242
243
func (l *base) runningContainers() (containers []config.Container, err error) {
244
	switch l.ServerInfo.ContainerType {
245
	case "", "docker":
246
		stdout, err := l.dockerPs("--format '{{.ID}} {{.Names}} {{.Image}}'")
247
		if err != nil {
248
			return containers, err
249
		}
250
		return l.parseDockerPs(stdout)
251
	case "lxd":
252
		stdout, err := l.lxdPs("volatile.last_state.power=RUNNING -c n")
253
		if err != nil {
254
			return containers, err
255
		}
256
		return l.parseLxdPs(stdout)
257
	case "lxc":
258
		stdout, err := l.lxcPs("-1 --running")
259
		if err != nil {
260
			return containers, err
261
		}
262
		return l.parseLxcPs(stdout)
263
	default:
264
		return containers, fmt.Errorf(
265
			"Not supported yet: %s", l.ServerInfo.ContainerType)
266
	}
267
}
268
269
func (l *base) exitedContainers() (containers []config.Container, err error) {
270
	switch l.ServerInfo.ContainerType {
271
	case "", "docker":
272
		stdout, err := l.dockerPs("--filter 'status=exited' --format '{{.ID}} {{.Names}} {{.Image}}'")
273
		if err != nil {
274
			return containers, err
275
		}
276
		return l.parseDockerPs(stdout)
277
	case "lxd":
278
		stdout, err := l.lxdPs("volatile.last_state.power=STOPPED -c n")
279
		if err != nil {
280
			return containers, err
281
		}
282
		return l.parseLxdPs(stdout)
283
	case "lxc":
284
		stdout, err := l.lxcPs("-1 --stopped")
285
		if err != nil {
286
			return containers, err
287
		}
288
		return l.parseLxcPs(stdout)
289
	default:
290
		return containers, fmt.Errorf(
291
			"Not supported yet: %s", l.ServerInfo.ContainerType)
292
	}
293
}
294
295
func (l *base) dockerPs(option string) (string, error) {
296
	cmd := fmt.Sprintf("docker ps %s", option)
297
	r := l.exec(cmd, noSudo)
298
	if !r.isSuccess() {
299
		return "", fmt.Errorf("Failed to SSH: %s", r)
300
	}
301
	return r.Stdout, nil
302
}
303
304
func (l *base) lxdPs(option string) (string, error) {
305
	cmd := fmt.Sprintf("lxc list %s", option)
306
	r := l.exec(cmd, noSudo)
307
	if !r.isSuccess() {
308
		return "", fmt.Errorf("failed to SSH: %s", r)
309
	}
310
	return r.Stdout, nil
311
}
312
313
func (l *base) lxcPs(option string) (string, error) {
314
	cmd := fmt.Sprintf("lxc-ls %s 2>/dev/null", option)
315
	r := l.exec(cmd, sudo)
316
	if !r.isSuccess() {
317
		return "", fmt.Errorf("failed to SSH: %s", r)
318
	}
319
	return r.Stdout, nil
320
}
321
322
func (l *base) parseDockerPs(stdout string) (containers []config.Container, err error) {
323
	lines := strings.Split(stdout, "\n")
324
	for _, line := range lines {
325
		fields := strings.Fields(line)
326
		if len(fields) == 0 {
327
			break
328
		}
329
		if len(fields) != 3 {
330
			return containers, fmt.Errorf("Unknown format: %s", line)
331
		}
332
		containers = append(containers, config.Container{
333
			ContainerID: fields[0],
334
			Name:        fields[1],
335
			Image:       fields[2],
336
		})
337
	}
338
	return
339
}
340
341
func (l *base) parseLxdPs(stdout string) (containers []config.Container, err error) {
342
	lines := strings.Split(stdout, "\n")
343
	for i, line := range lines[3:] {
344
		if i%2 == 1 {
345
			continue
346
		}
347
		fields := strings.Fields(strings.Replace(line, "|", " ", -1))
348
		if len(fields) == 0 {
349
			break
350
		}
351
		if len(fields) != 1 {
352
			return containers, fmt.Errorf("Unknown format: %s", line)
353
		}
354
		containers = append(containers, config.Container{
355
			ContainerID: fields[0],
356
			Name:        fields[0],
357
		})
358
	}
359
	return
360
}
361
362
func (l *base) parseLxcPs(stdout string) (containers []config.Container, err error) {
363
	lines := strings.Split(stdout, "\n")
364
	for _, line := range lines {
365
		fields := strings.Fields(line)
366
		if len(fields) == 0 {
367
			break
368
		}
369
		containers = append(containers, config.Container{
370
			ContainerID: fields[0],
371
			Name:        fields[0],
372
		})
373
	}
374
	return
375
}
376
377
// ip executes ip command and returns IP addresses
378
func (l *base) ip() ([]string, []string, error) {
379
	// e.g.
380
	// 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
381
	// 2: eth0    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
382
	// 2: eth0    inet6 fe80::5054:ff:fe2a:864c/64 scope link \       valid_lft forever preferred_lft forever
383
	r := l.exec("/sbin/ip -o addr", noSudo)
384
	if !r.isSuccess() {
385
		return nil, nil, fmt.Errorf("Failed to detect IP address: %v", r)
386
	}
387
	ipv4Addrs, ipv6Addrs := l.parseIP(r.Stdout)
388
	return ipv4Addrs, ipv6Addrs, nil
389
}
390
391
// parseIP parses the results of ip command
392
func (l *base) parseIP(stdout string) (ipv4Addrs []string, ipv6Addrs []string) {
393
	lines := strings.Split(stdout, "\n")
394
	for _, line := range lines {
395
		fields := strings.Fields(line)
396
		if len(fields) < 4 {
397
			continue
398
		}
399
		ip, _, err := net.ParseCIDR(fields[3])
400
		if err != nil {
401
			continue
402
		}
403
		if !ip.IsGlobalUnicast() {
404
			continue
405
		}
406
		if ipv4 := ip.To4(); ipv4 != nil {
407
			ipv4Addrs = append(ipv4Addrs, ipv4.String())
408
		} else {
409
			ipv6Addrs = append(ipv6Addrs, ip.String())
410
		}
411
	}
412
	return
413
}
414
415
func (l *base) detectPlatform() {
416
	if l.getServerInfo().Mode.IsOffline() {
417
		l.setPlatform(models.Platform{Name: "unknown"})
418
		return
419
	}
420
	ok, instanceID, err := l.detectRunningOnAws()
421
	if err != nil {
422
		l.setPlatform(models.Platform{Name: "other"})
423
		return
424
	}
425
	if ok {
426
		l.setPlatform(models.Platform{
427
			Name:       "aws",
428
			InstanceID: instanceID,
429
		})
430
		return
431
	}
432
433
	//TODO Azure, GCP...
434
	l.setPlatform(models.Platform{Name: "other"})
435
	return
436
}
437
438
func (l *base) detectRunningOnAws() (ok bool, instanceID string, err error) {
439
	if r := l.exec("type curl", noSudo); r.isSuccess() {
440
		cmd := "curl --max-time 1 --noproxy 169.254.169.254 http://169.254.169.254/latest/meta-data/instance-id"
441
		r := l.exec(cmd, noSudo)
442
		if r.isSuccess() {
443
			id := strings.TrimSpace(r.Stdout)
444
			if !l.isAwsInstanceID(id) {
445
				return false, "", nil
446
			}
447
			return true, id, nil
448
		}
449
450
		switch r.ExitStatus {
451
		case 28, 7:
452
			// Not running on AWS
453
			//  7   Failed to connect to host.
454
			// 28  operation timeout.
455
			return false, "", nil
456
		}
457
	}
458
459
	if r := l.exec("type wget", noSudo); r.isSuccess() {
460
		cmd := "wget --tries=3 --timeout=1 --no-proxy -q -O - http://169.254.169.254/latest/meta-data/instance-id"
461
		r := l.exec(cmd, noSudo)
462
		if r.isSuccess() {
463
			id := strings.TrimSpace(r.Stdout)
464
			if !l.isAwsInstanceID(id) {
465
				return false, "", nil
466
			}
467
			return true, id, nil
468
		}
469
470
		switch r.ExitStatus {
471
		case 4, 8:
472
			// Not running on AWS
473
			// 4   Network failure
474
			// 8   Server issued an error response.
475
			return false, "", nil
476
		}
477
	}
478
	return false, "", fmt.Errorf(
479
		"Failed to curl or wget to AWS instance metadata on %s. container: %s",
480
		l.ServerInfo.ServerName, l.ServerInfo.Container.Name)
481
}
482
483
// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html
484
var awsInstanceIDPattern = regexp.MustCompile(`^i-[0-9a-f]+$`)
485
486
func (l *base) isAwsInstanceID(str string) bool {
487
	return awsInstanceIDPattern.MatchString(str)
488
}
489
490
func (l *base) convertToModel() models.ScanResult {
491
	ctype := l.ServerInfo.ContainerType
492
	if l.ServerInfo.Container.ContainerID != "" && ctype == "" {
493
		ctype = "docker"
494
	}
495
	container := models.Container{
496
		ContainerID: l.ServerInfo.Container.ContainerID,
497
		Name:        l.ServerInfo.Container.Name,
498
		Image:       l.ServerInfo.Container.Image,
499
		Type:        ctype,
500
	}
501
502
	errs := []string{}
503
	for _, e := range l.errs {
504
		errs = append(errs, fmt.Sprintf("%s", e))
505
	}
506
507
	return models.ScanResult{
508
		JSONVersion:   models.JSONVersion,
509
		ServerName:    l.ServerInfo.ServerName,
510
		ScannedAt:     time.Now(),
511
		ScanMode:      l.ServerInfo.Mode.String(),
512
		Family:        l.Distro.Family,
513
		Release:       l.Distro.Release,
514
		Container:     container,
515
		Platform:      l.Platform,
516
		IPv4Addrs:     l.ServerInfo.IPv4Addrs,
517
		IPv6Addrs:     l.ServerInfo.IPv6Addrs,
518
		ScannedCves:   l.VulnInfos,
519
		RunningKernel: l.Kernel,
520
		Packages:      l.Packages,
521
		SrcPackages:   l.SrcPackages,
522
		Optional:      l.ServerInfo.Optional,
523
		Errors:        errs,
524
	}
525
}
526
527
func (l *base) setErrs(errs []error) {
528
	l.errs = errs
529
}
530
531
func (l *base) getErrs() []error {
532
	return l.errs
533
}
534
535
const (
536
	systemd  = "systemd"
537
	upstart  = "upstart"
538
	sysVinit = "init"
539
)
540
541
// https://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem
542
func (l *base) detectInitSystem() (string, error) {
543
	var f func(string) (string, error)
544
	f = func(cmd string) (string, error) {
545
		r := l.exec(cmd, sudo)
546
		if !r.isSuccess() {
547
			return "", fmt.Errorf("Failed to stat %s: %s", cmd, r)
548
		}
549
		scanner := bufio.NewScanner(strings.NewReader(r.Stdout))
550
		scanner.Scan()
551
		line := strings.TrimSpace(scanner.Text())
552
		if strings.Contains(line, "systemd") {
553
			return systemd, nil
554
		} else if strings.Contains(line, "upstart") {
555
			return upstart, nil
556
		} else if strings.Contains(line, "File: ‘/proc/1/exe’ -> ‘/sbin/init’") ||
557
			strings.Contains(line, "File: `/proc/1/exe' -> `/sbin/init'") {
558
			return f("stat /sbin/init")
559
		} else if line == "File: ‘/sbin/init’" ||
560
			line == "File: `/sbin/init'" {
561
			r := l.exec("/sbin/init --version", noSudo)
562
			if r.isSuccess() {
563
				if strings.Contains(r.Stdout, "upstart") {
564
					return upstart, nil
565
				}
566
			}
567
			return sysVinit, nil
568
		}
569
		return "", fmt.Errorf("Failed to detect a init system: %s", line)
570
	}
571
	return f("stat /proc/1/exe")
572
}
573
574
func (l *base) detectServiceName(pid string) (string, error) {
575
	cmd := fmt.Sprintf("systemctl status --quiet --no-pager %s", pid)
576
	r := l.exec(cmd, noSudo)
577
	if !r.isSuccess() {
578
		return "", fmt.Errorf("Failed to stat %s: %s", cmd, r)
579
	}
580
	return l.parseSystemctlStatus(r.Stdout), nil
581
}
582
583
func (l *base) parseSystemctlStatus(stdout string) string {
584
	scanner := bufio.NewScanner(strings.NewReader(stdout))
585
	scanner.Scan()
586
	line := scanner.Text()
587
	ss := strings.Fields(line)
588
	if len(ss) < 2 || strings.HasPrefix(line, "Failed to get unit for PID") {
589
		return ""
590
	}
591
	return ss[1]
592
}
593