-
Notifications
You must be signed in to change notification settings - Fork 51
/
keylib.go
462 lines (414 loc) · 13.6 KB
/
keylib.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package in_toto
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/secure-systems-lab/go-securesystemslib/cjson"
)
// ErrFailedPEMParsing gets returned when PKCS1, PKCS8 or PKIX key parsing fails
var ErrFailedPEMParsing = errors.New("failed parsing the PEM block: unsupported PEM type")
// ErrNoPEMBlock gets triggered when there is no PEM block in the provided file
var ErrNoPEMBlock = errors.New("failed to decode the data as PEM block (are you sure this is a pem file?)")
// ErrUnsupportedKeyType is returned when we are dealing with a key type different to ed25519 or RSA
var ErrUnsupportedKeyType = errors.New("unsupported key type")
// ErrInvalidSignature is returned when the signature is invalid
var ErrInvalidSignature = errors.New("invalid signature")
// ErrInvalidKey is returned when a given key is none of RSA, ECDSA or ED25519
var ErrInvalidKey = errors.New("invalid key")
const (
rsaKeyType string = "rsa"
ecdsaKeyType string = "ecdsa"
ed25519KeyType string = "ed25519"
rsassapsssha256Scheme string = "rsassa-pss-sha256"
ecdsaSha2nistp224 string = "ecdsa-sha2-nistp224"
ecdsaSha2nistp256 string = "ecdsa-sha2-nistp256"
ecdsaSha2nistp384 string = "ecdsa-sha2-nistp384"
ecdsaSha2nistp521 string = "ecdsa-sha2-nistp521"
ed25519Scheme string = "ed25519"
pemPublicKey string = "PUBLIC KEY"
pemPrivateKey string = "PRIVATE KEY"
pemRSAPrivateKey string = "RSA PRIVATE KEY"
)
/*
getSupportedKeyIDHashAlgorithms returns a string slice of supported
KeyIDHashAlgorithms. We need to use this function instead of a constant,
because Go does not support global constant slices.
*/
func getSupportedKeyIDHashAlgorithms() Set {
return NewSet("sha256", "sha512")
}
/*
getSupportedRSASchemes returns a string slice of supported RSA Key schemes.
We need to use this function instead of a constant because Go does not support
global constant slices.
*/
func getSupportedRSASchemes() []string {
return []string{rsassapsssha256Scheme}
}
/*
getSupportedEcdsaSchemes returns a string slice of supported ecdsa Key schemes.
We need to use this function instead of a constant because Go does not support
global constant slices.
*/
func getSupportedEcdsaSchemes() []string {
return []string{ecdsaSha2nistp224, ecdsaSha2nistp256, ecdsaSha2nistp384, ecdsaSha2nistp521}
}
/*
getSupportedEd25519Schemes returns a string slice of supported ed25519 Key
schemes. We need to use this function instead of a constant because Go does
not support global constant slices.
*/
func getSupportedEd25519Schemes() []string {
return []string{ed25519Scheme}
}
/*
generateKeyID creates a partial key map and generates the key ID
based on the created partial key map via the SHA256 method.
The resulting keyID will be directly saved in the corresponding key object.
On success generateKeyID will return nil, in case of errors while encoding
there will be an error.
*/
func (k *Key) generateKeyID() error {
// Create partial key map used to create the keyid
// Unfortunately, we can't use the Key object because this also carries
// yet unwanted fields, such as KeyID and KeyVal.Private and therefore
// produces a different hash. We generate the keyID exactly as we do in
// the securesystemslib to keep interoperability between other in-toto
// implementations.
var keyToBeHashed = map[string]interface{}{
"keytype": k.KeyType,
"scheme": k.Scheme,
"keyid_hash_algorithms": k.KeyIDHashAlgorithms,
"keyval": map[string]string{
"public": k.KeyVal.Public,
},
}
keyCanonical, err := cjson.EncodeCanonical(keyToBeHashed)
if err != nil {
return err
}
// calculate sha256 and return string representation of keyID
keyHashed := sha256.Sum256(keyCanonical)
k.KeyID = fmt.Sprintf("%x", keyHashed)
err = validateKey(*k)
if err != nil {
return err
}
return nil
}
/*
generatePEMBlock creates a PEM block from scratch via the keyBytes and the pemType.
If successful it returns a PEM block as []byte slice. This function should always
succeed, if keyBytes is empty the PEM block will have an empty byte block.
Therefore only header and footer will exist.
*/
func generatePEMBlock(keyBytes []byte, pemType string) []byte {
// construct PEM block
pemBlock := &pem.Block{
Type: pemType,
Headers: nil,
Bytes: keyBytes,
}
return pem.EncodeToMemory(pemBlock)
}
/*
setKeyComponents sets all components in our key object.
Furthermore it makes sure to remove any trailing and leading whitespaces or newlines.
We treat key types differently for interoperability reasons to the in-toto python
implementation and the securesystemslib.
*/
func (k *Key) setKeyComponents(pubKeyBytes []byte, privateKeyBytes []byte, keyType string, scheme string, KeyIDHashAlgorithms []string) error {
// assume we have a privateKey if the key size is bigger than 0
switch keyType {
case rsaKeyType:
if len(privateKeyBytes) > 0 {
k.KeyVal = KeyVal{
Private: strings.TrimSpace(string(generatePEMBlock(privateKeyBytes, pemRSAPrivateKey))),
Public: strings.TrimSpace(string(generatePEMBlock(pubKeyBytes, pemPublicKey))),
}
} else {
k.KeyVal = KeyVal{
Public: strings.TrimSpace(string(generatePEMBlock(pubKeyBytes, pemPublicKey))),
}
}
case ecdsaKeyType:
if len(privateKeyBytes) > 0 {
k.KeyVal = KeyVal{
Private: strings.TrimSpace(string(generatePEMBlock(privateKeyBytes, pemPrivateKey))),
Public: strings.TrimSpace(string(generatePEMBlock(pubKeyBytes, pemPublicKey))),
}
} else {
k.KeyVal = KeyVal{
Public: strings.TrimSpace(string(generatePEMBlock(pubKeyBytes, pemPublicKey))),
}
}
case ed25519KeyType:
if len(privateKeyBytes) > 0 {
k.KeyVal = KeyVal{
Private: strings.TrimSpace(hex.EncodeToString(privateKeyBytes)),
Public: strings.TrimSpace(hex.EncodeToString(pubKeyBytes)),
}
} else {
k.KeyVal = KeyVal{
Public: strings.TrimSpace(hex.EncodeToString(pubKeyBytes)),
}
}
default:
return fmt.Errorf("%w: %s", ErrUnsupportedKeyType, keyType)
}
k.KeyType = keyType
k.Scheme = scheme
k.KeyIDHashAlgorithms = KeyIDHashAlgorithms
if err := k.generateKeyID(); err != nil {
return err
}
return nil
}
/*
parseKey tries to parse a PEM []byte slice. Using the following standards
in the given order:
- PKCS8
- PKCS1
- PKIX
On success it returns the parsed key and nil.
On failure it returns nil and the error ErrFailedPEMParsing
*/
func parseKey(data []byte) (interface{}, error) {
key, err := x509.ParsePKCS8PrivateKey(data)
if err == nil {
return key, nil
}
key, err = x509.ParsePKCS1PrivateKey(data)
if err == nil {
return key, nil
}
key, err = x509.ParsePKIXPublicKey(data)
if err == nil {
return key, nil
}
key, err = x509.ParseCertificate(data)
if err == nil {
return key, nil
}
key, err = x509.ParseECPrivateKey(data)
if err == nil {
return key, nil
}
return nil, ErrFailedPEMParsing
}
/*
decodeAndParse receives potential PEM bytes decodes them via pem.Decode
and pushes them to parseKey. If any error occurs during this process,
the function will return nil and an error (either ErrFailedPEMParsing
or ErrNoPEMBlock). On success it will return the decoded pemData, the
key object interface and nil as error. We need the decoded pemData,
because LoadKey relies on decoded pemData for operating system
interoperability.
*/
func decodeAndParse(pemBytes []byte) (*pem.Block, interface{}, error) {
// pem.Decode returns the parsed pem block and a rest.
// The rest is everything, that could not be parsed as PEM block.
// Therefore we can drop this via using the blank identifier "_"
data, _ := pem.Decode(pemBytes)
if data == nil {
return nil, nil, ErrNoPEMBlock
}
// Try to load private key, if this fails try to load
// key as public key
key, err := parseKey(data.Bytes)
if err != nil {
return nil, nil, err
}
return data, key, nil
}
/*
LoadKey loads the key file at specified file path into the key object.
It automatically derives the PEM type and the key type.
Right now the following PEM types are supported:
- PKCS1 for private keys
- PKCS8 for private keys
- PKIX for public keys
The following key types are supported and will be automatically assigned to
the key type field:
- ed25519
- rsa
- ecdsa
The following schemes are supported:
- ed25519 -> ed25519
- rsa -> rsassa-pss-sha256
- ecdsa -> ecdsa-sha256-nistp256
Note that, this behavior is consistent with the securesystemslib, except for
ecdsa. We do not use the scheme string as key type in in-toto-golang.
Instead we are going with a ecdsa/ecdsa-sha2-nistp256 pair.
On success it will return nil. The following errors can happen:
- path not found or not readable
- no PEM block in the loaded file
- no valid PKCS8/PKCS1 private key or PKIX public key
- errors while marshalling
- unsupported key types
*/
func (k *Key) LoadKey(path string, scheme string, KeyIDHashAlgorithms []string) error {
pemFile, err := os.Open(path)
if err != nil {
return err
}
defer pemFile.Close()
err = k.LoadKeyReader(pemFile, scheme, KeyIDHashAlgorithms)
if err != nil {
return err
}
return pemFile.Close()
}
func (k *Key) LoadKeyDefaults(path string) error {
pemFile, err := os.Open(path)
if err != nil {
return err
}
defer pemFile.Close()
err = k.LoadKeyReaderDefaults(pemFile)
if err != nil {
return err
}
return pemFile.Close()
}
// LoadKeyReader loads the key from a supplied reader. The logic matches LoadKey otherwise.
func (k *Key) LoadKeyReader(r io.Reader, scheme string, KeyIDHashAlgorithms []string) error {
if r == nil {
return ErrNoPEMBlock
}
// Read key bytes
pemBytes, err := io.ReadAll(r)
if err != nil {
return err
}
// decodeAndParse returns the pemData for later use
// and a parsed key object (for operations on that key, like extracting the public Key)
pemData, key, err := decodeAndParse(pemBytes)
if err != nil {
return err
}
return k.loadKey(key, pemData, scheme, KeyIDHashAlgorithms)
}
func (k *Key) LoadKeyReaderDefaults(r io.Reader) error {
if r == nil {
return ErrNoPEMBlock
}
// Read key bytes
pemBytes, err := io.ReadAll(r)
if err != nil {
return err
}
// decodeAndParse returns the pemData for later use
// and a parsed key object (for operations on that key, like extracting the public Key)
pemData, key, err := decodeAndParse(pemBytes)
if err != nil {
return err
}
scheme, keyIDHashAlgorithms, err := getDefaultKeyScheme(key)
if err != nil {
return err
}
return k.loadKey(key, pemData, scheme, keyIDHashAlgorithms)
}
func getDefaultKeyScheme(key interface{}) (scheme string, keyIDHashAlgorithms []string, err error) {
keyIDHashAlgorithms = []string{"sha256", "sha512"}
switch k := key.(type) {
case *rsa.PublicKey, *rsa.PrivateKey:
scheme = rsassapsssha256Scheme
case ed25519.PrivateKey, ed25519.PublicKey:
scheme = ed25519Scheme
case *ecdsa.PrivateKey, *ecdsa.PublicKey:
scheme = ecdsaSha2nistp256
case *x509.Certificate:
return getDefaultKeyScheme(k.PublicKey)
default:
err = ErrUnsupportedKeyType
}
return scheme, keyIDHashAlgorithms, err
}
func (k *Key) loadKey(keyObj interface{}, pemData *pem.Block, scheme string, keyIDHashAlgorithms []string) error {
switch key := keyObj.(type) {
case *rsa.PublicKey:
pubKeyBytes, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return err
}
if err := k.setKeyComponents(pubKeyBytes, []byte{}, rsaKeyType, scheme, keyIDHashAlgorithms); err != nil {
return err
}
case *rsa.PrivateKey:
// Note: RSA Public Keys will get stored as X.509 SubjectPublicKeyInfo (RFC5280)
// This behavior is consistent to the securesystemslib
pubKeyBytes, err := x509.MarshalPKIXPublicKey(key.Public())
if err != nil {
return err
}
if err := k.setKeyComponents(pubKeyBytes, pemData.Bytes, rsaKeyType, scheme, keyIDHashAlgorithms); err != nil {
return err
}
case ed25519.PublicKey:
if err := k.setKeyComponents(key, []byte{}, ed25519KeyType, scheme, keyIDHashAlgorithms); err != nil {
return err
}
case ed25519.PrivateKey:
pubKeyBytes := key.Public()
publicKey, ok := pubKeyBytes.(ed25519.PublicKey)
if !ok {
return fmt.Errorf("pubKeyBytes must be ed25519.PublicKey")
}
if err := k.setKeyComponents(publicKey, key, ed25519KeyType, scheme, keyIDHashAlgorithms); err != nil {
return err
}
case *ecdsa.PrivateKey:
pubKeyBytes, err := x509.MarshalPKIXPublicKey(key.Public())
if err != nil {
return err
}
if err := k.setKeyComponents(pubKeyBytes, pemData.Bytes, ecdsaKeyType, scheme, keyIDHashAlgorithms); err != nil {
return err
}
case *ecdsa.PublicKey:
pubKeyBytes, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return err
}
if err := k.setKeyComponents(pubKeyBytes, []byte{}, ecdsaKeyType, scheme, keyIDHashAlgorithms); err != nil {
return err
}
case *x509.Certificate:
err := k.loadKey(key.PublicKey, pemData, scheme, keyIDHashAlgorithms)
if err != nil {
return err
}
k.KeyVal.Certificate = string(pem.EncodeToMemory(pemData))
default:
// We should never get here, because we implement all from Go supported Key Types
return errors.New("unexpected Error in LoadKey function")
}
return nil
}
/*
VerifyCertificateTrust verifies that the certificate has a chain of trust
to a root in rootCertPool, possibly using any intermediates in
intermediateCertPool
*/
func VerifyCertificateTrust(cert *x509.Certificate, rootCertPool, intermediateCertPool *x509.CertPool) ([][]*x509.Certificate, error) {
verifyOptions := x509.VerifyOptions{
Roots: rootCertPool,
Intermediates: intermediateCertPool,
}
chains, err := cert.Verify(verifyOptions)
if len(chains) == 0 || err != nil {
return nil, fmt.Errorf("cert cannot be verified by provided roots and intermediates")
}
return chains, nil
}