-
Notifications
You must be signed in to change notification settings - Fork 14
/
key_store.go
263 lines (216 loc) · 6.2 KB
/
key_store.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
// Copyright 2022 Dimitrij Drus <dadrus@gmx.de>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package keystore
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"os"
"github.com/youmark/pkcs8"
"github.com/dadrus/heimdall/internal/heimdall"
"github.com/dadrus/heimdall/internal/x/errorchain"
"github.com/dadrus/heimdall/internal/x/pkix"
"github.com/dadrus/heimdall/internal/x/stringx"
)
const (
pemBlockTypeEncryptedPrivateKey = "ENCRYPTED PRIVATE KEY"
pemBlockTypePrivateKey = "PRIVATE KEY"
pemBlockTypeECPrivateKey = "EC PRIVATE KEY"
pemBlockTypeRSAPrivateKey = "RSA PRIVATE KEY"
pemBlockTypeCertificate = "CERTIFICATE"
AlgRSA = "RSA"
AlgECDSA = "ECDSA"
)
var ErrNoSuchKey = errors.New("no such key")
type KeyStore interface {
GetKey(id string) (*Entry, error)
Entries() []*Entry
}
type keyStore []*Entry
func (ks keyStore) GetKey(id string) (*Entry, error) {
for _, entry := range ks {
if entry.KeyID == id {
return entry, nil
}
}
return nil, errorchain.NewWithMessagef(ErrNoSuchKey, "%s", id)
}
func (ks keyStore) Entries() []*Entry {
return ks
}
func NewKeyStoreFromKey(privateKey crypto.Signer) (KeyStore, error) {
entry, err := createEntry(privateKey, "")
if err != nil {
return nil, err
}
return verifyAndBuildKeyStore([]*Entry{entry}, nil)
}
func NewKeyStoreFromPEMFile(pemFilePath, password string) (KeyStore, error) {
fInfo, err := os.Stat(pemFilePath)
if err != nil {
return nil, errorchain.NewWithMessagef(heimdall.ErrConfiguration,
"failed to get information about %s", pemFilePath).CausedBy(err)
}
if fInfo.IsDir() {
return nil, errorchain.NewWithMessagef(heimdall.ErrConfiguration, "'%s' is not a file", pemFilePath)
}
contents, err := os.ReadFile(pemFilePath)
if err != nil {
return nil, errorchain.NewWithMessagef(heimdall.ErrConfiguration,
"failed to read %s", pemFilePath).CausedBy(err)
}
return NewKeyStoreFromPEMBytes(contents, password)
}
func NewKeyStoreFromPEMBytes(pemBytes []byte, password string) (KeyStore, error) {
return createKeyStore(readPEMContents(pemBytes), password)
}
func createKeyStore(blocks []*pem.Block, password string) (keyStore, error) {
var (
entries []*Entry
certs []*x509.Certificate
)
for idx, block := range blocks {
var (
cert *x509.Certificate
key any
err error
)
switch block.Type {
case pemBlockTypeEncryptedPrivateKey:
// PKCS#8 (PKCS#5 (v2.0) algorithms)
key, err = pkcs8.ParsePKCS8PrivateKey(block.Bytes, stringx.ToBytes(password))
case pemBlockTypePrivateKey:
// PKCS#8 - unencrypted
key, err = x509.ParsePKCS8PrivateKey(block.Bytes)
case pemBlockTypeECPrivateKey:
// PKCS#1 - unencrypted
key, err = x509.ParseECPrivateKey(block.Bytes)
case pemBlockTypeRSAPrivateKey:
// PKCS#1 - unencrypted
key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
case pemBlockTypeCertificate:
cert, err = x509.ParseCertificate(block.Bytes)
default:
return nil, errorchain.NewWithMessagef(heimdall.ErrInternal,
"unsupported entry '%s' entry in the pem file", block.Type)
}
if err != nil {
return nil, errorchain.NewWithMessagef(heimdall.ErrInternal,
"failed to parse %d entry in the pem file", idx).CausedBy(err)
}
if cert != nil {
certs = append(certs, cert)
} else {
entry, err := createEntry(key, block.Headers["X-Key-ID"])
if err != nil {
return nil, err
}
entries = append(entries, entry)
}
}
return verifyAndBuildKeyStore(entries, certs)
}
func verifyAndBuildKeyStore(entries []*Entry, certs []*x509.Certificate) (keyStore, error) {
known := make(map[string]bool)
for idx, entry := range entries {
chain := FindChain(entry.PrivateKey.Public(), certs)
if len(chain) != 0 {
if err := ValidateChain(chain); err != nil {
return nil, err
}
}
if len(entry.KeyID) == 0 {
kid, err := generateKeyID(chain, entry)
if err != nil {
return nil, errorchain.NewWithMessagef(heimdall.ErrInternal,
"failed generating kid for %d entry", idx+1).CausedBy(err)
}
entry.KeyID = kid
}
if _, ok := known[entry.KeyID]; ok {
return nil, errorchain.NewWithMessagef(heimdall.ErrConfiguration,
"duplicate entry for key_id=%s found", entry.KeyID)
}
known[entry.KeyID] = true
entry.CertChain = chain
}
return entries, nil
}
func generateKeyID(chain []*x509.Certificate, entry *Entry) (string, error) {
var (
keyID []byte
err error
)
if len(chain) != 0 {
// use subject key identifier from certificate (if present)
keyID = chain[0].SubjectKeyId
}
// if certificate did not have subject key identifier set
// calculate subject key identifier and use it
if len(keyID) == 0 {
keyID, err = pkix.SubjectKeyID(entry.PrivateKey.Public())
if err != nil {
return "", err
}
}
return hex.EncodeToString(keyID), nil
}
func readPEMContents(data []byte) []*pem.Block {
var (
blocks []*pem.Block
block *pem.Block
)
next := data
for {
block, next = pem.Decode(next)
blocks = append(blocks, block)
if len(next) == 0 {
break
}
}
return blocks
}
func createEntry(key any, keyID string) (*Entry, error) {
var (
sigKey crypto.Signer
algorithm string
size int
)
switch typedKey := key.(type) {
case *rsa.PrivateKey:
const bitsInByte = 8
algorithm = AlgRSA
sigKey = typedKey
size = typedKey.Size() * bitsInByte
case *ecdsa.PrivateKey:
algorithm = AlgECDSA
sigKey = typedKey
size = typedKey.Params().BitSize
default:
return nil, errorchain.NewWithMessage(heimdall.ErrInternal,
"unsupported key type; only rsa and ecdsa keys are supported")
}
return &Entry{
KeyID: keyID,
Alg: algorithm,
KeySize: size,
PrivateKey: sigKey,
}, nil
}