forked from mothership/rds-auth-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cert.go
93 lines (82 loc) · 2.13 KB
/
cert.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
package cert
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"strings"
"time"
"github.com/JacobJohansen/rds-auth-proxy/pkg/file"
)
// GenerateSelfSignedCert creates a self signed RSA cert and returns it
// along with the private key or any errors that occurred while generating
// it.
func GenerateSelfSignedCert(host string, isCA bool) ([]byte, []byte, error) {
notBefore := time.Now()
// 5 years later
notAfter := notBefore.Add(5 * 365 * 24 * time.Hour)
var priv *rsa.PrivateKey
var err error
priv, err = rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, err
}
template := x509.Certificate{
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Mothership"},
},
}
hosts := strings.Split(host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
if isCA {
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
}
certBytes, err := x509.CreateCertificate(
rand.Reader,
&template,
&template,
&priv.PublicKey,
priv,
)
if err != nil {
return nil, nil, err
}
pemKeyBytes := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv),
},
)
pemCertBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
return pemCertBytes, pemKeyBytes, err
}
// Save saves a file to disk
func Save(path string, pemBytes []byte) error {
fileWriter := file.NewFileWriter()
_, err := fileWriter.Write(pemBytes)
if err != nil {
return err
}
return fileWriter.Save(path)
}