forked from kubernetes/kops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ca.go
374 lines (314 loc) · 9.2 KB
/
ca.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
package fi
import (
"bytes"
"crypto"
crypto_rand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/golang/glog"
"io"
"k8s.io/kops/util/pkg/vfs"
"math/big"
"time"
)
const CertificateId_CA = "ca"
type Certificate struct {
Subject pkix.Name
IsCA bool
Certificate *x509.Certificate
PublicKey crypto.PublicKey
}
const (
SecretTypeSSHPublicKey = "SSHPublicKey"
SecretTypeKeypair = "Keypair"
SecretTypeSecret = "Secret"
// Name for the primary SSH key
SecretNameSSHPrimary = "admin"
)
type KeystoreItem struct {
Type string
Name string
Id string
Data []byte
}
func (c *Certificate) UnmarshalJSON(b []byte) error {
s := ""
if err := json.Unmarshal(b, &s); err == nil {
r, err := LoadPEMCertificate([]byte(s))
if err != nil {
// Alternative form: Check if base64 encoded
// TODO: Do we need this? I think we need this only on nodeup, but maybe we could just not base64-it?
d, err2 := base64.StdEncoding.DecodeString(s)
if err2 == nil {
r2, err2 := LoadPEMCertificate(d)
if err2 == nil {
glog.Warningf("used base64 decode of certificate")
r = r2
err = nil
}
}
if err != nil {
glog.Infof("Invalid certificate data: %q", string(b))
return fmt.Errorf("error parsing certificate: %v", err)
}
}
*c = *r
return nil
}
return fmt.Errorf("unknown format for Certificate: %q", string(b))
}
func (c *Certificate) MarshalJSON() ([]byte, error) {
var data bytes.Buffer
_, err := c.WriteTo(&data)
if err != nil {
return nil, fmt.Errorf("error writing SSL certificate: %v", err)
}
return json.Marshal(data.String())
}
type CAStore interface {
// Cert returns the primary specified certificate
Cert(name string) (*Certificate, error)
// CertificatePool returns all active certificates with the specified id
CertificatePool(name string) (*CertificatePool, error)
PrivateKey(name string) (*PrivateKey, error)
FindCert(name string) (*Certificate, error)
FindPrivateKey(name string) (*PrivateKey, error)
//IssueCert(id string, privateKey *PrivateKey, template *x509.Certificate) (*Certificate, error)
//CreatePrivateKey(id string) (*PrivateKey, error)
CreateKeypair(name string, template *x509.Certificate) (*Certificate, *PrivateKey, error)
// List will list all the items, but will not fetch the data
List() ([]*KeystoreItem, error)
// VFSPath returns the path where the CAStore is stored
VFSPath() vfs.Path
// AddCert adds an alternative certificate to the pool (primarily useful for CAs)
AddCert(name string, cert *Certificate) error
// AddSSHPublicKey adds an SSH public key
AddSSHPublicKey(name string, data []byte) error
// FindSSHPublicKeys retrieves the SSH public keys with the specific name
FindSSHPublicKeys(name string) ([]*KeystoreItem, error)
// DeleteSecret will delete the specified item
DeleteSecret(item *KeystoreItem) error
}
func (c *Certificate) AsString() (string, error) {
// Nicer behaviour because this is called from templates
if c == nil {
return "", fmt.Errorf("AsString called on nil Certificate")
}
var data bytes.Buffer
_, err := c.WriteTo(&data)
if err != nil {
return "", fmt.Errorf("error writing SSL certificate: %v", err)
}
return data.String(), nil
}
type PrivateKey struct {
Key crypto.PrivateKey
}
func (c *PrivateKey) AsString() (string, error) {
// Nicer behaviour because this is called from templates
if c == nil {
return "", fmt.Errorf("AsString called on nil Certificate")
}
var data bytes.Buffer
_, err := c.WriteTo(&data)
if err != nil {
return "", fmt.Errorf("error writing SSL private key: %v", err)
}
return data.String(), nil
}
func (k *PrivateKey) UnmarshalJSON(b []byte) (err error) {
s := ""
if err := json.Unmarshal(b, &s); err == nil {
r, err := parsePEMPrivateKey([]byte(s))
if err != nil {
// Alternative form: Check if base64 encoded
// TODO: Do we need this? I think we need this only on nodeup, but maybe we could just not base64-it?
d, err2 := base64.StdEncoding.DecodeString(s)
if err2 == nil {
r2, err2 := parsePEMPrivateKey(d)
if err2 == nil {
glog.Warningf("used base64 decode of PrivateKey")
r = r2
err = nil
}
}
if err != nil {
return fmt.Errorf("error parsing private key: %v", err)
}
}
k.Key = r
return nil
}
return fmt.Errorf("unknown format for private key: %q", string(b))
}
func (k *PrivateKey) MarshalJSON() ([]byte, error) {
var data bytes.Buffer
_, err := k.WriteTo(&data)
if err != nil {
return nil, fmt.Errorf("error writing SSL private key: %v", err)
}
return json.Marshal(data.String())
}
var _ io.WriterTo = &PrivateKey{}
func (k *PrivateKey) WriteTo(w io.Writer) (int64, error) {
if k.Key == nil {
// For the dry-run case
return 0, nil
}
var data bytes.Buffer
var err error
switch pk := k.Key.(type) {
case *rsa.PrivateKey:
err = pem.Encode(w, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(pk)})
default:
return 0, fmt.Errorf("unknown private key type: %T", k.Key)
}
if err != nil {
return 0, fmt.Errorf("error writing SSL private key: %v", err)
}
return data.WriteTo(w)
}
func LoadPEMCertificate(pemData []byte) (*Certificate, error) {
cert, err := parsePEMCertificate(pemData)
if err != nil {
return nil, err
}
c := &Certificate{
Subject: cert.Subject,
Certificate: cert,
PublicKey: cert.PublicKey,
IsCA: cert.IsCA,
}
return c, nil
}
func SignNewCertificate(privateKey *PrivateKey, template *x509.Certificate, signer *x509.Certificate, signerPrivateKey *PrivateKey) (*Certificate, error) {
if template.PublicKey == nil {
rsaPrivateKey, ok := privateKey.Key.(*rsa.PrivateKey)
if ok {
template.PublicKey = rsaPrivateKey.Public()
}
}
if template.PublicKey == nil {
return nil, fmt.Errorf("PublicKey not set, and cannot be determined from %T", privateKey)
}
now := time.Now()
if template.NotBefore.IsZero() {
template.NotBefore = now.Add(time.Hour * -48)
}
if template.NotAfter.IsZero() {
template.NotAfter = now.Add(time.Hour * 10 * 365 * 24)
}
if template.SerialNumber == nil {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := crypto_rand.Int(crypto_rand.Reader, serialNumberLimit)
if err != nil {
return nil, fmt.Errorf("error generating certificate serial number: %s", err)
}
template.SerialNumber = serialNumber
}
var parent *x509.Certificate
if signer != nil {
parent = signer
} else {
parent = template
signerPrivateKey = privateKey
}
if template.KeyUsage == 0 {
template.KeyUsage = x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment
}
if template.ExtKeyUsage == nil {
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
}
//c.SignatureAlgorithm = do we want to overrride?
certificateData, err := x509.CreateCertificate(crypto_rand.Reader, template, parent, template.PublicKey, signerPrivateKey.Key)
if err != nil {
return nil, fmt.Errorf("error creating certificate: %v", err)
}
c := &Certificate{}
c.PublicKey = template.PublicKey
cert, err := x509.ParseCertificate(certificateData)
if err != nil {
return nil, fmt.Errorf("error parsing certificate: %v", err)
}
c.Certificate = cert
return c, nil
}
var _ io.WriterTo = &Certificate{}
func (c *Certificate) WriteTo(w io.Writer) (int64, error) {
// For the dry-run case
if c.Certificate == nil {
return 0, nil
}
var b bytes.Buffer
err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: c.Certificate.Raw})
if err != nil {
return 0, err
}
return b.WriteTo(w)
}
func parsePEMCertificate(pemData []byte) (*x509.Certificate, error) {
for {
block, rest := pem.Decode(pemData)
if block == nil {
return nil, fmt.Errorf("could not parse certificate")
}
if block.Type == "CERTIFICATE" {
glog.V(8).Infof("Parsing pem block: %q", block.Type)
return x509.ParseCertificate(block.Bytes)
} else {
glog.Infof("Ignoring unexpected PEM block: %q", block.Type)
}
pemData = rest
}
}
func parsePEMPrivateKey(pemData []byte) (crypto.PrivateKey, error) {
for {
block, rest := pem.Decode(pemData)
if block == nil {
return nil, fmt.Errorf("could not parse private key")
}
if block.Type == "RSA PRIVATE KEY" {
glog.V(8).Infof("Parsing pem block: %q", block.Type)
return x509.ParsePKCS1PrivateKey(block.Bytes)
} else if block.Type == "PRIVATE KEY" {
glog.V(8).Infof("Parsing pem block: %q", block.Type)
k, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return k.(crypto.PrivateKey), nil
} else {
glog.Infof("Ignoring unexpected PEM block: %q", block.Type)
}
pemData = rest
}
}
type CertificatePool struct {
Secondary []*Certificate
Primary *Certificate
}
func (c *CertificatePool) AsString() (string, error) {
// Nicer behaviour because this is called from templates
if c == nil {
return "", fmt.Errorf("AsString called on nil CertificatePool")
}
var data bytes.Buffer
if c.Primary != nil {
_, err := c.Primary.WriteTo(&data)
if err != nil {
return "", fmt.Errorf("error writing SSL certificate: %v", err)
}
}
for _, cert := range c.Secondary {
_, err := cert.WriteTo(&data)
if err != nil {
return "", fmt.Errorf("error writing SSL certificate: %v", err)
}
}
return data.String(), nil
}