-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
228 lines (189 loc) · 5.72 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
// 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 (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
versionpkg "github.com/build-security/pdp-docker-authz/version"
"github.com/docker/go-plugins-helpers/authorization"
)
// 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
debug bool
instanceID string
}
type PluginConfiguration struct {
PdpAddr string `json:"pdp_addr"`
AllowOnFailure bool `json:"allow_on_failure"`
}
type AuthzResult struct {
Allow bool `json:"allow"`
Messages []string `json:"messages"`
}
type ResponseBody struct {
Result AuthzResult `json:"result"`
}
// 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()
authzResult, err := p.evaluate(ctx, r)
if authzResult.Allow {
return authorization.Response{Allow: true}
} else if err != nil {
if p.debug {
log.Printf("Returning PDP decision: %v (error: %v)", true, err)
return authorization.Response{Allow: true}
}
return authorization.Response{Err: err.Error()}
}
return authorization.Response{Msg: "request rejected by administrative policy: " +
strings.Join(authzResult.Messages, " ,")}
}
// AuthZRes is called before the Docker daemon returns an API response. All responses
// are allowed.
func (p DockerAuthZPlugin) AuthZRes(_ authorization.Request) authorization.Response {
return authorization.Response{Allow: true}
}
func (p DockerAuthZPlugin) evaluate(_ context.Context, r authorization.Request) (AuthzResult, error) {
bs, err := ioutil.ReadFile(p.configFile)
if err != nil {
return AuthzResult{Allow: false}, err
}
var cfg PluginConfiguration
if err = json.Unmarshal(bs, &cfg); err != nil {
return AuthzResult{Allow: false}, err
}
input, err := makeInput(r)
if err != nil {
return AuthzResult{Allow: cfg.AllowOnFailure}, err
}
body, err := json.Marshal(input)
allowed, messages, err := func() (bool, []string, error) {
client := http.Client{
Timeout: 3 * time.Second,
}
resp, err := client.Post(cfg.PdpAddr, "application/json", bytes.NewBuffer(body))
if err != nil {
return cfg.AllowOnFailure, nil, err
}
defer dclose(resp.Body)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return cfg.AllowOnFailure, nil, err
}
var bodyJSON ResponseBody
if err = json.Unmarshal(body, &bodyJSON); err != nil {
return cfg.AllowOnFailure, nil, err
}
log.Println("Response", bodyJSON)
return bodyJSON.Result.Allow, bodyJSON.Result.Messages, nil
}()
decisionId, _ := uuid4()
configHash := sha256.Sum256(bs)
labels := map[string]string{
"app": "pdp-docker-authz",
"id": p.instanceID,
"plugin_version": versionpkg.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 PDP decision: %v (error: %v; input: %v)", allowed, err, string(i))
} else {
log.Printf("Returning PDP decision: %v", allowed)
dl, _ := json.Marshal(decisionLog)
log.Println(string(dl))
}
return AuthzResult{Allow: allowed, Messages: messages}, nil
}
func dclose(c io.Closer) {
if err := c.Close(); err != nil {
log.Println(err)
}
}
func makeInput(r authorization.Request) (interface{}, error) {
var body 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
}
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,
}
wrapped := map[string]interface{}{
"input": input,
}
return wrapped, 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 main() {
pluginName := flag.String("plugin-name", "pdp-docker-authz", "sets the plugin name that will be registered with Docker")
configFile := flag.String("config-file", "~/.pdp/config.json", "sets the path of the config file to load")
debug := flag.Bool("debug", false, "sets whether should run in debug mode")
version := flag.Bool("version", false, "print the version of the plugin")
flag.Parse()
if *version {
fmt.Println("Version:", versionpkg.Version)
os.Exit(0)
}
instanceId, _ := uuid4()
p := DockerAuthZPlugin{
configFile: *configFile,
debug: *debug,
instanceID: instanceId,
}
h := authorization.NewHandler(p)
log.Println("Starting server.")
err := h.ServeUnix(*pluginName, 0)
log.Fatal(err)
}