-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend.go
326 lines (269 loc) · 7.94 KB
/
backend.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
package vault_sgx_plugin
import (
"context"
"crypto/sha512"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/enclaive/vault-sgx-auth/attest"
vault "github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"os"
"sort"
"strings"
"time"
)
const (
mountPath = "auth/sgx-auth/login"
)
// backend wraps the backend framework and adds a map for storing key value pairs.
type backend struct {
*framework.Backend
//TODO this should be persisted
// unknown property SealWrap
// req.Storage.Put(ctx, &logical.StorageEntry{
// Key: "enclave/"+id,
// Value: mrenclave,
// SealWrap: false,
// })
enclaves map[string]string
}
var _ logical.Factory = Factory
// Factory configures and returns Mock backends
func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
b, err := newBackend()
if err != nil {
return nil, err
}
if conf == nil {
return nil, fmt.Errorf("configuration passed into backend is nil")
}
if err := b.Setup(ctx, conf); err != nil {
return nil, err
}
return b, nil
}
func newBackend() (*backend, error) {
b := &backend{
enclaves: make(map[string]string),
}
b.Backend = &framework.Backend{
Help: strings.TrimSpace(sgxHelp),
BackendType: logical.TypeCredential,
AuthRenew: b.pathAuthRenew,
PathsSpecial: &logical.Paths{
Unauthenticated: []string{
"login",
},
},
Paths: framework.PathAppend(
[]*framework.Path{
b.pathLogin(),
b.pathUsersList(),
},
b.pathUsers(),
),
}
return b, nil
}
func NewSgxAuth(request *attest.Request) *SgxAuth {
return &SgxAuth{request: request}
}
type SgxAuth struct {
request *attest.Request
}
func (s *SgxAuth) Login(ctx context.Context, client *vault.Client) (*vault.Secret, error) {
if ctx == nil {
ctx = context.Background()
}
attestation, err := json.Marshal(s.request)
if err != nil {
return nil, err
}
loginData := map[string]interface{}{
"id": s.request.Name,
"attestation": attestation,
}
resp, err := client.Logical().WriteWithContext(ctx, mountPath, loginData)
if err != nil {
return nil, err
}
return resp, nil
}
func (b *backend) pathLogin() *framework.Path {
return &framework.Path{
Pattern: "login$",
Fields: map[string]*framework.FieldSchema{
"id": {
Type: framework.TypeString,
Description: "enclave id",
},
"attestation": {
Type: framework.TypeString,
Description: "sgx attestation",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.handleLogin,
Summary: "Log in using en enclave id and attestation",
},
},
}
}
func (b *backend) handleLogin(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
if req.Connection == nil || req.Connection.ConnState == nil {
return logical.ErrorResponse("tls connection required"), nil
}
connState := req.Connection.ConnState
if connState.PeerCertificates == nil || len(connState.PeerCertificates) == 0 {
return logical.ErrorResponse("tls client certificate required"), nil
}
attestation := data.Get("attestation").(string)
if attestation == "" {
return logical.ErrorResponse("attestation must be provided"), nil
}
request := new(attest.Request)
rawRequest, err := base64.StdEncoding.DecodeString(attestation)
if err != nil {
return logical.ErrorResponse("attestation was not base64 encoded"), nil
}
if err = json.Unmarshal(rawRequest, request); err != nil {
return logical.ErrorResponse("attestation was not base64 encoded"), nil
}
id := data.Get("id").(string)
if id == "" {
return logical.ErrorResponse("id must be provided"), nil
}
measurement, ok := b.enclaves[id]
if !ok {
return logical.ErrorResponse("unknown enclave name"), nil
}
hash := sha512.Sum512(connState.PeerCertificates[0].Raw)
if err = attest.Verify(hash, request.Quote, measurement); err != nil {
return logical.ErrorResponse("attestation failed"), nil
}
domain := fmt.Sprintf("%s.%s.svc.cluster.local", id, os.Getenv("ENCLAIVE_NAMESPACE"))
// Compose the response
resp := &logical.Response{
Auth: &logical.Auth{
InternalData: map[string]interface{}{
"attestation": attestation,
},
// Policies can be passed in as a parameter to the request
Policies: []string{"sgx-app/" + id},
NoDefaultPolicy: true,
Metadata: map[string]string{
"domain": domain,
},
// Lease options can be passed in as parameters to the request
LeaseOptions: logical.LeaseOptions{
TTL: 30 * time.Second,
MaxTTL: 60 * time.Minute,
Renewable: true,
},
},
}
return resp, nil
}
func (b *backend) pathUsers() []*framework.Path {
return []*framework.Path{
{
Pattern: "enclave/" + framework.GenericNameRegex("id"),
Fields: map[string]*framework.FieldSchema{
"id": {
Type: framework.TypeString,
Description: "Specifies the enclave id",
},
"mrenclave": {
Type: framework.TypeString,
Description: "Specifies the expected mrenclave",
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.UpdateOperation: &framework.PathOperation{
Callback: b.handleUserWrite,
Summary: "Adds a new enclave to the auth method.",
},
logical.CreateOperation: &framework.PathOperation{
Callback: b.handleUserWrite,
Summary: "Updates a enclave on the auth method.",
},
logical.DeleteOperation: &framework.PathOperation{
Callback: b.handleUserDelete,
Summary: "Deletes a enclave on the auth method.",
},
},
ExistenceCheck: b.handleExistenceCheck,
},
}
}
func (b *backend) handleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
id := data.Get("id").(string)
_, ok := b.enclaves[id]
return ok, nil
}
func (b *backend) pathUsersList() *framework.Path {
return &framework.Path{
Pattern: "enclaves/?$",
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.handleUsersList,
Summary: "List existing enclaves.",
},
},
}
}
func (b *backend) handleUsersList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
enclaveList := make([]string, len(b.enclaves))
i := 0
for u, _ := range b.enclaves {
enclaveList[i] = u
i++
}
sort.Strings(enclaveList)
return logical.ListResponse(enclaveList), nil
}
func (b *backend) handleUserWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
id := data.Get("id").(string)
if id == "" {
return logical.ErrorResponse("id must be provided"), nil
}
password := data.Get("mrenclave").(string)
if password == "" {
return logical.ErrorResponse("password must be provided"), nil
}
// Store kv pairs in map at specified path
b.enclaves[id] = password
return nil, nil
}
func (b *backend) handleUserDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
enclavename := data.Get("id").(string)
if enclavename == "" {
return logical.ErrorResponse("id must be provided"), nil
}
// Remove entry for specified path
delete(b.enclaves, enclavename)
return nil, nil
}
func (b *backend) pathAuthRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
enclavename := req.Auth.Metadata["id"]
pw := req.Auth.InternalData["attestation"].(string)
storedPassword, ok := b.enclaves[enclavename]
if !ok {
return nil, errors.New("attestation on the token could not be found")
}
if subtle.ConstantTimeCompare([]byte(pw), []byte(storedPassword)) != 1 {
return nil, errors.New("internal data does not match")
}
resp := &logical.Response{Auth: req.Auth}
resp.Auth.TTL = 30 * time.Second
resp.Auth.MaxTTL = 60 * time.Minute
return resp, nil
}
const sgxHelp = `
login with sgx attestation
`