File
Blob: internal/dns/dns.go
| 1 | package dns |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "runtime" |
| 10 | "time" |
| 11 | |
| 12 | "go.miragespace.co/specter/acme" |
| 13 | "go.miragespace.co/specter/config" |
| 14 | "go.miragespace.co/specter/internal/listen" |
| 15 | "go.miragespace.co/specter/spec/chord" |
| 16 | "go.miragespace.co/specter/spec/protocol" |
| 17 | "go.miragespace.co/specter/util/reuse" |
| 18 | |
| 19 | "github.com/avast/retry-go/v5" |
| 20 | "github.com/miekg/dns" |
| 21 | "github.com/twitchtv/twirp" |
| 22 | "go.uber.org/zap" |
| 23 | ) |
| 24 | |
| 25 | type Options struct { |
| 26 | Logger *zap.Logger |
| 27 | Version string |
| 28 | TCPAddresses []listen.Address |
| 29 | UDPAddresses []listen.Address |
| 30 | RPCNetwork string |
| 31 | RPCAddress string |
| 32 | ACMEEmail string |
| 33 | ACMEZone string |
| 34 | } |
| 35 | |
| 36 | // Run serves the ACME challenge zone until ctx is canceled. |
| 37 | func Run(ctx context.Context, options Options) error { |
| 38 | ctx, cancel := context.WithCancel(ctx) |
| 39 | defer cancel() |
| 40 | logger := options.Logger |
| 41 | |
| 42 | addrStrings := func(addrs []listen.Address) []string { |
| 43 | out := make([]string, 0, len(addrs)) |
| 44 | for _, a := range addrs { |
| 45 | out = append(out, a.Address) |
| 46 | } |
| 47 | return out |
| 48 | } |
| 49 | logger.Info("acme dns listener configuration", |
| 50 | zap.Strings("tcp", addrStrings(options.TCPAddresses)), |
| 51 | zap.Strings("udp", addrStrings(options.UDPAddresses)), |
| 52 | ) |
| 53 | |
| 54 | listenCfg := &net.ListenConfig{ |
| 55 | Control: reuse.Control, |
| 56 | } |
| 57 | |
| 58 | dialer := &net.Dialer{} |
| 59 | t := http.DefaultTransport.(*http.Transport).Clone() |
| 60 | t.MaxConnsPerHost = 100 |
| 61 | t.MaxIdleConnsPerHost = 5 |
| 62 | t.DisableCompression = true |
| 63 | t.IdleConnTimeout = time.Minute |
| 64 | t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 65 | return dialer.DialContext(ctx, options.RPCNetwork, options.RPCAddress) |
| 66 | } |
| 67 | httpClient := &http.Client{ |
| 68 | Transport: t, |
| 69 | } |
| 70 | defer t.CloseIdleConnections() |
| 71 | client := protocol.NewKVServiceProtobufClient("http://rpc", httpClient) |
| 72 | kv := &remoteKV{ |
| 73 | Client: client, |
| 74 | } |
| 75 | |
| 76 | acmeDomain := options.ACMEZone |
| 77 | configClient := config.NewClient("http://rpc", httpClient) |
| 78 | loadConfig := func(ctx context.Context) (config.Record, error) { |
| 79 | return loadDNSConfig(ctx, configClient) |
| 80 | } |
| 81 | record, err := waitDNSConfig(ctx, logger, loadConfig, acmeDomain, dnsConfigPollInterval) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | acmeDNS, err := acme.NewDNS(ctx, logger.With(zap.String("component", "acme_dns")), |
| 86 | kv, |
| 87 | options.ACMEEmail, |
| 88 | acmeDomain, record, |
| 89 | ) |
| 90 | if err != nil { |
| 91 | return fmt.Errorf("configure ACME DNS: %w", err) |
| 92 | } |
| 93 | refreshDone := make(chan struct{}) |
| 94 | go func() { |
| 95 | defer close(refreshDone) |
| 96 | refreshDNSConfig(ctx, logger, loadConfig, acmeDNS, dnsConfigPollInterval) |
| 97 | }() |
| 98 | defer func() { |
| 99 | cancel() |
| 100 | <-refreshDone |
| 101 | }() |
| 102 | |
| 103 | dnsMux := dns.NewServeMux() |
| 104 | dnsMux.Handle(acmeDomain, acmeDNS) |
| 105 | dnsMux.Handle(".", chaos(options.Version)) |
| 106 | |
| 107 | var tcpServers, udpServers []*dns.Server |
| 108 | defer func() { |
| 109 | for _, srv := range tcpServers { |
| 110 | srv.Shutdown() |
| 111 | srv.Listener.Close() |
| 112 | } |
| 113 | for _, srv := range udpServers { |
| 114 | srv.Shutdown() |
| 115 | srv.PacketConn.Close() |
| 116 | } |
| 117 | }() |
| 118 | |
| 119 | for _, addr := range options.TCPAddresses { |
| 120 | ln, err := listenCfg.Listen(ctx, addr.Network, addr.Address) |
| 121 | if err != nil { |
| 122 | return fmt.Errorf("error setting up dns tcp listener on %s: %w", addr.Address, err) |
| 123 | } |
| 124 | listenAddr := addr.Address |
| 125 | server := &dns.Server{ |
| 126 | Listener: ln, |
| 127 | Handler: dnsMux, |
| 128 | NotifyStartedFunc: func() { |
| 129 | logger.Info("ACME DNS started", zap.String("proto", "tcp"), zap.String("listen", listenAddr)) |
| 130 | }, |
| 131 | } |
| 132 | tcpServers = append(tcpServers, server) |
| 133 | go server.ActivateAndServe() |
| 134 | } |
| 135 | |
| 136 | for _, addr := range options.UDPAddresses { |
| 137 | pconn, err := listenCfg.ListenPacket(ctx, addr.Network, addr.Address) |
| 138 | if err != nil { |
| 139 | return fmt.Errorf("error setting up dns udp listener on %s: %w", addr.Address, err) |
| 140 | } |
| 141 | listenAddr := addr.Address |
| 142 | var packetConn net.PacketConn = pconn |
| 143 | if runtime.GOOS == "illumos" { |
| 144 | // needed to force net.PacketConn path instead of *net.UDPConn path |
| 145 | // because of dual stack not working on illumos |
| 146 | packetConn = &squashed{PacketConn: pconn} |
| 147 | } |
| 148 | server := &dns.Server{ |
| 149 | PacketConn: packetConn, |
| 150 | Handler: dnsMux, |
| 151 | NotifyStartedFunc: func() { |
| 152 | logger.Info("ACME DNS started", zap.String("proto", "udp"), zap.String("listen", listenAddr)) |
| 153 | }, |
| 154 | } |
| 155 | udpServers = append(udpServers, server) |
| 156 | go server.ActivateAndServe() |
| 157 | } |
| 158 | |
| 159 | <-ctx.Done() |
| 160 | logger.Info("ACME DNS stopping", zap.Error(ctx.Err())) |
| 161 | |
| 162 | return nil |
| 163 | } |
| 164 | |
| 165 | const ( |
| 166 | dnsConfigPollInterval = 5 * time.Second |
| 167 | dnsConfigTimeout = 3 * time.Second |
| 168 | ) |
| 169 | |
| 170 | func loadDNSConfig(ctx context.Context, client *config.Client) (config.Record, error) { |
| 171 | ctx, cancel := context.WithTimeout(ctx, dnsConfigTimeout) |
| 172 | defer cancel() |
| 173 | record, err := client.Get(ctx, acme.DNSConfigName) |
| 174 | var rpcError twirp.Error |
| 175 | if errors.As(err, &rpcError) && rpcError.Code() == twirp.NotFound { |
| 176 | return config.Record{}, fmt.Errorf("shared DNS configuration is missing; initialize the first server with specter config init --data-dir DIR --file FILE") |
| 177 | } |
| 178 | return record, err |
| 179 | } |
| 180 | |
| 181 | func waitDNSConfig(ctx context.Context, logger *zap.Logger, load func(context.Context) (config.Record, error), localZone string, interval time.Duration) (config.Record, error) { |
| 182 | return retry.NewWithData[config.Record]( |
| 183 | retry.Context(ctx), |
| 184 | retry.UntilSucceeded(), |
| 185 | retry.Delay(interval), |
| 186 | retry.DelayType(retry.FixedDelay), |
| 187 | retry.OnRetry(func(_ uint, err error) { |
| 188 | if ctx.Err() == nil { |
| 189 | logger.Warn("Waiting for shared DNS configuration", zap.Error(err)) |
| 190 | } |
| 191 | }), |
| 192 | ).Do(func() (config.Record, error) { |
| 193 | record, err := load(ctx) |
| 194 | if err == nil { |
| 195 | _, err = acme.DecodeDNSConfig(record, localZone) |
| 196 | } |
| 197 | return record, err |
| 198 | }) |
| 199 | } |
| 200 | |
| 201 | func refreshDNSConfig(ctx context.Context, logger *zap.Logger, load func(context.Context) (config.Record, error), handler *acme.DNS, interval time.Duration) { |
| 202 | ticker := time.NewTicker(interval) |
| 203 | defer ticker.Stop() |
| 204 | for { |
| 205 | select { |
| 206 | case <-ctx.Done(): |
| 207 | return |
| 208 | case <-ticker.C: |
| 209 | record, err := load(ctx) |
| 210 | if err == nil { |
| 211 | err = handler.ApplyConfig(record) |
| 212 | } |
| 213 | if err != nil && ctx.Err() == nil { |
| 214 | logger.Warn("Unable to refresh shared DNS configuration; retaining the active version", zap.String("version", handler.ConfigVersion()), zap.Error(err)) |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | type remoteKV struct { |
| 221 | chord.KV |
| 222 | Client protocol.KVService |
| 223 | } |
| 224 | |
| 225 | func (r *remoteKV) PrefixList(ctx context.Context, prefix []byte) (children [][]byte, err error) { |
| 226 | resp, err := r.Client.List(ctx, &protocol.PrefixRequest{ |
| 227 | Prefix: prefix, |
| 228 | }) |
| 229 | if err != nil { |
| 230 | return nil, err |
| 231 | } |
| 232 | return resp.GetChildren(), nil |
| 233 | } |
| 234 | |
| 235 | func chaos(version string) dns.HandlerFunc { |
| 236 | return func(w dns.ResponseWriter, r *dns.Msg) { |
| 237 | m := new(dns.Msg) |
| 238 | m.SetReply(r) |
| 239 | |
| 240 | q := r.Question[0] |
| 241 | if q.Name == "version.bind." && q.Qtype == dns.TypeTXT && q.Qclass == dns.ClassCHAOS { |
| 242 | m.Answer = []dns.RR{ |
| 243 | &dns.TXT{ |
| 244 | Hdr: dns.RR_Header{ |
| 245 | Name: q.Name, |
| 246 | Rrtype: dns.TypeTXT, |
| 247 | Class: dns.ClassCHAOS, |
| 248 | Ttl: 3600, |
| 249 | }, |
| 250 | Txt: []string{version}, |
| 251 | }, |
| 252 | } |
| 253 | } else { |
| 254 | m.MsgHdr.Rcode = dns.RcodeRefused |
| 255 | } |
| 256 | |
| 257 | w.WriteMsg(m) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | type squashed struct { |
| 262 | net.PacketConn |
| 263 | } |