forked from kelseyhightower/kube-cert-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dns.go
180 lines (161 loc) · 4.41 KB
/
dns.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
// Copyright 2016 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"log"
"net"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/miekg/dns"
)
type dnsClient struct {
domain string
provider string
secret string
secretKey string
}
func newDNSClient(provider, domain, secret, secretKey string) (*dnsClient, error) {
return &dnsClient{domain, provider, secret, secretKey}, nil
}
func envVar(key, value string) string {
return fmt.Sprintf("%s=%s", key, value)
}
func (c *dnsClient) createRecord(fqdn, value string, ttl int) error {
providerConfig, err := getDNSConfigFromSecret(c.secret, c.secretKey)
if err != nil {
return errors.New("Error getting dns config from secret" + err.Error())
}
env := []string{
envVar("APIVERSION", "v1"),
envVar("COMMAND", "CREATE"),
envVar("DOMAIN", c.domain),
envVar("FQDN", fqdn),
envVar("TOKEN", value),
}
cmd := &exec.Cmd{
Path: filepath.Join("/", c.provider),
Env: env,
Stdin: bytes.NewReader(providerConfig),
}
_, err = cmd.Output()
if err != nil {
exitError, ok := err.(*exec.ExitError)
if ok {
return errors.New(string(exitError.Stderr))
}
return err
}
return nil
}
func (c *dnsClient) deleteRecord(fqdn, value string, ttl int) error {
providerConfig, err := getDNSConfigFromSecret(c.secret, c.secretKey)
if err != nil {
return errors.New("Error getting dns config from secret" + err.Error())
}
env := []string{
envVar("APIVERSION", "v1"),
envVar("COMMAND", "DELETE"),
envVar("DOMAIN", c.domain),
envVar("FQDN", fqdn),
envVar("TOKEN", value),
}
cmd := &exec.Cmd{
Path: filepath.Join("/", c.provider),
Env: env,
Stdin: bytes.NewReader(providerConfig),
}
_, err = cmd.Output()
if err != nil {
exitError, ok := err.(*exec.ExitError)
if ok {
return errors.New(string(exitError.Stderr))
}
return err
}
return nil
}
func (c *dnsClient) monitorDNSPropagation(fqdn, value string, ttl int) error {
dnsClient := new(dns.Client)
dnsClient.Net = "tcp"
dnsClient.Timeout = time.Second * 10
ns, err := net.LookupNS(c.domain)
if err != nil {
return err
}
nameservers := make([]string, 0)
for _, s := range ns {
nameservers = append(nameservers, net.JoinHostPort(s.Host, "53"))
}
log.Printf("Monitoring %s DNS propagation: %s", fqdn, strings.Join(nameservers, " "))
dnsMsg := new(dns.Msg)
dnsMsg.SetQuestion(fqdn, dns.TypeTXT)
dnsMsg.SetEdns0(4096, false)
dnsMsg.RecursionDesired = false
var wg sync.WaitGroup
for _, ns := range nameservers {
wg.Add(1)
go func(ns string) {
defer wg.Done()
for {
in, _, err := dnsClient.Exchange(dnsMsg, ns)
if err != nil {
log.Println(err)
time.Sleep(1 * time.Second)
continue
}
if len(in.Answer) == 0 {
time.Sleep(1 * time.Second)
continue
}
for _, rr := range in.Answer {
if txt, ok := rr.(*dns.TXT); ok {
if strings.Join(txt.Txt, "") == value {
log.Printf("%s DNS-01 challenge complete on %s", c.domain, ns)
return
}
}
}
}
}(ns)
}
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
// Wait until the TTL expires to be sure Let's Encrypt picks up the
// right TXT record.
time.Sleep(time.Duration(ttl) * time.Second)
log.Printf("%s DNS propagation complete.", fqdn)
return nil
case <-time.After(300 * time.Second):
return fmt.Errorf("Timeout waiting for %s DNS propagation", fqdn)
}
}
func DNSChallengeRecord(domain, token, jwkThumbprint string) (string, string, int) {
fqdn := fmt.Sprintf("_acme-challenge.%s.", domain)
keyAuthorization := fmt.Sprintf("%s.%s", token, jwkThumbprint)
keyAuthorizationShaBytes := sha256.Sum256([]byte(keyAuthorization))
value := base64.URLEncoding.EncodeToString(keyAuthorizationShaBytes[:sha256.Size])
value = strings.TrimRight(value, "=")
ttl := 30
return fqdn, value, ttl
}