-
Notifications
You must be signed in to change notification settings - Fork 0
/
certstore.go
100 lines (79 loc) · 2.19 KB
/
certstore.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
package awsmocker
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"math"
"math/big"
"net"
"sync"
"time"
)
var (
globalCertStore *CertStorage
leafCertStart = time.Unix(time.Now().Unix()-2592000, 0) // 2592000 = 30 day
leafCertEnd = time.Unix(time.Now().Unix()+31536000, 0)
)
type CertStorage struct {
certs sync.Map
mu sync.Mutex
nextSerial int64
privateKey *rsa.PrivateKey
}
func (tcs *CertStorage) Fetch(hostname string) *tls.Certificate {
icert, ok := tcs.certs.Load(hostname)
if ok {
cert := icert.(tls.Certificate)
return &cert
}
return tcs.generateCert(hostname)
}
func (tcs *CertStorage) generateCert(hostname string) *tls.Certificate {
tcs.mu.Lock()
defer tcs.mu.Unlock()
tcs.nextSerial += 1
caCert := CACert()
template := x509.Certificate{
SerialNumber: big.NewInt(tcs.nextSerial),
Issuer: caCert.Subject,
Subject: pkix.Name{
Country: []string{"US"},
Organization: []string{"webdestroya"},
OrganizationalUnit: []string{"awsmocker fake leaf"},
},
NotBefore: leafCertStart,
NotAfter: leafCertEnd,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
if ip := net.ParseIP(hostname); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, hostname)
template.Subject.CommonName = hostname
}
var derBytes []byte
var err error
if derBytes, err = x509.CreateCertificate(rand.Reader, &template, caCert, tcs.privateKey.Public(), caKeyPair.PrivateKey); err != nil {
panic("could not generate cert")
}
newCert := tls.Certificate{
Certificate: [][]byte{derBytes, caKeyPair.Certificate[0]},
PrivateKey: tcs.privateKey,
}
val, _ := tcs.certs.LoadOrStore(hostname, newCert)
val2 := (val).(tls.Certificate)
return &val2
}
func init() {
privKey, _ := rsa.GenerateKey(rand.Reader, 2048)
startSerial, _ := rand.Int(rand.Reader, big.NewInt(int64(math.Pow(2, 40))))
globalCertStore = &CertStorage{
certs: sync.Map{},
privateKey: privKey,
nextSerial: startSerial.Int64(),
}
}