-
Notifications
You must be signed in to change notification settings - Fork 26
/
main.go
400 lines (327 loc) · 9.58 KB
/
main.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// Copyright 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/docker/go-plugins-helpers/authorization"
version_pkg "github.com/open-policy-agent/opa-docker-authz/version"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/loader"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/sdk"
)
// DockerAuthZPlugin implements the authorization.Plugin interface. Every
// request received by the Docker daemon will be forwarded to the AuthZReq
// function. The AuthZReq function returns a response that indicates whether
// the request should be allowed or denied.
type DockerAuthZPlugin struct {
configFile string
policyFile string
allowPath string
instanceID string
skipPing bool
quiet bool
logOnlyDenied bool
opa *sdk.OPA
}
// AuthZReq is called when the Docker daemon receives an API request. AuthZReq
// returns an authorization.Response that indicates whether the request should
// be allowed or denied.
func (p DockerAuthZPlugin) AuthZReq(r authorization.Request) authorization.Response {
ctx := context.Background()
allowed, err := p.evaluate(ctx, r)
if allowed {
return authorization.Response{Allow: true}
} else if err != nil {
return authorization.Response{Err: err.Error()}
}
return authorization.Response{Msg: "request rejected by administrative policy"}
}
// AuthZRes is called before the Docker daemon returns an API response. All responses
// are allowed.
func (DockerAuthZPlugin) AuthZRes(authorization.Request) authorization.Response {
return authorization.Response{Allow: true}
}
func (p DockerAuthZPlugin) evaluatePolicyFile(ctx context.Context, r authorization.Request) (bool, error) {
if _, err := os.Stat(p.policyFile); os.IsNotExist(err) {
log.Printf("OPA policy file %s does not exist, failing open and allowing request", p.policyFile)
return true, err
}
bs, err := os.ReadFile(p.policyFile)
if err != nil {
return false, err
}
input, err := makeInput(r)
if err != nil {
return false, err
}
allowed, err := func() (bool, error) {
eval := rego.New(
rego.Query(p.allowPath),
rego.Input(input),
rego.Module(p.policyFile, string(bs)),
)
rs, err := eval.Eval(ctx)
if err != nil {
return false, err
}
if len(rs) == 0 {
// Decision is undefined. Fallback to deny.
return false, nil
}
allowed, ok := rs[0].Expressions[0].Value.(bool)
if !ok {
return false, fmt.Errorf("administrative policy decision invalid")
}
return allowed, nil
}()
decisionID, _ := uuid4()
configHash := sha256.Sum256(bs)
labels := map[string]string{
"app": "opa-docker-authz",
"id": p.instanceID,
"opa_version": version_pkg.OPAVersion,
"plugin_version": version_pkg.Version,
}
decisionLog := map[string]interface{}{
"labels": labels,
"decision_id": decisionID,
"config_hash": hex.EncodeToString(configHash[:]),
"input": input,
"result": allowed,
"timestamp": time.Now().Format(time.RFC3339Nano),
}
if err != nil {
i, _ := json.Marshal(input)
log.Printf("Returning OPA policy decision: %v (error: %v; input: %v)", allowed, err, i)
} else {
if !p.quiet {
if !(p.logOnlyDenied && allowed) {
dl, _ := json.Marshal(decisionLog)
log.Printf("Returning OPA policy decision: %v: %s", allowed, string(dl))
}
}
}
return allowed, err
}
func (p DockerAuthZPlugin) evaluate(ctx context.Context, r authorization.Request) (bool, error) {
if p.skipPing && r.RequestMethod == "HEAD" && r.RequestURI == "/_ping" {
return true, nil
}
if p.configFile != "" {
input, err := makeInput(r)
if err != nil {
return false, err
}
decisionOptions := sdk.DecisionOptions{
Input: input,
Path: p.allowPath,
}
result, err := p.opa.Decision(ctx, decisionOptions)
if err != nil {
return false, err
}
decision, ok := result.Result.(bool)
if !ok || !decision {
return false, nil
}
return true, nil
}
return p.evaluatePolicyFile(ctx, r)
}
type BindMount struct {
Source string
ReadOnly bool
Resolved string
}
func listBindMounts(body map[string]interface{}) []BindMount {
var result []BindMount
hostConfig, ok := body["HostConfig"].(map[string]interface{})
if ok {
binds, ok := hostConfig["Binds"].([]interface{})
if ok {
for _, v := range binds {
bind, ok := v.(string)
if ok && strings.HasPrefix(bind, "/") {
bindParts := strings.Split(bind, ":")
hostPath := bindParts[0]
mount := BindMount{hostPath, false, ""}
if len(bindParts) == 3 && bindParts[2] == "ro" {
mount.ReadOnly = true
}
result = append(result, mount)
}
}
}
mounts, ok := hostConfig["Mounts"].([]interface{})
if ok {
for _, v := range mounts {
mount, ok := v.(map[string]interface{})
if !ok {
continue
}
mountType, typeOk := mount["Type"].(string)
source, srcOk := mount["Source"].(string)
if typeOk && srcOk && mountType == "bind" {
readonly, ok := mount["ReadOnly"].(bool)
result = append(result, BindMount{source, ok && readonly, ""})
}
}
}
}
// resolve bind mount paths to symlink targets
// and expand /example/../ to avoid bypassing rules
for idx, bindMount := range result {
resolved, err := filepath.EvalSymlinks(bindMount.Source)
if err == nil {
resolved = filepath.Clean(resolved)
result[idx].Resolved = resolved
}
}
return result
}
func makeInput(r authorization.Request) (interface{}, error) {
var body map[string]interface{}
if r.RequestHeaders["Content-Type"] == "application/json" && len(r.RequestBody) > 0 {
if err := json.Unmarshal(r.RequestBody, &body); err != nil {
return nil, err
}
}
u, err := url.Parse(r.RequestURI)
if err != nil {
return nil, err
}
bindMountList := listBindMounts(body)
input := map[string]interface{}{
"Headers": r.RequestHeaders,
"Path": r.RequestURI,
"PathPlain": u.Path,
"PathArr": strings.Split(u.Path, "/"),
"Query": u.Query(),
"Method": r.RequestMethod,
"Body": body,
"User": r.User,
"AuthMethod": r.UserAuthNMethod,
"BindMounts": bindMountList,
}
return input, nil
}
func uuid4() (string, error) {
bs := make([]byte, 16)
n, err := io.ReadFull(rand.Reader, bs)
if n != len(bs) || err != nil {
return "", err
}
bs[8] = bs[8]&^0xc0 | 0x80
bs[6] = bs[6]&^0xf0 | 0x40
return fmt.Sprintf("%x-%x-%x-%x-%x", bs[0:4], bs[4:6], bs[6:8], bs[8:10], bs[10:]), nil
}
func regoSyntax(p string) int {
stuffs := []string{p}
result, err := loader.AllRegos(stuffs)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
return 1
}
modules := map[string]*ast.Module{}
for _, m := range result.Modules {
modules[m.Name] = m.Parsed
}
compiler := ast.NewCompiler().SetErrorLimit(0)
if compiler.Compile(modules); compiler.Failed() {
for _, err := range compiler.Errors {
_, _ = fmt.Fprintln(os.Stderr, err)
}
return 1
}
return 0
}
func initOPA(ctx context.Context, configFile string) (*sdk.OPA, error) {
buf, err := os.Open(configFile)
if err != nil {
return nil, err
}
defer func() {
if err = buf.Close(); err != nil {
log.Fatal(err)
}
}()
options := sdk.Options{
Config: buf,
}
return sdk.New(ctx, options)
}
func normalizeAllowPath(path string, useConfig bool) string {
if useConfig && strings.HasPrefix(path, "data") {
return strings.ReplaceAll(strings.TrimPrefix(path, "data"), ".", "/")
}
if !useConfig && strings.HasPrefix(path, "/") {
return "data" + strings.ReplaceAll(strings.TrimPrefix(path, "data"), "/", ".")
}
return path
}
func main() {
pluginName := flag.String("plugin-name", "opa-docker-authz", "sets the plugin name that will be registered with Docker")
allowPath := flag.String("allowPath", "data.docker.authz.allow", "sets the path of the allow decision in OPA")
configFile := flag.String("config-file", "", "sets the path of the config file to load")
policyFile := flag.String("policy-file", "", "sets the path of the policy file to load")
skipPing := flag.Bool("skip-ping", true, "skip policy evaluation for requests to /_ping endpoint")
version := flag.Bool("version", false, "print the version of the plugin")
check := flag.Bool("check", false, "checks the syntax of the policy-file")
quiet := flag.Bool("quiet", false, "disable logging of each HTTP request (policy-file mode)")
logOnlyDenied := flag.Bool("log-only-denied", false, "only log denied requests (policy-file mode)")
flag.Parse()
if *version {
fmt.Println("Version:", version_pkg.Version)
fmt.Println("OPA Version:", version_pkg.OPAVersion)
os.Exit(0)
}
ctx := context.Background()
useConfig := *configFile != ""
var opa *sdk.OPA
if useConfig {
if *policyFile != "" {
log.Fatal("Only one of config-file and policy-file arguments allowed")
}
var err error
opa, err = initOPA(ctx, *configFile)
if err != nil {
log.Fatal(err)
}
defer opa.Stop(ctx)
}
instanceID, _ := uuid4()
p := DockerAuthZPlugin{
configFile: *configFile,
policyFile: *policyFile,
allowPath: normalizeAllowPath(*allowPath, useConfig),
instanceID: instanceID,
skipPing: *skipPing,
quiet: *quiet,
logOnlyDenied: *logOnlyDenied,
opa: opa,
}
if *check && *policyFile != "" {
os.Exit(regoSyntax(*policyFile))
}
h := authorization.NewHandler(p)
log.Println("Starting server.")
err := h.ServeUnix(*pluginName, 0)
if err != nil {
log.Printf("Failed serving on socket: %v", err)
}
}