File: compiler.go

package info (click to toggle)
snapd 2.72-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 80,412 kB
  • sloc: sh: 16,506; ansic: 16,211; python: 11,213; makefile: 1,919; exp: 190; awk: 58; xml: 22
file content (236 lines) | stat: -rw-r--r-- 7,531 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2019 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package seccomp

import (
	"bytes"
	"errors"
	"fmt"
	"os/exec"
	"regexp"
	"strconv"
	"strings"

	"github.com/snapcore/snapd/osutil"
)

var (
	// version-info format: <build-id> <libseccomp-version> <hash>
	// <features> Where, the hash is calculated over all syscall names
	// supported by the libseccomp library. The build-id is a string of up
	// to 166 chars, accommodates 128-bit MD5 (32 chars), 160-bit SHA-1 (40
	// chars) generated by GNU ld, and 83-byte (166 chars) build ID
	// generated by Go toolchain, also provides an upper limit of the
	// user-settable build ID. The hash is a 256-bit SHA-256 (64 char)
	// string. Allow libseccomp version to be 1-5 chars per field (eg, 1.2.3
	// or 12345.23456.34567) and 1-30 chars of colon-separated features. Ex:
	// 7ac348ac9c934269214b00d1692dfa50d5d4a157 2.3.3
	// 03e996919907bc7163bc83b95bca0ecab31300f20dfa365ea14047c698340e7c
	// bpf-actlog
	validVersionInfo = regexp.MustCompile(`^[0-9a-f]{1,166} [0-9]{1,5}\.[0-9]{1,5}\.[0-9]{1,5} [0-9a-f]{1,64} [-a-z0-9:]{1,30}$`)
)

type Compiler struct {
	snapSeccomp string
}

// NewCompiler returns a wrapper for the compiler binary. The path to the binary is
// looked up using the lookupTool helper.
func NewCompiler(lookupTool func(name string) (string, error)) (*Compiler, error) {
	if lookupTool == nil {
		panic("lookup tool func not provided")
	}

	path, err := lookupTool("snap-seccomp")
	if err != nil {
		return nil, err
	}

	return &Compiler{snapSeccomp: path}, nil
}

// VersionInfo returns the version information of the compiler. The format of
// version information is: <build-id> <libseccomp-version> <hash> <features>.
// Where, the hash is calculated over all syscall names supported by the
// libseccomp library.
func (c *Compiler) VersionInfo() (VersionInfo, error) {
	cmd := exec.Command(c.snapSeccomp, "version-info")
	output, err := cmd.Output()
	if err != nil {
		if exitErr, ok := err.(*exec.ExitError); ok && len(exitErr.Stderr) > 0 {
			output = exitErr.Stderr
		}
		return "", osutil.OutputErr(output, err)
	}
	raw := bytes.TrimSpace(output)
	// Example valid output:
	// 7ac348ac9c934269214b00d1692dfa50d5d4a157 2.3.3 03e996919907bc7163bc83b95bca0ecab31300f20dfa365ea14047c698340e7c bpf-actlog
	if match := validVersionInfo.Match(raw); !match {
		return "", fmt.Errorf("invalid format of version-info: %q", raw)
	}

	return VersionInfo(raw), nil
}

var compilerVersionInfoImpl = func(lookupTool func(name string) (string, error)) (VersionInfo, error) {
	c, err := NewCompiler(lookupTool)
	if err != nil {
		return VersionInfo(""), err
	}
	return c.VersionInfo()
}

// CompilerVersionInfo returns the version information of snap-seccomp
// looked up via lookupTool.
func CompilerVersionInfo(lookupTool func(name string) (string, error)) (VersionInfo, error) {
	return compilerVersionInfoImpl(lookupTool)
}

// MockCompilerVersionInfo mocks the return value of CompilerVersionInfo.
func MockCompilerVersionInfo(versionInfo string) (restore func()) {
	old := compilerVersionInfoImpl
	compilerVersionInfoImpl = func(_ func(name string) (string, error)) (VersionInfo, error) {
		return VersionInfo(versionInfo), nil
	}
	return func() {
		compilerVersionInfoImpl = old
	}
}

