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