-
Notifications
You must be signed in to change notification settings - Fork 0
/
utility.go
104 lines (94 loc) · 2.44 KB
/
utility.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
package talisman
import (
"crypto/tls"
"github.com/bouwerp/log"
"time"
)
type QuickGenerateConfig struct {
Host string
AdminEmail string
ValidityPeriod time.Duration
CertDir string
KeySize int
}
// QuickGenerateCerts utilises the self-signed certificate generator and certificate manager to generate
// TLS certificates and check whether they already exist, or whether they expired.
// This method uses a default certs directory and an expiry of 180 days.
func QuickGenerateCerts(conf *QuickGenerateConfig) (*tls.Certificate, error) {
var host, certBasePath, adminEmail string
var validityPeriod time.Duration
var keySize int
if conf != nil {
host = conf.Host
certBasePath = conf.CertDir
adminEmail = conf.AdminEmail
validityPeriod = conf.ValidityPeriod
keySize = conf.KeySize
}
if host == "" {
host = "localhost"
}
if certBasePath == "" {
certBasePath = "./certs"
}
if adminEmail == "" {
adminEmail = "admin@" + host
}
if validityPeriod == 0 {
validityPeriod = 180 * 24 * time.Hour
}
if keySize == 0 {
keySize = 2048
}
// self-signed certificate generator
certGen := SelfSignedCertificateGenerator{
CertificateBasePath: certBasePath,
CertificateValidity: validityPeriod,
}
// certificate manager
certMan := DefaultCertificateManager{
CertificateBasePath: certBasePath,
}
var keyPath, certPath string
generateResponse, err := certGen.Generate(GenerateRequest{
CommonName: host,
AdminEmail: adminEmail,
Algorithm: RSA,
KeySize: keySize,
})
if err != nil {
switch err.(type) {
case CertificateExistsErr:
inspectResponse, err := certMan.Inspect(InspectRequest{CommonName: host})
if err != nil {
return nil, err
}
if inspectResponse.Expiry.Before(time.Now()) || inspectResponse.Expiry.Equal(time.Now()) {
log.Debug("certificate for", host, "has expired")
// renew
} else if inspectResponse.Expiry.After(time.Now().Add(-7*24*time.Hour)) &&
inspectResponse.Expiry.Before(time.Now()) {
log.Debug("certificate for", host, "is expiring soon")
// renew
}
keyPath = inspectResponse.KeyPath
certPath = inspectResponse.CertPath
default:
return nil, err
}
} else {
keyPath = generateResponse.KeyPath
certPath = generateResponse.CertPath
}
c, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
return &c, err
}
var Verbose bool
func DebugVerbose(msg interface{}) {
if Verbose {
log.Debug(msg)
}
}