Completed
Pull Request — master (#769)
by
unknown
12:17
created

scan.parseStatus   A

Complexity

Conditions 3

Size

Total Lines 17
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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