-
Notifications
You must be signed in to change notification settings - Fork 210
/
key_pair_manager.go
311 lines (256 loc) · 8.45 KB
/
key_pair_manager.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
package utils
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
"net"
"os"
"time"
"go.step.sm/crypto/pemutil"
types "github.com/akash-network/akash-api/go/node/cert/v1beta3"
sdkclient "github.com/cosmos/cosmos-sdk/client"
sdk "github.com/cosmos/cosmos-sdk/types"
certerrors "github.com/akash-network/node/x/cert/errors"
)
var (
errCertificateNotFoundInPEM = fmt.Errorf("%w: certificate not found in PEM", certerrors.ErrCertificate)
errPrivateKeyNotFoundInPEM = fmt.Errorf("%w: private key not found in PEM", certerrors.ErrCertificate)
errPublicKeyNotFoundInPEM = fmt.Errorf("%w: public key not found in PEM", certerrors.ErrCertificate)
errUnsupportedEncryptedPEM = errors.New("unsupported encrypted PEM")
)
type KeyPairManager interface {
KeyExists() (bool, error)
Generate(notBefore, notAfter time.Time, domains []string) error
// Read the PEM blocks, containing the cert, private key, & public key
Read(fin ...io.Reader) ([]byte, []byte, []byte, error)
ReadX509KeyPair(fin ...io.Reader) (*x509.Certificate, tls.Certificate, error)
}
type keyPairManager struct {
addr sdk.AccAddress
passwordBytes []byte
passwordLegacy []byte
homeDir string
}
func NewKeyPairManager(cctx sdkclient.Context, fromAddress sdk.AccAddress) (KeyPairManager, error) {
sig, _, err := cctx.Keyring.SignByAddress(fromAddress, []byte(fromAddress.String()))
if err != nil {
return nil, err
}
// ignore error if ledger device is being used
// due to its jsonparser not liking bech address sent as data in binary format
// if test or file keyring used it will allow to decode old private keys for the mTLS cert
sigLegacy, _, _ := cctx.Keyring.SignByAddress(fromAddress, fromAddress.Bytes())
return &keyPairManager{
addr: fromAddress,
passwordBytes: sig,
passwordLegacy: sigLegacy,
homeDir: cctx.HomeDir,
}, nil
}
func (kpm *keyPairManager) getKeyPath() string {
return kpm.homeDir + "/" + kpm.addr.String() + ".pem"
}
func (kpm *keyPairManager) ReadX509KeyPair(fin ...io.Reader) (*x509.Certificate, tls.Certificate, error) {
certData, privKeyData, _, err := kpm.Read(fin...)
if err != nil {
return nil, tls.Certificate{}, err
}
x509cert, err := x509.ParseCertificate(certData)
if err != nil {
return nil, tls.Certificate{}, fmt.Errorf("could not parse x509 cert: %w", err)
}
result := tls.Certificate{
Certificate: [][]byte{certData},
}
result.PrivateKey, err = x509.ParsePKCS8PrivateKey(privKeyData)
if err != nil {
return nil, tls.Certificate{}, fmt.Errorf("%w: failed parsing private key data", err)
}
return x509cert, result, err
}
func (kpm *keyPairManager) KeyExists() (bool, error) {
_, err := os.Stat(kpm.getKeyPath())
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func (kpm *keyPairManager) Generate(notBefore, notAfter time.Time, domains []string) error {
var err error
var pemOut *os.File
if pemOut, err = os.OpenFile(kpm.getKeyPath(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600); err != nil {
return err
}
err = kpm.generateImpl(notBefore, notAfter, domains, pemOut)
closeErr := pemOut.Close()
if closeErr != nil {
return closeErr
}
return err
}
func (kpm *keyPairManager) generateImpl(notBefore, notAfter time.Time, domains []string, fout io.Writer) error {
var err error
// Generate the private key
var priv *ecdsa.PrivateKey
if priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader); err != nil {
return fmt.Errorf("could not generate key: %w", err)
}
serialNumber := new(big.Int).SetInt64(time.Now().UTC().UnixNano())
extKeyUsage := []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
}
if len(domains) != 0 {
extKeyUsage = append(extKeyUsage, x509.ExtKeyUsageServerAuth)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: kpm.addr.String(),
ExtraNames: []pkix.AttributeTypeAndValue{
{
Type: AuthVersionOID,
Value: "v0.0.1",
},
},
},
Issuer: pkix.Name{
CommonName: kpm.addr.String(),
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageDataEncipherment | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: extKeyUsage,
BasicConstraintsValid: true,
}
var ips []net.IP
for i := len(domains) - 1; i >= 0; i-- {
if ip := net.ParseIP(domains[i]); ip != nil {
ips = append(ips, ip)
domains = append(domains[:i], domains[i+1:]...)
}
}
if len(domains) != 0 || len(ips) != 0 {
template.PermittedDNSDomainsCritical = true
template.PermittedDNSDomains = domains
template.DNSNames = domains
template.IPAddresses = ips
}
var certDer []byte
if certDer, err = x509.CreateCertificate(rand.Reader, &template, &template, priv.Public(), priv); err != nil {
return fmt.Errorf("could not create certificate: %w", err)
}
var keyDer []byte
if keyDer, err = x509.MarshalPKCS8PrivateKey(priv); err != nil {
return fmt.Errorf("could not create private key: %w", err)
}
var blk *pem.Block
blk, err = pemutil.EncryptPKCS8PrivateKey(rand.Reader, keyDer, kpm.passwordBytes, x509.PEMCipherAES256)
if err != nil {
return fmt.Errorf("could not encrypt private key as PEM: %w", err)
}
// Write the certificate
if err = pem.Encode(fout, &pem.Block{Type: types.PemBlkTypeCertificate, Bytes: certDer}); err != nil {
return fmt.Errorf("could not encode certificate as PEM: %w", err)
}
// Write the encrypted private key
if err = pem.Encode(fout, blk); err != nil {
return fmt.Errorf("could not encode private key as PEM: %w", err)
}
return nil
}
func (kpm *keyPairManager) Read(fin ...io.Reader) ([]byte, []byte, []byte, error) {
var pemIn io.Reader
var closeMe io.ReadCloser
if len(fin) != 0 {
if len(fin) != 1 {
return nil, nil, nil, fmt.Errorf("%w: Read() takes exactly 1 or 0 arguments, not %d", certerrors.ErrCertificate, len(fin))
}
pemIn = fin[0]
}
if pemIn == nil {
fopen, err := os.OpenFile(kpm.getKeyPath(), os.O_RDONLY, 0x0)
if err != nil {
return nil, nil, nil, fmt.Errorf("could not open certificate PEM file: %w", err)
}
closeMe = fopen
pemIn = fopen
}
cert, privKey, pubKey, err := kpm.readImpl(pemIn)
if closeMe != nil {
closeErr := closeMe.Close()
if closeErr != nil {
return nil, nil, nil, fmt.Errorf("could not close PEM file: %w", closeErr)
}
}
return cert, privKey, pubKey, err
}
func (kpm *keyPairManager) readImpl(fin io.Reader) ([]byte, []byte, []byte, error) {
buf := &bytes.Buffer{}
_, err := io.Copy(buf, fin)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed reading certificate PEM file: %w", err)
}
data := buf.Bytes()
// Read certificate
block, remaining := pem.Decode(data)
if block == nil {
return nil, nil, nil, errCertificateNotFoundInPEM
}
cert := block.Bytes
// Read private key
block, _ = pem.Decode(remaining)
if block == nil {
return nil, nil, nil, errPrivateKeyNotFoundInPEM
}
var privKeyPlaintext []byte
var privKeyI interface{}
// PKCS#8 header defined in RFC7468 section 11
// nolint: gocritic
if block.Type == "ENCRYPTED PRIVATE KEY" {
privKeyPlaintext, err = pemutil.DecryptPKCS8PrivateKey(block.Bytes, kpm.passwordBytes)
} else if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
// nolint: staticcheck
privKeyPlaintext, _ = x509.DecryptPEMBlock(block, kpm.passwordBytes)
// DecryptPEMBlock may not return IncorrectPasswordError.
// Try parse private key instead and if it fails give another try with legacy password
privKeyI, err = x509.ParsePKCS8PrivateKey(privKeyPlaintext)
if err != nil {
// nolint: staticcheck
privKeyPlaintext, err = x509.DecryptPEMBlock(block, kpm.passwordLegacy)
}
} else {
return nil, nil, nil, errUnsupportedEncryptedPEM
}
if err != nil {
return nil, nil, nil, fmt.Errorf("%w: failed decrypting x509 block with private key", err)
}
if privKeyI == nil {
if privKeyI, err = x509.ParsePKCS8PrivateKey(privKeyPlaintext); err != nil {
return nil, nil, nil, fmt.Errorf("%w: failed parsing private key data", err)
}
}
eckey, valid := privKeyI.(*ecdsa.PrivateKey)
if !valid {
return nil, nil, nil, fmt.Errorf("%w: unexpected private key type, expected %T but got %T",
errPublicKeyNotFoundInPEM,
&ecdsa.PrivateKey{},
privKeyI)
}
var pubKey []byte
if pubKey, err = x509.MarshalPKIXPublicKey(eckey.Public()); err != nil {
return nil, nil, nil, fmt.Errorf("%w: failed extracting public key", err)
}
return cert, privKeyPlaintext, pubKey, nil
}