-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_sign_verify.go
431 lines (362 loc) · 13.1 KB
/
path_sign_verify.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package gmsm
import (
"context"
"encoding/base64"
"fmt"
"github.com/emmansun/gmsm/sm3"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/errutil"
"github.com/hashicorp/vault/sdk/helper/keysutil"
"github.com/hashicorp/vault/sdk/logical"
"github.com/mitchellh/mapstructure"
)
// BatchRequestSignItem represents a request item for batch processing.
// A map type allows us to distinguish between empty and missing values.
type batchRequestSignItem map[string]string
// BatchResponseSignItem represents a response item for batch processing
type batchResponseSignItem struct {
// signature for the input present in the corresponding batch
// request item
Signature string `json:"signature,omitempty" mapstructure:"signature"`
// The key version to be used for encryption
KeyVersion int `json:"key_version" mapstructure:"key_version"`
PublicKey []byte `json:"publickey,omitempty" mapstructure:"publickey"`
// Error, if set represents a failure encountered while encrypting a
// corresponding batch request item
Error string `json:"error,omitempty" mapstructure:"error"`
// The return paths through WriteSign in some cases are (nil, err) and others
// (logical.ErrorResponse(..),nil), and others (logical.ErrorResponse(..),err).
// For batch processing to successfully mimic previous handling for simple 'input',
// both output values are needed - though 'err' should never be serialized.
err error
}
// BatchRequestVerifyItem represents a request item for batch processing.
// A map type allows us to distinguish between empty and missing values.
type batchRequestVerifyItem map[string]string
// BatchResponseVerifyItem represents a response item for batch processing
type batchResponseVerifyItem struct {
// Valid indicates whether signature matches the signature derived from the input string
Valid bool `json:"valid" mapstructure:"valid"`
// Error, if set represents a failure encountered while encrypting a
// corresponding batch request item
Error string `json:"error,omitempty" mapstructure:"error"`
// The return paths through WriteSign in some cases are (nil, err) and others
// (logical.ErrorResponse(..),nil), and others (logical.ErrorResponse(..),err).
// For batch processing to successfully mimic previous handling for simple 'input',
// both output values are needed - though 'err' should never be serialized.
err error
}
func (b *backend) pathSign() *framework.Path {
return &framework.Path{
Pattern: "sign/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "The key to use",
},
"input": {
Type: framework.TypeString,
Description: "The base64-encoded input data",
},
"key_version": {
Type: framework.TypeInt,
Description: `The version of the key to use for signing.
Must be 0 (for latest) or a value greater than or equal
to the min_encryption_version configured on the key.`,
},
"prehashed": {
Type: framework.TypeBool,
Description: `Set to 'true' when the input is already hashed. `,
},
"marshaling_algorithm": {
Type: framework.TypeString,
Default: "asn1",
Description: `The method by which to marshal the signature. The default is 'asn1' which is used by openssl and X.509. It can also be set to 'jws' which is used for JWT signatures; setting it to this will also cause the encoding of the signature to be url-safe base64 instead of using standard base64 encoding. Currently only valid for ECDSA P-256 key types".`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathSignWrite,
},
HelpSynopsis: pathSignHelpSyn,
HelpDescription: pathSignHelpDesc,
}
}
func (b *backend) pathVerify() *framework.Path {
return &framework.Path{
Pattern: "verify/" + framework.GenericNameRegex("name"),
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeString,
Description: "The key to use",
},
"signature": {
Type: framework.TypeString,
Description: "The signature, including vault header/key version",
},
"input": {
Type: framework.TypeString,
Description: "The base64-encoded input data to verify",
},
"prehashed": {
Type: framework.TypeBool,
Description: `Set to 'true' when the input is already hashed. `,
},
"marshaling_algorithm": {
Type: framework.TypeString,
Default: "asn1",
Description: `The method by which to unmarshal the signature when verifying. The default is 'asn1' which is used by openssl and X.509; can also be set to 'jws' which is used for JWT signatures in which case the signature is also expected to be url-safe base64 encoding instead of standard base64 encoding. Currently only valid for ECDSA P-256 key types".`,
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathVerifyWrite,
},
HelpSynopsis: pathVerifyHelpSyn,
HelpDescription: pathVerifyHelpDesc,
}
}
func (b *backend) pathSignWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
name := d.Get("name").(string)
ver := d.Get("key_version").(int)
marshalingStr := d.Get("marshaling_algorithm").(string)
marshaling, ok := keysutil.MarshalingTypeMap[marshalingStr]
if !ok {
return logical.ErrorResponse(fmt.Sprintf("invalid marshaling type %q", marshalingStr)), logical.ErrInvalidRequest
}
prehashed := d.Get("prehashed").(bool)
// Get the policy
p, _, err := b.GetPolicy(ctx, PolicyRequest{
Storage: req.Storage,
Name: name,
}, b.GetRandomReader())
if err != nil {
return nil, err
}
if p == nil {
return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest
}
if !b.System().CachingDisabled() {
p.Lock(false)
}
if !p.Type.SigningSupported() {
p.Unlock()
return logical.ErrorResponse(fmt.Sprintf("key type %v does not support signing", p.Type)), logical.ErrInvalidRequest
}
batchInputRaw := d.Raw["batch_input"]
var batchInputItems []batchRequestSignItem
if batchInputRaw != nil {
err = mapstructure.Decode(batchInputRaw, &batchInputItems)
if err != nil {
p.Unlock()
return nil, errwrap.Wrapf("failed to parse batch input: {{err}}", err)
}
if len(batchInputItems) == 0 {
p.Unlock()
return logical.ErrorResponse("missing batch input to process"), logical.ErrInvalidRequest
}
} else {
// use empty string if input is missing - not an error
batchInputItems = make([]batchRequestSignItem, 1)
batchInputItems[0] = batchRequestSignItem{
"input": d.Get("input").(string),
}
}
response := make([]batchResponseSignItem, len(batchInputItems))
for i, item := range batchInputItems {
rawInput, ok := item["input"]
if !ok {
response[i].Error = "missing input"
response[i].err = logical.ErrInvalidRequest
continue
}
input, err := base64.StdEncoding.DecodeString(rawInput)
if err != nil {
response[i].Error = fmt.Sprintf("unable to decode input as base64: %s", err)
response[i].err = logical.ErrInvalidRequest
continue
}
if p.Type.HashSignatureInput() && !prehashed {
var hf = sm3.New()
hf.Write(input)
input = hf.Sum(nil)
}
sig, err := p.Sign(ver, input, marshaling)
if err != nil {
if batchInputRaw != nil {
response[i].Error = err.Error()
}
response[i].err = err
} else if sig == nil {
response[i].err = fmt.Errorf("signature could not be computed")
} else {
keyVersion := ver
if keyVersion == 0 {
keyVersion = p.LatestVersion
}
response[i].Signature = sig.Signature
response[i].PublicKey = sig.PublicKey
response[i].KeyVersion = keyVersion
}
}
// Generate the response
resp := &logical.Response{}
if batchInputRaw != nil {
resp.Data = map[string]interface{}{
"batch_results": response,
}
} else {
if response[0].Error != "" || response[0].err != nil {
p.Unlock()
if response[0].Error != "" {
return logical.ErrorResponse(response[0].Error), response[0].err
}
return nil, response[0].err
}
resp.Data = map[string]interface{}{
"signature": response[0].Signature,
"key_version": response[0].KeyVersion,
}
if len(response[0].PublicKey) > 0 {
resp.Data["public_key"] = response[0].PublicKey
}
}
p.Unlock()
return resp, nil
}
func (b *backend) pathVerifyWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
batchInputRaw := d.Raw["batch_input"]
var batchInputItems []batchRequestVerifyItem
if batchInputRaw != nil {
err := mapstructure.Decode(batchInputRaw, &batchInputItems)
if err != nil {
return nil, errwrap.Wrapf("failed to parse batch input: {{err}}", err)
}
if len(batchInputItems) == 0 {
return logical.ErrorResponse("missing batch input to process"), logical.ErrInvalidRequest
}
} else {
// use empty string if input is missing - not an error
inputB64 := d.Get("input").(string)
batchInputItems = make([]batchRequestVerifyItem, 1)
batchInputItems[0] = batchRequestVerifyItem{
"input": inputB64,
}
if sig, ok := d.GetOk("signature"); ok {
batchInputItems[0]["signature"] = sig.(string)
}
}
// For simplicity, 'signature' and 'hmac' cannot be mixed across batch_input elements.
// If one batch_input item is 'signature', they all must be 'signature'.
// If one batch_input item is 'hmac', they all must be 'hmac'.
sigFound := false
missing := false
for _, v := range batchInputItems {
if _, ok := v["signature"]; ok {
sigFound = true
} else {
missing = true
}
}
switch {
case batchInputRaw == nil && !sigFound:
return logical.ErrorResponse("no 'signature' was given to verify"), logical.ErrInvalidRequest
case missing && sigFound:
return logical.ErrorResponse("some elements of batch_input are missing 'signature'"), logical.ErrInvalidRequest
case missing:
return logical.ErrorResponse("no batch_input elements have 'signature'"), logical.ErrInvalidRequest
}
name := d.Get("name").(string)
marshalingStr := d.Get("marshaling_algorithm").(string)
marshaling, ok := keysutil.MarshalingTypeMap[marshalingStr]
if !ok {
return logical.ErrorResponse(fmt.Sprintf("invalid marshaling type %q", marshalingStr)), logical.ErrInvalidRequest
}
prehashed := d.Get("prehashed").(bool)
// Get the policy
p, _, err := b.GetPolicy(ctx, PolicyRequest{
Storage: req.Storage,
Name: name,
}, b.GetRandomReader())
if err != nil {
return nil, err
}
if p == nil {
return logical.ErrorResponse("encryption key not found"), logical.ErrInvalidRequest
}
if !b.System().CachingDisabled() {
p.Lock(false)
}
if !p.Type.SigningSupported() {
p.Unlock()
return logical.ErrorResponse(fmt.Sprintf("key type %v does not support verification", p.Type)), logical.ErrInvalidRequest
}
response := make([]batchResponseVerifyItem, len(batchInputItems))
for i, item := range batchInputItems {
rawInput, ok := item["input"]
if !ok {
response[i].Error = "missing input"
response[i].err = logical.ErrInvalidRequest
continue
}
input, err := base64.StdEncoding.DecodeString(rawInput)
if err != nil {
response[i].Error = fmt.Sprintf("unable to decode input as base64: %s", err)
response[i].err = logical.ErrInvalidRequest
continue
}
sig, ok := item["signature"]
if !ok {
response[i].Error = "missing signature"
response[i].err = logical.ErrInvalidRequest
continue
}
if p.Type.HashSignatureInput() && !prehashed {
hf := sm3.New()
hf.Write(input)
input = hf.Sum(nil)
}
valid, err := p.VerifySignature(input, marshaling, sig)
if err != nil {
switch err.(type) {
case errutil.UserError:
response[i].Error = err.Error()
response[i].err = logical.ErrInvalidRequest
default:
if batchInputRaw != nil {
response[i].Error = err.Error()
}
response[i].err = err
}
} else {
response[i].Valid = valid
}
}
// Generate the response
resp := &logical.Response{}
if batchInputRaw != nil {
resp.Data = map[string]interface{}{
"batch_results": response,
}
} else {
if response[0].Error != "" || response[0].err != nil {
p.Unlock()
if response[0].Error != "" {
return logical.ErrorResponse(response[0].Error), response[0].err
}
return nil, response[0].err
}
resp.Data = map[string]interface{}{
"valid": response[0].Valid,
}
}
p.Unlock()
return resp, nil
}
const pathSignHelpSyn = `Generate a signature for input data using the named key`
const pathSignHelpDesc = `
Generates a signature of the input data using the named key and SM3 hash algorithm.
`
const pathVerifyHelpSyn = `Verify a signature or HMAC for input data created using the named key`
const pathVerifyHelpDesc = `
Verifies a signature or HMAC of the input data using the named key and SM3 hash algorithm.
`