var errEmptyVersionInfo = errors.New("empty version-info")

// VersionInfo represents information about the seccomp compiler
type VersionInfo string

// LibseccompVersion parses VersionInfo and provides the libseccomp version
func (vi VersionInfo) LibseccompVersion() (string, error) {
	if vi == "" {
		return "", errEmptyVersionInfo
	}
	if match := validVersionInfo.Match([]byte(vi)); !match {
		return "", fmt.Errorf("invalid format of version-info: %q", vi)
	}
	return strings.Split(string(vi), " ")[1], nil
}

// Features parses the output of VersionInfo and provides the
// golang seccomp features
func (vi VersionInfo) Features() (string, error) {
	if vi == "" {
		return "", errEmptyVersionInfo
	}
	if match := validVersionInfo.Match([]byte(vi)); !match {
		return "", fmt.Errorf("invalid format of version-info: %q", vi)
	}
	return strings.Split(string(vi), " ")[3], nil
}

// HasFeature parses the output of VersionInfo and answers whether or
// not golang-seccomp supports the feature
func (vi VersionInfo) HasFeature(feature string) (bool, error) {
	features, err := vi.Features()
	if err != nil {
		return false, err
	}
	for _, f := range strings.Split(features, ":") {
		if f == feature {
			return true, nil
		}
	}
	return false, nil
}

// BuildTimeRequirementError represents the error case of a feature
// that cannot be supported because of unfulfilled build time
// requirements.
type BuildTimeRequirementError struct {
	Feature      string
	Requirements []string
}

func (e *BuildTimeRequirementError) RequirementsString() string {
	return strings.Join(e.Requirements, ", ")
}

func (e *BuildTimeRequirementError) Error() string {
	return fmt.Sprintf("%s requires a snapd built against %s", e.Feature, e.RequirementsString())
}

// SupportsRobustArgumentFiltering parses the output of VersionInfo and
// determines if libseccomp and golang-seccomp are new enough to support robust
// argument filtering
func (vi VersionInfo) SupportsRobustArgumentFiltering() error {
	libseccompVersion, err := vi.LibseccompVersion()
	if err != nil {
		return err
	}

	// Parse <libseccomp version>
	tmp := strings.Split(libseccompVersion, ".")
	maj, err := strconv.Atoi(tmp[0])
	if err != nil {
		return fmt.Errorf("cannot obtain seccomp compiler information: %v", err)
	}
	min, err := strconv.Atoi(tmp[1])
	if err != nil {
		return fmt.Errorf("cannot obtain seccomp compiler information: %v", err)
	}

	var unfulfilledReqs []string

	// libseccomp < 2.4 has significant argument filtering bugs that we
	// cannot reliably work around with this feature.
	if maj < 2 || (maj == 2 && min < 4) {
		unfulfilledReqs = append(unfulfilledReqs, "libseccomp >= 2.4")
	}

	// Due to https://github.com/seccomp/libseccomp-golang/issues/22,
	// golang-seccomp <= 0.9.0 cannot create correct BPFs for this feature.
	// The package does not contain any version information, but we know
	// that ActLog was implemented in the library after this issue was
	// fixed, so base the decision on that. ActLog is first available in
	// 0.9.1.
	res, err := vi.HasFeature("bpf-actlog")
	if err != nil {
		return err
	}
	if !res {
		unfulfilledReqs = append(unfulfilledReqs, "golang-seccomp >= 0.9.1")
	}

	if len(unfulfilledReqs) != 0 {
		return &BuildTimeRequirementError{
			Feature:      "robust argument filtering",
			Requirements: unfulfilledReqs,
		}
	}

	return nil
}

// Compile compiles given source profile and saves the result to the out
// location.
func (c *Compiler) Compile(in, out string) error {
	cmd := exec.Command(c.snapSeccomp, "compile", in, out)
	if output, err := cmd.CombinedOutput(); err != nil {
		return osutil.OutputErr(output, err)
	}
	return nil
}