-
Notifications
You must be signed in to change notification settings - Fork 51
/
secretsproxy.go
336 lines (289 loc) · 9.84 KB
/
secretsproxy.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package secretsproxy
import (
"bufio"
"context"
"fmt"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"github.com/aporeto-inc/oxy/forward"
"github.com/shirou/gopsutil/process"
"go.aporeto.io/trireme-lib/common"
"go.aporeto.io/trireme-lib/controller/constants"
"go.aporeto.io/trireme-lib/controller/internal/portset"
"go.aporeto.io/trireme-lib/controller/pkg/fqconfig"
"go.aporeto.io/trireme-lib/controller/pkg/secrets"
"go.aporeto.io/trireme-lib/controller/pkg/urisearch"
"go.aporeto.io/trireme-lib/monitor/remoteapi/server"
"go.aporeto.io/trireme-lib/policy"
"go.aporeto.io/trireme-lib/utils/cache"
"go.uber.org/zap"
)
// SecretsProxy holds all state information for applying policy
// in the secrets socket API.
type SecretsProxy struct {
socketPath string
forwarder *forward.Forwarder // nolint: structcheck
apiCacheMapping cache.DataStore
drivers cache.DataStore
cgroupCache cache.DataStore
policyCache cache.DataStore
server *http.Server
sync.Mutex
}
// NewSecretsProxy creates a new secrets proxy.
func NewSecretsProxy() *SecretsProxy {
return &SecretsProxy{
socketPath: constants.DefaultSecretsPath,
drivers: cache.NewCache("secrets driver cache"),
apiCacheMapping: cache.NewCache("secrets api cache"),
cgroupCache: cache.NewCache("secrets pu cache"),
policyCache: cache.NewCache("policy cache"),
}
}
// Run implements the run method of the CtrlInterface. It starts the proxy
// server and initializes the data structures.
func (s *SecretsProxy) Run(ctx context.Context) error {
s.Lock()
defer s.Unlock()
var err error
// Start a custom listener
addr, _ := net.ResolveUnixAddr("unix", s.socketPath)
nl, err := net.ListenUnix("unix", addr)
if err != nil {
return fmt.Errorf("Unable to start API server: %s", err)
}
s.server = &http.Server{
Handler: http.HandlerFunc(s.apiProcessor),
}
go func() {
<-ctx.Done()
s.server.Close() // nolint errcheck
}()
go s.server.Serve(server.NewUIDListener(nl)) // nolint errcheck
return nil
}
// Enforce implements the corresponding interface of enforcers.
func (s *SecretsProxy) Enforce(ctx context.Context, contextID string, puInfo *policy.PUInfo) error {
return s.updateService(ctx, puInfo)
}
// Unenforce implements the corresponding interface of the enforcers.
func (s *SecretsProxy) Unenforce(contextID string) error {
return s.deleteService(contextID)
}
// GetFilterQueue is a stub for TCP proxy
func (s *SecretsProxy) GetFilterQueue() *fqconfig.FilterQueue {
return nil
}
// GetPortSetInstance returns nil for the proxy
func (s *SecretsProxy) GetPortSetInstance() portset.PortSet {
return nil
}
// UpdateSecrets updates the secrets of running enforcers managed by trireme. Remote enforcers will
// get the secret updates with the next policy push.
func (s *SecretsProxy) UpdateSecrets(secret secrets.Secrets) error {
return nil
}
// apiProcessor is called for every request. It processes the request
// and forwards to the originator of the secrets service after
// authenticating that the client can access the service.
func (s *SecretsProxy) apiProcessor(w http.ResponseWriter, r *http.Request) {
zap.L().Info("Processing secrets call",
zap.String("URI", r.RequestURI),
zap.String("Host", r.Host),
zap.String("Remote address", r.RemoteAddr),
)
// The remote address will contain the uid, gid and pid of the calling process.
// This is because of the specific socket listener we are uing.
parts := strings.Split(r.RemoteAddr, ":")
if len(parts) != 3 {
httpError(w, fmt.Errorf("Bad Remote Address"), "Unauthorized request", http.StatusUnauthorized)
return
}
// We only care about the originating PID.
pid := parts[2]
cgroup, err := findParentCgroup(pid)
if err != nil {
httpError(w, err, "Unauthorized client - not the first process", http.StatusUnauthorized)
return
}
data, err := s.apiCacheMapping.Get(cgroup)
if err != nil {
httpError(w, err, "Unauthorized client", http.StatusUnauthorized)
return
}
// Find the corresponding API cache with the access permissions for
// this particular client.
apiCache, ok := data.(*urisearch.APICache)
if !ok {
httpError(w, fmt.Errorf("Invalid data types"), "Internal server error - invalid type", http.StatusInternalServerError)
return
}
// Find the identity of the PU
policyData, err := s.policyCache.Get(cgroup)
if err != nil {
httpError(w, err, "Unauthorized client", http.StatusUnauthorized)
return
}
scopes, ok := policyData.([]string)
if !ok {
httpError(w, fmt.Errorf("Invalid data types"), "Internal server error - invalid type", http.StatusInternalServerError)
return
}
// Search the API cache for matching rules.
found, _ := apiCache.FindAndMatchScope(r.Method, r.RequestURI, scopes)
if !found {
httpError(w, fmt.Errorf("Unauthorized service"), "Unauthorized access", http.StatusUnauthorized)
return
}
// Retrieve the secrets driver data and information.
driverData, err := s.drivers.Get(cgroup)
if err != nil {
httpError(w, err, "No secrets driver for this client", http.StatusBadRequest)
return
}
driver, ok := driverData.(SecretsDriver)
if !ok {
httpError(w, fmt.Errorf("driver not found"), "Bad driver", http.StatusInternalServerError)
return
}
// Transfor the request based on the driver.
if err := driver.Transform(r); err != nil {
httpError(w, err, "Secrets driver error", http.StatusInternalServerError)
return
}
// Forward the request. TODO .. we need to massage the return here.
forwarder, err := forward.New(forward.RoundTripper(driver.Transport()))
if err != nil {
httpError(w, err, "Failed to configure forwarder", http.StatusInternalServerError)
return
}
forwarder.ServeHTTP(w, r)
}
func (s *SecretsProxy) updateService(ctx context.Context, puInfo *policy.PUInfo) error {
var cgroup string
// Only supporting secrets for containers PUs at this time.
if puInfo.Runtime.PUType() != common.ContainerPU {
return nil
}
// First we need to determine the corresponding cgroup. We will look at the
// cache since this might be an update event. If that fails, we will look
// at the runtime. If it is not found we abort. If we find the cgroup
// we add it to the cache for future reference.
cgroupData, err := s.cgroupCache.Get(puInfo.ContextID)
if err == nil {
cgroup = cgroupData.(string)
} else {
if puInfo.Runtime == nil {
return fmt.Errorf("Unable to find cgroup")
}
var found bool
cgroup, found = puInfo.Policy.Annotations().Get("@sys:cgroupparent")
if !found {
// This is not Kubernetes. We will associate the cgroup with the enforcer.
cgroup = puInfo.ContextID
}
s.cgroupCache.AddOrUpdate(puInfo.ContextID, cgroup)
}
scopes := append(puInfo.Policy.Identity().Copy().Tags, puInfo.Policy.Scopes()...)
s.policyCache.AddOrUpdate(cgroup, scopes)
// Scan through the dependent services for secrets distribution services.
for _, service := range puInfo.Policy.DependentServices() {
// Ignore all other services
if service.Type != policy.ServiceSecretsProxy {
continue
}
uriCache := urisearch.NewAPICache(service.HTTPRules, service.ID, true)
s.apiCacheMapping.AddOrUpdate(cgroup, uriCache)
// Parse the service definition and instantiate the transform driver.
d, err := NewGenericSecretsDriver(service.CACert, service.AuthToken, service.NetworkInfo)
if err != nil {
return fmt.Errorf("Failed to create secrets driver: %s", err)
}
s.drivers.AddOrUpdate(cgroup, d)
}
return nil
}
func (s *SecretsProxy) deleteService(contextID string) error {
cgroupData, err := s.cgroupCache.Get(contextID)
if err != nil {
// Returning nil here. Nothing anyone can do about it.
zap.L().Debug("PU not found in secrets controller - unable to clean state")
return nil
}
s.cgroupCache.Remove(contextID) // nolint errcheck
s.apiCacheMapping.Remove(cgroupData.(string)) // nolint errcheck
s.drivers.Remove(cgroupData.(string)) // nolint errcheck
s.policyCache.Remove(cgroupData.(string)) // nolint errcheck
return nil
}
func httpError(w http.ResponseWriter, err error, msg string, number int) {
zap.L().Error(msg, zap.Error(err))
http.Error(w, msg, number)
}
// ValidateOriginProcess implements a strict validation of the origin process. We might add later.
func ValidateOriginProcess(pid string) (string, error) {
pidNumber, err := strconv.Atoi(pid)
if err != nil {
return "", fmt.Errorf("Invalid PID %s", pid)
}
process, err := process.NewProcess(int32(pidNumber))
if err != nil {
return "", fmt.Errorf("Process not found: %s", err)
}
ppid, err := process.Ppid()
if err != nil {
return "", fmt.Errorf("Parent process not found: %s", err)
}
parentPidCgroup, err := processCgroups(strconv.Itoa(int(ppid)), "net_cls,net_prio")
if err != nil {
return "", fmt.Errorf("Parent cgroup not found: %s", err)
}
if parentPidCgroup != "/" {
return "", fmt.Errorf("Parent is not root cgroup - authorization fail")
}
return findParentCgroup(pid)
}
func processCgroups(pid string, cgroupType string) (string, error) {
path := fmt.Sprintf("/aporetoproc/%s/cgroup", pid)
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close() // nolint
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if err := scanner.Err(); err != nil {
return "", err
}
text := scanner.Text()
if !strings.Contains(text, cgroupType) {
continue
}
parts := strings.SplitN(text, ":", 3)
if len(parts) < 3 {
continue
}
return parts[2], nil
}
return "", fmt.Errorf("cgroup not found")
}
// findParentCgroup returns the parent cgroup of the process caller
func findParentCgroup(pid string) (string, error) {
cgroup, err := processCgroups(pid, "net_cls,net_prio")
if err != nil {
return "", fmt.Errorf("Invalid cgroup: %s", err)
}
for i := len(cgroup) - 1; i > 0; i-- {
if cgroup[i:i+1] == "/" {
return cgroup[:i], nil
}
}
if strings.HasPrefix(cgroup, "/docker/") && len(cgroup) > 8 {
return cgroup[8:20], nil
}
return "", fmt.Errorf("Cannot find parent cgroup: %s", pid)
}