-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.go
More file actions
299 lines (271 loc) · 7.85 KB
/
backend.go
File metadata and controls
299 lines (271 loc) · 7.85 KB
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
package kmipengine
import (
"context"
"encoding/json"
"fmt"
"github.com/cryacry/kmip-plugins/kmip"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/jsonutil"
"github.com/hashicorp/vault/sdk/logical"
"strings"
"sync"
)
// Factory returns a new backend as logical.Backend
func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
b := NewKmipBackend(ctx, conf)
return b, nil
}
type locks struct {
scopeLock map[string]*sync.RWMutex
roleLock map[string]*sync.RWMutex
configLock *sync.RWMutex
certLock map[string]*sync.RWMutex
snLock *sync.Mutex
}
// KmipBackend is used storing secrets directly into the physical
// backend.
type KmipBackend struct {
*framework.Backend
locks
tokenAccessor string
// listening service management
server *kmip.Server
// logger is the server logger copied over from core
logger log.Logger
storage logical.Storage
lock *sync.Mutex
TokenCreate func(ctx context.Context, scopeName, roleName, tokenAccessor string) (*logical.Auth, error)
TokenRevoke func(ctx context.Context, accessor string) error
PolicyCreate func(ctx context.Context, scopeName, roleName string) error
PolicyDelete func(ctx context.Context, scope, role string) error
MountTransit func(ctx context.Context, scope, role string) error
UnmountTransit func(ctx context.Context, scope, role string) error
NamespaceByPath func(nsPath string) (*namespace.Namespace, error)
}
func NewKmipBackend(ctx context.Context, config *logical.BackendConfig) *KmipBackend {
b := &KmipBackend{
logger: config.Logger,
locks: locks{
scopeLock: make(map[string]*sync.RWMutex),
roleLock: make(map[string]*sync.RWMutex),
certLock: make(map[string]*sync.RWMutex),
configLock: new(sync.RWMutex),
snLock: new(sync.Mutex),
},
lock: new(sync.Mutex),
server: &kmip.Server{},
}
backend := &framework.Backend{
BackendType: logical.TypeLogical,
Help: strings.TrimSpace(KmipHelp),
Paths: framework.PathAppend(
[]*framework.Path{
pathConfig(b),
pathCa(b),
},
pathScope(b),
pathRole(b),
pathCredentials(b),
),
Secrets: []*framework.Secret{},
InitializeFunc: b.initialize,
Clean: b.cleanup,
}
backend.Setup(ctx, config)
b.Backend = backend
return b
}
// write default config
func (kb *KmipBackend) initialize(ctx context.Context, l *logical.InitializationRequest) error {
kb.serverInit()
kb.storage = l.Storage
out, err := kb.storage.Get(ctx, configPath)
if err != nil {
return err
}
if out != nil {
// exist config information
var data map[string]interface{}
// load config from storage
if err := jsonutil.DecodeJSON(out.Value, &data); err != nil {
return fmt.Errorf("json decoding failed: %w", err)
}
// open listener
raw := data["listen_addrs"].([]interface{})
var addrs []string
for _, k := range raw {
addrs = append(addrs, k.(string))
}
kb.setupListener(addrs)
if err := kb.initLocks(ctx); err != nil {
return err
}
return nil
}
// init default config
conf := DefaultConfigMap()
config := kb.newConfig()
MapToStruct(conf, &config)
// open listener
// set listened addr
config.ListenAddrs = kb.setupListener(config.ListenAddrs)
// create root ca chain
ns, err := namespace.FromContext(ctx)
// set new CA-Cert
s := kb.newSerialNumber()
s.readStorage(ctx, kb.storage)
rootCA := kb.newCA(s.SN.String())
rootCA.SetCACert("root", "root", "1000h", ns, s)
s.readStorage(ctx, kb.storage)
childCA := kb.newCA(s.SN.String())
childCA.SetCACert("root", "root", "1000h", ns, s)
// 1、Update root certificate chain
// rootCA
if err := rootCA.CaGenerate(config.TLSCAKeyType, config.TLSCAKeyBits, nil); err != nil {
return err
}
if err := rootCA.writeStorage(ctx, kb.storage, caPath); err != nil {
return err
}
// childCA
if err := childCA.CaGenerate(config.TLSCAKeyType, config.TLSCAKeyBits, rootCA); err != nil {
return err
}
if err := childCA.writeStorage(ctx, kb.storage, caPath); err != nil {
return err
}
if err := config.writeStorage(ctx, kb.storage); err != nil {
return fmt.Errorf("failed to write: %w", err)
}
if kb.logger.IsInfo() {
kb.logger.Info("init default config")
}
return nil
}
func (kb *KmipBackend) initLocks(ctx context.Context) error {
scopePath := "scope/"
scopes, err := listStorage(ctx, kb.storage, scopePath)
if err != nil {
return err
}
for _, scopeName := range scopes {
kb.scopeLock[scopeName] = new(sync.RWMutex)
rolePath := fmt.Sprintf("scope/%s/role/", scopeName)
roles, err := listStorage(ctx, kb.storage, rolePath)
if err != nil {
return err
}
for _, roleName := range roles {
kb.roleLock[scopeName+"-"+roleName] = new(sync.RWMutex)
}
}
return nil
}
// stop kmip listener
func (kb *KmipBackend) cleanup(ctx context.Context) {
kb.stopListen()
if kb.logger.IsInfo() {
kb.logger.Info("Server is shutting down")
}
}
func readStorage(ctx context.Context, storage logical.Storage, key string) (map[string]interface{}, error) {
out, err := storage.Get(ctx, key)
if err != nil {
return nil, err
}
if out == nil {
return nil, fmt.Errorf(errPathDataIsEmpty)
}
// Fast-path the no data case
var data map[string]interface{}
// load config from storage
if err := jsonutil.DecodeJSON(out.Value, &data); err != nil {
return nil, fmt.Errorf("json decoding failed: %w", err)
}
return data, nil
}
func listStorage(ctx context.Context, storage logical.Storage, key string) ([]string, error) {
if key != "" && !strings.HasSuffix(key, "/") {
key = key + "/"
}
keys, err := storage.List(ctx, key)
if err != nil {
return nil, err
}
var d []string
for _, k := range keys {
if !strings.ContainsAny(k, "/") {
d = append(d, k)
}
}
return d, nil
}
func writeStorage(ctx context.Context, storage logical.Storage, key string, data map[string]interface{}) error {
buf, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("json encoding failed: %w", err)
}
// Write out a new key
entry := &logical.StorageEntry{
Key: key,
Value: buf,
}
if err := storage.Put(ctx, entry); err != nil {
return fmt.Errorf("failed to write: %w", err)
}
return nil
}
func deleteStorage(ctx context.Context, req *logical.Request, key string) error {
//Delete the key at the request path
if err := req.Storage.Delete(ctx, key); err != nil {
return err
}
return nil
}
func (kb *KmipBackend) tokenCreate(ctx context.Context, scopeName, roleName string) (*logical.Auth, error) {
if kb.TokenCreate == nil {
return nil, fmt.Errorf("undefind kmip TokenCreate function")
}
return kb.TokenCreate(ctx, scopeName, roleName, kb.tokenAccessor)
}
func (kb *KmipBackend) tokenRevoke(ctx context.Context, accessor string) error {
if kb.TokenRevoke == nil {
return fmt.Errorf("undefind kmip TokenRevoke function")
}
return kb.TokenRevoke(ctx, accessor)
}
func (kb *KmipBackend) policyCreate(ctx context.Context, scopeName, roleName string) error {
if kb.policyCreate != nil {
return kb.PolicyCreate(ctx, scopeName, roleName)
}
return nil
}
func (kb *KmipBackend) policyDelete(ctx context.Context, scopeName, roleName string) error {
if kb.PolicyDelete != nil {
return kb.PolicyDelete(ctx, scopeName, roleName)
}
return nil
}
func (kb *KmipBackend) mountTransit(ctx context.Context, scope, role string) error {
if kb.MountTransit != nil {
return kb.MountTransit(ctx, scope, role)
}
return nil
}
func (kb *KmipBackend) unmountTransit(ctx context.Context, scope, role string) error {
if kb.UnmountTransit != nil {
return kb.UnmountTransit(ctx, scope, role)
}
return nil
}
const KmipHelp = `
KMIP backend manages certificates and writes them to the backend.
`
const KmipHelpSynopsis = `
KMIP backend management certificate chain
`
const KmipHelpDescription = `
KMIP backend, managing the creation, update, and destruction of certificate chains
`