forked from getlantern/keyman
-
Notifications
You must be signed in to change notification settings - Fork 1
/
keyman.go
439 lines (392 loc) · 13 KB
/
keyman.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
// Package keyman provides convenience APIs around Go's built-in crypto APIs.
package keyman
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"net"
"os"
"time"
"github.com/getlantern/golog"
)
const (
PEM_HEADER_PRIVATE_KEY = "RSA PRIVATE KEY"
PEM_HEADER_PUBLIC_KEY = "RSA PRIVATE KEY"
PEM_HEADER_CERTIFICATE = "CERTIFICATE"
)
var (
log = golog.LoggerFor("keyman")
tenYearsFromToday = time.Now().AddDate(10, 0, 0)
)
// PrivateKey is a convenience wrapper for rsa.PrivateKey
type PrivateKey struct {
rsaKey *rsa.PrivateKey
}
// Certificate is a convenience wrapper for x509.Certificate
type Certificate struct {
cert *x509.Certificate
derBytes []byte
}
/*******************************************************************************
* Private Key Functions
******************************************************************************/
// GeneratePK generates a PrivateKey with a specified size in bits.
func GeneratePK(bits int) (key *PrivateKey, err error) {
var rsaKey *rsa.PrivateKey
rsaKey, err = rsa.GenerateKey(rand.Reader, bits)
if err == nil {
key = &PrivateKey{rsaKey: rsaKey}
}
return
}
// LoadPKFromFile loads a PEM-encoded PrivateKey from a file
func LoadPKFromFile(filename string) (key *PrivateKey, err error) {
privateKeyData, err := ioutil.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("Unable to read private key file from file %s: %s", filename, err)
}
block, _ := pem.Decode(privateKeyData)
if block == nil {
return nil, fmt.Errorf("Unable to decode PEM encoded private key data: %s", err)
}
rsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("Unable to decode X509 private key data: %s", err)
}
return &PrivateKey{rsaKey: rsaKey}, nil
}
// RSA() returns the RSA key underlying this PrivateKey
func (key *PrivateKey) RSA() *rsa.PrivateKey {
return key.rsaKey
}
// PEMEncoded encodes the PrivateKey in PEM
func (key *PrivateKey) PEMEncoded() (pemBytes []byte) {
return pem.EncodeToMemory(key.pemBlock())
}
// WriteToFile writes the PEM-encoded PrivateKey to the given file
func (key *PrivateKey) WriteToFile(filename string) (err error) {
keyOut, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("Failed to open %s for writing: %s", filename, err)
}
if err := pem.Encode(keyOut, key.pemBlock()); err != nil {
return fmt.Errorf("Unable to PEM encode private key: %s", err)
}
if err := keyOut.Close(); err != nil {
log.Debugf("Unable to close file: %v", err)
}
return
}
func (key *PrivateKey) pemBlock() *pem.Block {
return &pem.Block{Type: PEM_HEADER_PRIVATE_KEY, Bytes: x509.MarshalPKCS1PrivateKey(key.rsaKey)}
}
/*******************************************************************************
* Certificate Functions
******************************************************************************/
/*
Certificate() generates a certificate for the Public Key of the given PrivateKey
based on the given template and signed by the given issuer. If issuer is nil,
the generated certificate is self-signed.
*/
func (key *PrivateKey) Certificate(template *x509.Certificate, issuer *Certificate) (*Certificate, error) {
return key.CertificateForKey(template, issuer, &key.rsaKey.PublicKey)
}
/*
CertificateForKey() generates a certificate for the given Public Key based on
the given template and signed by the given issuer. If issuer is nil, the
generated certificate is self-signed.
*/
func (key *PrivateKey) CertificateForKey(template *x509.Certificate, issuer *Certificate, publicKey interface{}) (*Certificate, error) {
var issuerCert *x509.Certificate
if issuer == nil {
// Note - for self-signed certificates, we include the host's external IP address
issuerCert = template
} else {
issuerCert = issuer.cert
}
derBytes, err := x509.CreateCertificate(
rand.Reader, // secure entropy
template, // the template for the new cert
issuerCert, // cert that's signing this cert
publicKey, // public key
key.rsaKey, // private key
)
if err != nil {
return nil, err
}
return bytesToCert(derBytes)
}
// TLSCertificateFor generates a certificate useful for TLS use based on the
// given parameters. These certs are usable for key encipherment and digital
// signatures.
//
// organization: the org name for the cert.
// host: used as the hostname for the cert. If host is an IP
// address, it is also added as an IP SAN.
// commonName: used as the common name for the cert.
// validUntil: time at which certificate expires
// isCA: whether or not this cert is a CA
// issuer: the certificate which is issuing the new cert. If nil, the
// new cert will be a self-signed CA certificate.
//
func (key *PrivateKey) TLSCertificateFor(
organization string,
host string,
commonName string,
validUntil time.Time,
isCA bool,
issuer *Certificate) (cert *Certificate, err error) {
template := &x509.Certificate{
SerialNumber: new(big.Int).SetInt64(int64(time.Now().UnixNano())),
Subject: pkix.Name{
Organization: []string{organization},
CommonName: commonName,
},
NotBefore: time.Now().AddDate(0, -1, 0),
NotAfter: validUntil,
BasicConstraintsValid: true,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
}
// If host is an ip address, add it as an IP SAN
ip := net.ParseIP(host)
if ip != nil {
template.IPAddresses = []net.IP{ip}
}
isSelfSigned := issuer == nil
if isSelfSigned {
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}
}
// If it's a CA, add certificate signing
if isCA {
template.KeyUsage = template.KeyUsage | x509.KeyUsageCertSign
template.IsCA = true
}
cert, err = key.Certificate(template, issuer)
return
}
// LoadCertificateFromFile loads a Certificate from a PEM-encoded file
func LoadCertificateFromFile(filename string) (*Certificate, error) {
certificateData, err := ioutil.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return nil, err
}
return nil, fmt.Errorf("Unable to read certificate file from disk: %s", err)
}
return LoadCertificateFromPEMBytes(certificateData)
}
// LoadCertificateFromPEMBytes loads a Certificate from a byte array in PEM
// format
func LoadCertificateFromPEMBytes(pemBytes []byte) (*Certificate, error) {
block, _ := pem.Decode(pemBytes)
if block == nil {
return nil, fmt.Errorf("Unable to decode PEM encoded certificate")
}
return bytesToCert(block.Bytes)
}
// LoadCertificateFromX509 loads a Certificate from an x509.Certificate
func LoadCertificateFromX509(cert *x509.Certificate) (*Certificate, error) {
pemBytes := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Headers: nil,
Bytes: cert.Raw,
})
return LoadCertificateFromPEMBytes(pemBytes)
}
// X509 returns the x509 certificate underlying this Certificate
func (cert *Certificate) X509() *x509.Certificate {
return cert.cert
}
// DER returns the der encoded bytes for this Certificate
func (cert *Certificate) DER() []byte {
return cert.derBytes
}
// PEMEncoded encodes the Certificate in PEM
func (cert *Certificate) PEMEncoded() (pemBytes []byte) {
return pem.EncodeToMemory(cert.pemBlock())
}
// WriteToFile writes the PEM-encoded Certificate to a file.
func (cert *Certificate) WriteToFile(filename string) (err error) {
certOut, err := os.Create(filename)
if err != nil {
return fmt.Errorf("Failed to open %s for writing: %s", filename, err)
}
defer func() {
if err := certOut.Close(); err != nil {
log.Debugf("Unable to close file: %v", err)
}
}()
return pem.Encode(certOut, cert.pemBlock())
}
func (cert *Certificate) WriteToTempFile() (name string, err error) {
// Create a temp file containing the certificate
tempFile, err := ioutil.TempFile("", "tempCert")
if err != nil {
return "", fmt.Errorf("Unable to create temp file: %s", err)
}
name = tempFile.Name()
err = cert.WriteToFile(name)
if err != nil {
return "", fmt.Errorf("Unable to save certificate to temp file: %s", err)
}
return
}
// WriteToDERFile writes the DER-encoded Certificate to a file.
func (cert *Certificate) WriteToDERFile(filename string) (err error) {
certOut, err := os.Create(filename)
if err != nil {
return fmt.Errorf("Failed to open %s for writing: %s", filename, err)
}
defer func() {
if err := certOut.Close(); err != nil {
log.Debugf("Unable to close file: %v", err)
}
}()
_, err = certOut.Write(cert.derBytes)
return err
}
// PoolContainingCert creates a pool containing this cert.
func (cert *Certificate) PoolContainingCert() *x509.CertPool {
pool := x509.NewCertPool()
pool.AddCert(cert.cert)
return pool
}
// PoolContainingCerts constructs a CertPool containing all of the given certs
// (PEM encoded).
func PoolContainingCerts(certs ...string) (*x509.CertPool, error) {
pool := x509.NewCertPool()
for _, cert := range certs {
c, err := LoadCertificateFromPEMBytes([]byte(cert))
if err != nil {
return nil, err
}
pool.AddCert(c.cert)
}
return pool, nil
}
func (cert *Certificate) ExpiresBefore(time time.Time) bool {
return cert.cert.NotAfter.Before(time)
}
func bytesToCert(derBytes []byte) (*Certificate, error) {
cert, err := x509.ParseCertificate(derBytes)
if err != nil {
return nil, err
}
return &Certificate{cert, derBytes}, nil
}
func (cert *Certificate) pemBlock() *pem.Block {
return &pem.Block{Type: PEM_HEADER_CERTIFICATE, Bytes: cert.derBytes}
}
/*******************************************************************************
* Utility Functions
******************************************************************************/
// StoredPKAndCert returns a PK and certificate for the given host, storing
// these at the given pkfile and certfile paths and using the stored values on
// subsequence calls.
func StoredPKAndCert(pkfile string, certfile string, organization string, host string, commonName string) (*PrivateKey, *Certificate, error) {
pk, err := LoadPKFromFile(pkfile)
if err != nil {
if os.IsNotExist(err) {
log.Debugf("Creating new PK at: %s", pkfile)
pk, err = GeneratePK(2048)
if err != nil {
return nil, nil, err
}
err = pk.WriteToFile(pkfile)
if err != nil {
return nil, nil, fmt.Errorf("Unable to save private key: %s", err)
}
} else {
return nil, nil, fmt.Errorf("Unable to read private key, even though it exists: %s", err)
}
}
cert, err := LoadCertificateFromFile(certfile)
if err != nil {
if os.IsNotExist(err) {
log.Debugf("Creating new server cert at: %s", certfile)
cert, err = pk.TLSCertificateFor(organization, host, commonName, tenYearsFromToday, true, nil)
if err != nil {
return nil, nil, err
}
err = cert.WriteToFile(certfile)
if err != nil {
return nil, nil, fmt.Errorf("Unable to save certificate: %s", err)
}
} else {
return nil, nil, fmt.Errorf("Unable to read certificate, even though it exists: %s", err)
}
}
return pk, cert, nil
}
// KeyPairFor creates a key pair for the given host, pkfile and certfile. If
// either pkfile or certfile is missing, default files will be created.
func KeyPairFor(host, commonName, pkfile, certfile string) (tls.Certificate, error) {
mypkfile := pkfile
if mypkfile == "" {
mypkfile = "key.pem"
}
mycertfile := certfile
if mycertfile == "" {
mycertfile = "cert.pem"
}
ctx := certContext{
PKFile: mypkfile,
ServerCertFile: mycertfile,
}
_, err1 := os.Stat(ctx.ServerCertFile)
_, err2 := os.Stat(ctx.PKFile)
if os.IsNotExist(err1) || os.IsNotExist(err2) {
fmt.Println("At least one of the Key/Cert files is not found -> Generating new key pair")
err := ctx.initPKAndCert(host, commonName)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Unable to init server cert: %s\n", err)
}
}
cert, err := tls.LoadX509KeyPair(ctx.ServerCertFile, ctx.PKFile)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Unable to load certificate and key from %s and %s: %s\n", ctx.ServerCertFile, ctx.PKFile, err)
}
return cert, err
}
// certContext encapsulates the certificates used by a Server
type certContext struct {
PKFile string
ServerCertFile string
PK *PrivateKey
ServerCert *Certificate
}
// initPKAndCert initializes a PK + cert, creating them if necessary.
func (ctx *certContext) initPKAndCert(host string, commonName string) (err error) {
if ctx.PK, err = LoadPKFromFile(ctx.PKFile); err != nil {
if os.IsNotExist(err) {
fmt.Printf("Creating new PK at: %s\n", ctx.PKFile)
if ctx.PK, err = GeneratePK(2048); err != nil {
return
}
if err = ctx.PK.WriteToFile(ctx.PKFile); err != nil {
return fmt.Errorf("Unable to save private key: %s\n", err)
}
} else {
return fmt.Errorf("Unable to read private key, even though it exists: %s\n", err)
}
}
fmt.Printf("Creating new cert for host %v at: %s\n", host, ctx.ServerCertFile)
ctx.ServerCert, err = ctx.PK.TLSCertificateFor("Lantern", host, commonName, tenYearsFromToday, true, nil)
if err != nil {
return
}
err = ctx.ServerCert.WriteToFile(ctx.ServerCertFile)
if err != nil {
return
}
return nil
}