/
unix_posix.go
290 lines (242 loc) · 7 KB
/
unix_posix.go
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//go:build !windows
package unix
import (
"bufio"
"context"
"fmt"
"os"
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/hcl"
"github.com/shirou/gopsutil/v3/process"
workloadattestorv1 "github.com/spiffe/spire-plugin-sdk/proto/spire/plugin/agent/workloadattestor/v1"
configv1 "github.com/spiffe/spire-plugin-sdk/proto/spire/service/common/config/v1"
"github.com/spiffe/spire/pkg/common/catalog"
"github.com/spiffe/spire/pkg/common/util"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func builtin(p *Plugin) catalog.BuiltIn {
return catalog.MakeBuiltIn(pluginName,
workloadattestorv1.WorkloadAttestorPluginServer(p),
configv1.ConfigServiceServer(p),
)
}
type processInfo interface {
Uids() ([]int32, error)
Gids() ([]int32, error)
Groups() ([]string, error)
Exe() (string, error)
NamespacedExe() string
}
type PSProcessInfo struct {
*process.Process
}
func (ps PSProcessInfo) NamespacedExe() string {
return getProcPath(ps.Pid, "exe")
}
// Groups returns the supplementary group IDs
// This is a custom implementation that only works for linux until the next issue is fixed
// https://github.com/shirou/gopsutil/issues/913
func (ps PSProcessInfo) Groups() ([]string, error) {
if runtime.GOOS != "linux" {
return []string{}, nil
}
statusPath := getProcPath(ps.Pid, "status")
f, err := os.Open(statusPath)
if err != nil {
return nil, err
}
defer f.Close()
scnr := bufio.NewScanner(f)
for scnr.Scan() {
row := scnr.Text()
parts := strings.SplitN(row, ":", 2)
if len(parts) != 2 {
continue
}
key := strings.ToLower(strings.TrimSpace(parts[0]))
if key == "groups" {
value := strings.TrimSpace(parts[1])
return strings.Fields(value), nil
}
}
if err := scnr.Err(); err != nil {
return nil, err
}
return []string{}, nil
}
type Configuration struct {
DiscoverWorkloadPath bool `hcl:"discover_workload_path"`
WorkloadSizeLimit int64 `hcl:"workload_size_limit"`
}
type Plugin struct {
workloadattestorv1.UnsafeWorkloadAttestorServer
configv1.UnsafeConfigServer
mu sync.Mutex
config *Configuration
log hclog.Logger
// hooks for tests
hooks struct {
newProcess func(pid int32) (processInfo, error)
lookupUserByID func(id string) (*user.User, error)
lookupGroupByID func(id string) (*user.Group, error)
}
}
func New() *Plugin {
p := &Plugin{}
p.hooks.newProcess = func(pid int32) (processInfo, error) { p, err := process.NewProcess(pid); return PSProcessInfo{p}, err }
p.hooks.lookupUserByID = user.LookupId
p.hooks.lookupGroupByID = user.LookupGroupId
return p
}
func (p *Plugin) SetLogger(log hclog.Logger) {
p.log = log
}
func (p *Plugin) Attest(_ context.Context, req *workloadattestorv1.AttestRequest) (*workloadattestorv1.AttestResponse, error) {
config, err := p.getConfig()
if err != nil {
return nil, err
}
proc, err := p.hooks.newProcess(req.Pid)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get process: %v", err)
}
var selectorValues []string
uid, err := p.getUID(proc)
if err != nil {
return nil, err
}
selectorValues = append(selectorValues, makeSelectorValue("uid", uid))
if user, ok := p.getUserName(uid); ok {
selectorValues = append(selectorValues, makeSelectorValue("user", user))
}
gid, err := p.getGID(proc)
if err != nil {
return nil, err
}
selectorValues = append(selectorValues, makeSelectorValue("gid", gid))
if group, ok := p.getGroupName(gid); ok {
selectorValues = append(selectorValues, makeSelectorValue("group", group))
}
sgIDs, err := proc.Groups()
if err != nil {
return nil, status.Errorf(codes.Internal, "supplementary GIDs lookup: %v", err)
}
for _, sgID := range sgIDs {
selectorValues = append(selectorValues, makeSelectorValue("supplementary_gid", sgID))
if sGroup, ok := p.getGroupName(sgID); ok {
selectorValues = append(selectorValues, makeSelectorValue("supplementary_group", sGroup))
}
}
// obtaining the workload process path and digest are behind a config flag
// since it requires the agent to have permissions that might not be
// available.
if config.DiscoverWorkloadPath {
processPath, err := p.getPath(proc)
if err != nil {
return nil, err
}
selectorValues = append(selectorValues, makeSelectorValue("path", processPath))
if config.WorkloadSizeLimit >= 0 {
exePath := p.getNamespacedPath(proc)
sha256Digest, err := util.GetSHA256Digest(exePath, config.WorkloadSizeLimit)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
selectorValues = append(selectorValues, makeSelectorValue("sha256", sha256Digest))
}
}
return &workloadattestorv1.AttestResponse{
SelectorValues: selectorValues,
}, nil
}
func (p *Plugin) Configure(_ context.Context, req *configv1.ConfigureRequest) (*configv1.ConfigureResponse, error) {
config := new(Configuration)
if err := hcl.Decode(config, req.HclConfiguration); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to decode configuration: %v", err)
}
p.setConfig(config)
return &configv1.ConfigureResponse{}, nil
}
func (p *Plugin) getConfig() (*Configuration, error) {
p.mu.Lock()
config := p.config
p.mu.Unlock()
if config == nil {
return nil, status.Error(codes.FailedPrecondition, "not configured")
}
return config, nil
}
func (p *Plugin) setConfig(config *Configuration) {
p.mu.Lock()
p.config = config
p.mu.Unlock()
}
func (p *Plugin) getUID(proc processInfo) (string, error) {
uids, err := proc.Uids()
if err != nil {
return "", status.Errorf(codes.Internal, "UIDs lookup: %v", err)
}
switch len(uids) {
case 0:
return "", status.Error(codes.Internal, "UIDs lookup: no UIDs for process")
case 1:
return fmt.Sprint(uids[0]), nil
default:
return fmt.Sprint(uids[1]), nil
}
}
func (p *Plugin) getUserName(uid string) (string, bool) {
u, err := p.hooks.lookupUserByID(uid)
if err != nil {
return "", false
}
return u.Username, true
}
func (p *Plugin) getGID(proc processInfo) (string, error) {
gids, err := proc.Gids()
if err != nil {
return "", status.Errorf(codes.Internal, "GIDs lookup: %v", err)
}
switch len(gids) {
case 0:
return "", status.Error(codes.Internal, "GIDs lookup: no GIDs for process")
case 1:
return fmt.Sprint(gids[0]), nil
default:
return fmt.Sprint(gids[1]), nil
}
}
func (p *Plugin) getGroupName(gid string) (string, bool) {
g, err := p.hooks.lookupGroupByID(gid)
if err != nil {
return "", false
}
return g.Name, true
}
func (p *Plugin) getPath(proc processInfo) (string, error) {
path, err := proc.Exe()
if err != nil {
return "", status.Errorf(codes.Internal, "path lookup: %v", err)
}
return path, nil
}
func (p *Plugin) getNamespacedPath(proc processInfo) string {
return proc.NamespacedExe()
}
func makeSelectorValue(kind, value string) string {
return fmt.Sprintf("%s:%s", kind, value)
}
func getProcPath(pID int32, lastPath string) string {
procPath := os.Getenv("HOST_PROC")
if procPath == "" {
procPath = "/proc"
}
return filepath.Join(procPath, strconv.FormatInt(int64(pID), 10), lastPath)
}