-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
253 lines (211 loc) · 5.96 KB
/
main.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
package main
import (
"context"
"log"
"os"
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"net/http"
"time"
"github.com/ericchiang/k8s"
"github.com/ericchiang/k8s/api/v1"
metav1 "github.com/ericchiang/k8s/apis/meta/v1"
"github.com/xenolf/lego/acme"
"github.com/xenolf/lego/providers/dns"
"gopkg.in/yaml.v2"
)
const (
DefaultConfigSecret = "letsencrypt"
DefaultNamespace = "default"
DefaultInterval = "1h"
DefaultProvider = "route53"
DefaultEndpoint = "https://acme-v01.api.letsencrypt.org/directory"
)
func GetEnv(key, defaultVal string) string {
if os.Getenv(key) == "" {
return defaultVal
}
return os.Getenv(key)
}
type Config struct {
Account struct {
Email string `yaml:"email"`
Key string `yaml:"key"`
} `yaml:"account"`
Certificates []struct {
Domains []string `yaml:"domains"`
Secret string `yaml:"secret"`
} `yaml:"certificates"`
}
func NewConfig(client *k8s.Client, namespace, secret string) (*Config, error) {
config, err := client.CoreV1().GetSecret(context.TODO(), secret, namespace)
if err != nil {
return nil, err
}
var c Config
err = yaml.Unmarshal(config.GetData()["config.yaml"], &c)
if err != nil {
return nil, err
}
return &c, nil
}
type AcmeUser struct {
Email string
Registration *acme.RegistrationResource
Key crypto.PrivateKey
}
func (u AcmeUser) GetEmail() string {
return u.Email
}
func (u AcmeUser) GetRegistration() *acme.RegistrationResource {
return u.Registration
}
func (u AcmeUser) GetPrivateKey() crypto.PrivateKey {
return u.Key
}
func ParseRsaKey(pemIn string) (*rsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(pemIn))
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return priv, nil
}
func ParseCertificateFromPEM(inPem []byte) (*x509.Certificate, error) {
block, _ := pem.Decode([]byte(inPem))
if block == nil {
return nil, errors.New("Unable to decode pem from byte array")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return cert, nil
}
func main() {
// get our environment config
namespace := GetEnv("NAMESPACE", DefaultNamespace)
secret := GetEnv("CONFIG_SECRET", DefaultConfigSecret)
endpoint := GetEnv("ACME_ENDPOINT", DefaultEndpoint)
provider := GetEnv("PROVIDER", DefaultProvider)
intervalStr := GetEnv("INTERVAL", DefaultInterval)
interval, err := time.ParseDuration(intervalStr)
if err != nil {
log.Fatal(err)
}
// Get a new incluster client
client, err := k8s.NewInClusterClient()
if err != nil {
log.Fatal(err)
}
// parse our yaml config, from Secret
config, err := NewConfig(client, namespace, secret)
if err != nil {
log.Fatal(err)
}
for {
// for certificate in the config
for _, cert := range config.Certificates {
log.Println("Working on: ", cert.Domains)
// attempt to get an existing secret
existingCert, err := client.CoreV1().GetSecret(context.TODO(), cert.Secret, namespace)
var expiresIn float64
isNew := false
if apiErr, ok := err.(*k8s.APIError); ok {
// it wasn't found...
if apiErr.Code == http.StatusNotFound {
log.Println("Secret doesn't exist, brand new certificate")
expiresIn = 0
isNew = true
} else {
// some other error, need to abort
log.Fatal(err)
}
} else {
// it was found!
parsedCert, err := ParseCertificateFromPEM(existingCert.GetData()["tls.crt"])
if err != nil {
log.Fatal("Error decoding certificate: ", err)
}
// seconds until expiration
expiresIn = parsedCert.NotAfter.Sub(time.Now()).Seconds()
}
// check to see if we expire less than a month for now
if expiresIn >= 60*60*24*30*1 {
// This expires past our current window, no need to renew.
log.Println("Expires more than a month from now, all fine! continuing, expiresIn:", expiresIn)
continue
}
log.Println("Expires less than a month from now, renewing")
// get an AcmeUser
var user AcmeUser
user.Email = config.Account.Email
user.Key, err = ParseRsaKey(config.Account.Key)
if err != nil {
log.Fatal(err)
}
// new ACME client
var acme_client, errr = acme.NewClient(endpoint, &user, acme.RSA2048)
if errr != nil {
log.Fatal(err)
}
// exclude unused challenges, HTTP01 and TLSSNI01
acme_client.ExcludeChallenges([]acme.Challenge{acme.HTTP01, acme.TLSSNI01})
// attempt to register
reg, err := acme_client.Register()
if err != nil {
log.Fatal(err)
}
user.Registration = reg
// always agree to the TOS
err = acme_client.AgreeToTOS()
if err != nil {
log.Fatal(err)
}
// instantiates the route53 provider
challenge_provider, err := dns.NewDNSChallengeProviderByName(provider)
if err != nil {
log.Fatal(err)
}
// sets the route53 provider
acme_client.SetChallengeProvider(acme.DNS01, challenge_provider)
// obtain our certificates, automatically rolling in a new private key
certificates, failures := acme_client.ObtainCertificate(cert.Domains, true, nil, false)
// more than a single domain failed for some reason
if len(failures) > 0 {
log.Println("The following domains failed to verify, so we couldn't renew our certificate:")
log.Println(failures)
continue
}
// prepare our data
stringData := make(map[string]string)
stringData["tls.crt"] = string(certificates.Certificate[:])
stringData["tls.key"] = string(certificates.PrivateKey[:])
secretType := "tls"
tlsSecret := &v1.Secret{
Metadata: &metav1.ObjectMeta{
Name: &cert.Secret,
Namespace: &namespace,
},
StringData: stringData,
Type: &secretType,
}
// if it's new, create it, else update it.
if isNew {
_, err = client.CoreV1().CreateSecret(context.TODO(), tlsSecret)
} else {
_, err = client.CoreV1().UpdateSecret(context.TODO(), tlsSecret)
}
if err != nil {
log.Fatal(err)
}
}
time.Sleep(interval)
}
}