forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
518 lines (445 loc) · 13.6 KB
/
crypto.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package crypto
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"math/big"
"net"
"os"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/auth/user"
"k8s.io/kubernetes/pkg/util"
"github.com/openshift/origin/pkg/auth/authenticator/request/x509request"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
)
type TLSCertificateConfig struct {
Certs []*x509.Certificate
Key crypto.PrivateKey
}
type TLSCARoots struct {
Roots []*x509.Certificate
}
func (c *TLSCertificateConfig) writeCertConfig(certFile, keyFile string) error {
if err := writeCertificates(certFile, c.Certs...); err != nil {
return err
}
if err := writeKeyFile(keyFile, c.Key); err != nil {
return err
}
return nil
}
func (c *TLSCARoots) writeCARoots(rootFile string) error {
if err := writeCertificates(rootFile, c.Roots...); err != nil {
return err
}
return nil
}
func GetTLSCARoots(caFile string) (*TLSCARoots, error) {
if len(caFile) == 0 {
return nil, errors.New("caFile missing")
}
caPEMBlock, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
roots, err := cmdutil.CertificatesFromPEM(caPEMBlock)
if err != nil {
return nil, fmt.Errorf("Error reading %s: %s", caFile, err)
}
return &TLSCARoots{roots}, nil
}
func GetTLSCertificateConfig(certFile, keyFile string) (*TLSCertificateConfig, error) {
if len(certFile) == 0 {
return nil, errors.New("certFile missing")
}
if len(keyFile) == 0 {
return nil, errors.New("keyFile missing")
}
certPEMBlock, err := ioutil.ReadFile(certFile)
if err != nil {
return nil, err
}
certs, err := cmdutil.CertificatesFromPEM(certPEMBlock)
if err != nil {
return nil, fmt.Errorf("Error reading %s: %s", certFile, err)
}
keyPEMBlock, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, err
}
keyPairCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
if err != nil {
return nil, err
}
key := keyPairCert.PrivateKey
return &TLSCertificateConfig{certs, key}, nil
}
var (
// Default templates to last for a year
lifetime = time.Hour * 24 * 365
// Default keys are 2048 bits
keyBits = 2048
)
type CA struct {
SerialFile string
Config *TLSCertificateConfig
// lock guards access to the Serial field
lock sync.Mutex
Serial int64
}
// EnsureCA returns a CA, whether it was created (as opposed to pre-existing), and any error
func EnsureCA(certFile, keyFile, serialFile, name string) (*CA, bool, error) {
if ca, err := GetCA(certFile, keyFile, serialFile); err == nil {
return ca, false, err
}
ca, err := MakeCA(certFile, keyFile, serialFile, name)
return ca, true, err
}
func GetCA(certFile, keyFile, serialFile string) (*CA, error) {
caConfig, err := GetTLSCertificateConfig(certFile, keyFile)
if err != nil {
return nil, err
}
// read serial file
var serial int64
if serialData, err := ioutil.ReadFile(serialFile); err == nil {
serial, _ = strconv.ParseInt(string(serialData), 10, 64)
} else {
return nil, err
}
if serial < 1 {
serial = 1
}
return &CA{
Serial: serial,
SerialFile: serialFile,
Config: caConfig,
}, nil
}
func MakeCA(certFile, keyFile, serialFile, name string) (*CA, error) {
glog.V(2).Infof("Generating new CA for %s cert, and key in %s, %s", name, certFile, keyFile)
// Create CA cert
rootcaPublicKey, rootcaPrivateKey, err := NewKeyPair()
if err != nil {
return nil, err
}
rootcaTemplate, err := newSigningCertificateTemplate(pkix.Name{CommonName: name})
if err != nil {
return nil, err
}
rootcaCert, err := signCertificate(rootcaTemplate, rootcaPublicKey, rootcaTemplate, rootcaPrivateKey)
if err != nil {
return nil, err
}
caConfig := &TLSCertificateConfig{
Certs: []*x509.Certificate{rootcaCert},
Key: rootcaPrivateKey,
}
if err := caConfig.writeCertConfig(certFile, keyFile); err != nil {
return nil, err
}
if err := ioutil.WriteFile(serialFile, []byte("0"), 0644); err != nil {
return nil, err
}
return &CA{
Serial: 0,
SerialFile: serialFile,
Config: caConfig,
}, nil
}
func (ca *CA) EnsureServerCert(certFile, keyFile string, hostnames util.StringSet) (*TLSCertificateConfig, bool, error) {
certConfig, err := GetServerCert(certFile, keyFile, hostnames)
if err != nil {
certConfig, err = ca.MakeServerCert(certFile, keyFile, hostnames)
return certConfig, true, err
}
return certConfig, false, nil
}
func GetServerCert(certFile, keyFile string, hostnames util.StringSet) (*TLSCertificateConfig, error) {
server, err := GetTLSCertificateConfig(certFile, keyFile)
if err != nil {
return nil, err
}
cert := server.Certs[0]
ips, dns := IPAddressesDNSNames(hostnames.List())
missingIps := ipsNotInSlice(ips, cert.IPAddresses)
missingDns := stringsNotInSlice(dns, cert.DNSNames)
if len(missingIps) == 0 && len(missingDns) == 0 {
glog.V(4).Infof("Found existing server certificate in %s", certFile)
return server, nil
}
return nil, fmt.Errorf("Existing server certificate in %s was missing some hostnames (%v) or IP addresses (%v).", certFile, missingDns, missingIps)
}
func (ca *CA) MakeServerCert(certFile, keyFile string, hostnames util.StringSet) (*TLSCertificateConfig, error) {
glog.V(4).Infof("Generating server certificate in %s, key in %s", certFile, keyFile)
serverPublicKey, serverPrivateKey, _ := NewKeyPair()
serverTemplate, _ := newServerCertificateTemplate(pkix.Name{CommonName: hostnames.List()[0]}, hostnames.List())
serverCrt, _ := ca.signCertificate(serverTemplate, serverPublicKey)
server := &TLSCertificateConfig{
Certs: append([]*x509.Certificate{serverCrt}, ca.Config.Certs...),
Key: serverPrivateKey,
}
if err := server.writeCertConfig(certFile, keyFile); err != nil {
return server, err
}
return server, nil
}
func (ca *CA) EnsureClientCertificate(certFile, keyFile string, u user.Info) (*TLSCertificateConfig, bool, error) {
certConfig, err := GetTLSCertificateConfig(certFile, keyFile)
if err != nil {
certConfig, err = ca.MakeClientCertificate(certFile, keyFile, u)
return certConfig, true, err // true indicates we wrote the files.
}
return certConfig, false, nil
}
func (ca *CA) MakeClientCertificate(certFile, keyFile string, u user.Info) (*TLSCertificateConfig, error) {
glog.V(4).Infof("Generating client cert in %s and key in %s", certFile, keyFile)
// ensure parent dirs
if err := os.MkdirAll(filepath.Dir(certFile), os.FileMode(0755)); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(keyFile), os.FileMode(0755)); err != nil {
return nil, err
}
clientPublicKey, clientPrivateKey, _ := NewKeyPair()
clientTemplate, _ := newClientCertificateTemplate(x509request.UserToSubject(u))
clientCrt, _ := ca.signCertificate(clientTemplate, clientPublicKey)
certData, err := encodeCertificates(clientCrt)
if err != nil {
return nil, err
}
keyData, err := encodeKey(clientPrivateKey)
if err != nil {
return nil, err
}
if err = ioutil.WriteFile(certFile, certData, os.FileMode(0644)); err != nil {
return nil, err
}
if err = ioutil.WriteFile(keyFile, keyData, os.FileMode(0600)); err != nil {
return nil, err
}
return GetTLSCertificateConfig(certFile, keyFile)
}
// nextSerial returns a unique, monotonically increasing serial number and ensures the CA on
// disk records that value.
func (ca *CA) nextSerial() (int64, error) {
ca.lock.Lock()
defer ca.lock.Unlock()
next := ca.Serial + 1
ca.Serial = next
if err := ioutil.WriteFile(ca.SerialFile, []byte(fmt.Sprintf("%d", next)), os.FileMode(0640)); err != nil {
return 0, err
}
return next, nil
}
func (ca *CA) signCertificate(template *x509.Certificate, requestKey crypto.PublicKey) (*x509.Certificate, error) {
// Increment and persist serial
serial, err := ca.nextSerial()
if err != nil {
return nil, err
}
template.SerialNumber = big.NewInt(serial)
return signCertificate(template, requestKey, ca.Config.Certs[0], ca.Config.Key)
}
func NewKeyPair() (crypto.PublicKey, crypto.PrivateKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, keyBits)
if err != nil {
return nil, nil, err
}
return &privateKey.PublicKey, privateKey, nil
}
// Can be used for CA or intermediate signing certs
func newSigningCertificateTemplate(subject pkix.Name) (*x509.Certificate, error) {
return &x509.Certificate{
Subject: subject,
SignatureAlgorithm: x509.SHA256WithRSA,
NotBefore: time.Now().Add(-1 * time.Second),
NotAfter: time.Now().Add(lifetime),
SerialNumber: big.NewInt(1),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
}, nil
}
// Can be used for ListenAndServeTLS
func newServerCertificateTemplate(subject pkix.Name, hosts []string) (*x509.Certificate, error) {
template := &x509.Certificate{
Subject: subject,
SignatureAlgorithm: x509.SHA256WithRSA,
NotBefore: time.Now().Add(-1 * time.Second),
NotAfter: time.Now().Add(lifetime),
SerialNumber: big.NewInt(1),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
template.IPAddresses, template.DNSNames = IPAddressesDNSNames(hosts)
return template, nil
}
func IPAddressesDNSNames(hosts []string) ([]net.IP, []string) {
ips := []net.IP{}
dns := []string{}
for _, host := range hosts {
if ip := net.ParseIP(host); ip != nil {
ips = append(ips, ip)
} else {
dns = append(dns, host)
}
}
// Include IP addresses as DNS subjectAltNames in the cert as well, for the sake of Python, Windows (< 10), and unnamed other libraries
// Ensure these technically invalid DNS subjectAltNames occur after the valid ones, to avoid triggering cert errors in Firefox
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1148766
for _, ip := range ips {
dns = append(dns, ip.String())
}
return ips, dns
}
func CertsFromPEM(pemCerts []byte) ([]*x509.Certificate, error) {
ok := false
certs := []*x509.Certificate{}
for len(pemCerts) > 0 {
var block *pem.Block
block, pemCerts = pem.Decode(pemCerts)
if block == nil {
break
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return certs, err
}
certs = append(certs, cert)
ok = true
}
if !ok {
return certs, errors.New("Could not read any certificates")
}
return certs, nil
}
// Can be used as a certificate in http.Transport TLSClientConfig
func newClientCertificateTemplate(subject pkix.Name) (*x509.Certificate, error) {
return &x509.Certificate{
Subject: subject,
SignatureAlgorithm: x509.SHA256WithRSA,
NotBefore: time.Now().Add(-1 * time.Second),
NotAfter: time.Now().Add(lifetime),
SerialNumber: big.NewInt(1),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}, nil
}
func signCertificate(template *x509.Certificate, requestKey crypto.PublicKey, issuer *x509.Certificate, issuerKey crypto.PrivateKey) (*x509.Certificate, error) {
derBytes, err := x509.CreateCertificate(rand.Reader, template, issuer, requestKey, issuerKey)
if err != nil {
return nil, err
}
certs, err := x509.ParseCertificates(derBytes)
if err != nil {
return nil, err
}
if len(certs) != 1 {
return nil, errors.New("Expected a single certificate")
}
return certs[0], nil
}
func encodeCertificates(certs ...*x509.Certificate) ([]byte, error) {
b := bytes.Buffer{}
for _, cert := range certs {
if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}); err != nil {
return []byte{}, err
}
}
return b.Bytes(), nil
}
func encodeKey(key crypto.PrivateKey) ([]byte, error) {
b := bytes.Buffer{}
switch key := key.(type) {
case *ecdsa.PrivateKey:
keyBytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return []byte{}, err
}
if err := pem.Encode(&b, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil {
return b.Bytes(), err
}
case *rsa.PrivateKey:
if err := pem.Encode(&b, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}); err != nil {
return []byte{}, err
}
default:
return []byte{}, errors.New("Unrecognized key type")
}
return b.Bytes(), nil
}
func writeCertificates(path string, certs ...*x509.Certificate) error {
// ensure parent dir
if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil {
return err
}
bytes, err := encodeCertificates(certs...)
if err != nil {
return err
}
return ioutil.WriteFile(path, bytes, os.FileMode(0644))
}
func writeKeyFile(path string, key crypto.PrivateKey) error {
// ensure parent dir
if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil {
return err
}
b, err := encodeKey(key)
if err != nil {
return err
}
return ioutil.WriteFile(path, b, os.FileMode(0600))
}
func stringsNotInSlice(needles []string, haystack []string) []string {
missing := []string{}
for _, needle := range needles {
if !stringInSlice(needle, haystack) {
missing = append(missing, needle)
}
}
return missing
}
func stringInSlice(needle string, haystack []string) bool {
for _, straw := range haystack {
if needle == straw {
return true
}
}
return false
}
func ipsNotInSlice(needles []net.IP, haystack []net.IP) []net.IP {
missing := []net.IP{}
for _, needle := range needles {
if !ipInSlice(needle, haystack) {
missing = append(missing, needle)
}
}
return missing
}
func ipInSlice(needle net.IP, haystack []net.IP) bool {
for _, straw := range haystack {
if needle.Equal(straw) {
return true
}
}
return false
}