-
Notifications
You must be signed in to change notification settings - Fork 37
/
keystore.go
365 lines (289 loc) · 9.26 KB
/
keystore.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
package keystore
import (
"bytes"
"crypto/rand"
"crypto/sha1"
"errors"
"fmt"
"io"
"sort"
"strings"
"time"
)
var (
ErrEntryNotFound = errors.New("entry not found")
ErrWrongEntryType = errors.New("wrong entry type")
ErrEmptyPrivateKey = errors.New("empty private key")
ErrEmptyCertificateType = errors.New("empty certificate type")
ErrEmptyCertificateContent = errors.New("empty certificate content")
ErrShortPassword = errors.New("short password")
)
// KeyStore is a mapping of alias to pointer to PrivateKeyEntry or TrustedCertificateEntry.
type KeyStore struct {
m map[string]interface{}
r io.Reader
ordered bool
caseExact bool
minPasswordLen int
}
// PrivateKeyEntry is an entry for private keys and associated certificates.
type PrivateKeyEntry struct {
CreationTime time.Time
PrivateKey []byte
CertificateChain []Certificate
}
// TrustedCertificateEntry is an entry for certificates only.
type TrustedCertificateEntry struct {
CreationTime time.Time
Certificate Certificate
}
// Certificate describes type of certificate.
type Certificate struct {
Type string
Content []byte
}
type Option func(store *KeyStore)
// WithOrderedAliases sets ordered option to true. Order aliases alphabetically.
func WithOrderedAliases() Option {
return func(ks *KeyStore) { ks.ordered = true }
}
// WithCaseExactAliases sets caseExact option to true. Preserves original case of aliases.
func WithCaseExactAliases() Option {
return func(ks *KeyStore) { ks.caseExact = true }
}
// WithMinPasswordLen sets minPasswordLen option to minPasswordLen argument value.
func WithMinPasswordLen(minPasswordLen int) Option {
return func(ks *KeyStore) { ks.minPasswordLen = minPasswordLen }
}
// WithCustomRandomNumberGenerator sets a random generator used to generate salt when encrypting private keys.
func WithCustomRandomNumberGenerator(r io.Reader) Option {
return func(ks *KeyStore) { ks.r = r }
}
// New returns new initialized instance of the KeyStore.
func New(options ...Option) KeyStore {
ks := KeyStore{
m: make(map[string]interface{}),
r: rand.Reader,
}
for _, option := range options {
option(&ks)
}
return ks
}
// Store signs keystore using password and writes its representation into w
// It is strongly recommended to fill password slice with zero after usage.
func (ks KeyStore) Store(w io.Writer, password []byte) error {
if len(password) < ks.minPasswordLen {
return fmt.Errorf("password must be at least %d characters: %w", ks.minPasswordLen, ErrShortPassword)
}
e := encoder{
w: w,
h: sha1.New(),
}
passwordBytes := passwordBytes(password)
defer zeroing(passwordBytes)
if _, err := e.h.Write(passwordBytes); err != nil {
return fmt.Errorf("update digest with password: %w", err)
}
if _, err := e.h.Write(whitenerMessage); err != nil {
return fmt.Errorf("update digest with whitener message: %w", err)
}
if err := e.writeUint32(magic); err != nil {
return fmt.Errorf("write magic: %w", err)
}
// always write latest version
if err := e.writeUint32(version02); err != nil {
return fmt.Errorf("write version: %w", err)
}
if err := e.writeUint32(uint32(len(ks.m))); err != nil { //nolint:gosec
return fmt.Errorf("write number of entries: %w", err)
}
for _, alias := range ks.Aliases() {
switch typedEntry := ks.m[alias].(type) {
case PrivateKeyEntry:
if err := e.writePrivateKeyEntry(alias, typedEntry); err != nil {
return fmt.Errorf("write private key entry: %w", err)
}
case TrustedCertificateEntry:
if err := e.writeTrustedCertificateEntry(alias, typedEntry); err != nil {
return fmt.Errorf("write trusted certificate entry: %w", err)
}
default:
return errors.New("got invalid entry")
}
}
if err := e.writeBytes(e.h.Sum(nil)); err != nil {
return fmt.Errorf("write digest: %w", err)
}
return nil
}
// Load reads keystore representation from r and checks its signature.
// It is strongly recommended to fill password slice with zero after usage.
func (ks KeyStore) Load(r io.Reader, password []byte) error {
d := decoder{
r: r,
h: sha1.New(),
}
passwordBytes := passwordBytes(password)
defer zeroing(passwordBytes)
if _, err := d.h.Write(passwordBytes); err != nil {
return fmt.Errorf("update digest with password: %w", err)
}
if _, err := d.h.Write(whitenerMessage); err != nil {
return fmt.Errorf("update digest with whitener message: %w", err)
}
readMagic, err := d.readUint32()
if err != nil {
return fmt.Errorf("read magic: %w", err)
}
if readMagic != magic {
return errors.New("got invalid magic")
}
version, err := d.readUint32()
if err != nil {
return fmt.Errorf("read version: %w", err)
}
entryNum, err := d.readUint32()
if err != nil {
return fmt.Errorf("read number of entries: %w", err)
}
for i := range entryNum {
alias, entry, err := d.readEntry(version)
if err != nil {
return fmt.Errorf("read %d entry: %w", i, err)
}
ks.m[alias] = entry
}
computedDigest := d.h.Sum(nil)
actualDigest, err := d.readBytes(uint32(d.h.Size())) //nolint:gosec
if err != nil {
return fmt.Errorf("read digest: %w", err)
}
if !bytes.Equal(actualDigest, computedDigest) {
return errors.New("got invalid digest")
}
return nil
}
// SetPrivateKeyEntry adds PrivateKeyEntry into keystore by alias encrypted with password.
// It is strongly recommended to fill password slice with zero after usage.
func (ks KeyStore) SetPrivateKeyEntry(alias string, entry PrivateKeyEntry, password []byte) error {
if err := entry.validate(); err != nil {
return fmt.Errorf("validate private key entry: %w", err)
}
if len(password) < ks.minPasswordLen {
return fmt.Errorf("password must be at least %d characters: %w", ks.minPasswordLen, ErrShortPassword)
}
epk, err := encrypt(ks.r, entry.PrivateKey, password)
if err != nil {
return fmt.Errorf("encrypt private key: %w", err)
}
entry.PrivateKey = epk
ks.m[ks.convertAlias(alias)] = entry
return nil
}
// GetPrivateKeyEntry returns PrivateKeyEntry from the keystore by the alias decrypted with the password.
// It is strongly recommended to fill password slice with zero after usage.
func (ks KeyStore) GetPrivateKeyEntry(alias string, password []byte) (PrivateKeyEntry, error) {
e, ok := ks.m[ks.convertAlias(alias)]
if !ok {
return PrivateKeyEntry{}, ErrEntryNotFound
}
pke, ok := e.(PrivateKeyEntry)
if !ok {
return PrivateKeyEntry{}, ErrWrongEntryType
}
dpk, err := decrypt(pke.PrivateKey, password)
if err != nil {
return PrivateKeyEntry{}, fmt.Errorf("decrypt private key: %w", err)
}
pke.PrivateKey = dpk
return pke, nil
}
// GetPrivateKeyEntryCertificateChain returns certificate chain associated with
// PrivateKeyEntry from the keystore by the alias.
func (ks KeyStore) GetPrivateKeyEntryCertificateChain(alias string) ([]Certificate, error) {
e, ok := ks.m[ks.convertAlias(alias)]
if !ok {
return nil, ErrEntryNotFound
}
pke, ok := e.(PrivateKeyEntry)
if !ok {
return nil, ErrWrongEntryType
}
return pke.CertificateChain, nil
}
// IsPrivateKeyEntry returns true if the keystore has PrivateKeyEntry by the alias.
func (ks KeyStore) IsPrivateKeyEntry(alias string) bool {
_, ok := ks.m[ks.convertAlias(alias)].(PrivateKeyEntry)
return ok
}
// SetTrustedCertificateEntry adds TrustedCertificateEntry into keystore by alias.
func (ks KeyStore) SetTrustedCertificateEntry(alias string, entry TrustedCertificateEntry) error {
if err := entry.validate(); err != nil {
return fmt.Errorf("validate trusted certificate entry: %w", err)
}
ks.m[ks.convertAlias(alias)] = entry
return nil
}
// GetTrustedCertificateEntry returns TrustedCertificateEntry from the keystore by the alias.
func (ks KeyStore) GetTrustedCertificateEntry(alias string) (TrustedCertificateEntry, error) {
e, ok := ks.m[ks.convertAlias(alias)]
if !ok {
return TrustedCertificateEntry{}, ErrEntryNotFound
}
tce, ok := e.(TrustedCertificateEntry)
if !ok {
return TrustedCertificateEntry{}, ErrWrongEntryType
}
return tce, nil
}
// IsTrustedCertificateEntry returns true if the keystore has TrustedCertificateEntry by the alias.
func (ks KeyStore) IsTrustedCertificateEntry(alias string) bool {
_, ok := ks.m[ks.convertAlias(alias)].(TrustedCertificateEntry)
return ok
}
// DeleteEntry deletes entry from the keystore.
func (ks KeyStore) DeleteEntry(alias string) {
delete(ks.m, ks.convertAlias(alias))
}
// Aliases returns slice of all aliases from the keystore.
// Aliases returns slice of all aliases sorted alphabetically if keystore created using WithOrderedAliases option.
func (ks KeyStore) Aliases() []string {
as := make([]string, 0, len(ks.m))
for a := range ks.m {
as = append(as, a)
}
if ks.ordered {
sort.Strings(as)
}
return as
}
func (ks KeyStore) convertAlias(alias string) string {
if ks.caseExact {
return alias
}
return strings.ToLower(alias)
}
func (e PrivateKeyEntry) validate() error {
if len(e.PrivateKey) == 0 {
return ErrEmptyPrivateKey
}
for i, c := range e.CertificateChain {
if err := c.validate(); err != nil {
return fmt.Errorf("validate certificate %d in chain: %w", i, err)
}
}
return nil
}
func (e TrustedCertificateEntry) validate() error {
return e.Certificate.validate()
}
func (c Certificate) validate() error {
if len(c.Type) == 0 {
return ErrEmptyCertificateType
}
if len(c.Content) == 0 {
return ErrEmptyCertificateContent
}
return nil
}