forked from tailscale/caddy-tailscale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
379 lines (323 loc) · 9.46 KB
/
module.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: Apache-2.0
// Package tscaddy provides a set of Caddy modules to integrate Tailscale into Caddy.
package tscaddy
// module.go contains the Tailscale network listeners for caddy
// as well as some shared logic for registered Tailscale nodes.
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/netip"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/caddyserver/certmagic"
"github.com/tailscale/tscert"
"go.uber.org/zap"
"tailscale.com/client/tailscale"
"tailscale.com/hostinfo"
"tailscale.com/tsnet"
)
func init() {
caddy.RegisterNetwork("tailscale", getTCPListener)
caddy.RegisterNetwork("tailscale+tls", getTLSListener)
caddy.RegisterNetwork("tailscale/udp", getUDPListener)
caddyhttp.RegisterNetworkHTTP3("tailscale", "tailscale/udp")
// Caddy uses tscert to get certificates for Tailscale hostnames.
// Update the tscert transport to send requests to the correct tsnet server,
// rather than just always connecting to the local machine's tailscaled.
tscert.TailscaledTransport = &tsnetMuxTransport{}
hostinfo.SetApp("caddy")
}
func getTCPListener(c context.Context, _ string, addr string, _ net.ListenConfig) (any, error) {
ctx, ok := c.(caddy.Context)
if !ok {
return nil, fmt.Errorf("context is not a caddy.Context: %T", c)
}
network, host, port, err := caddy.SplitNetworkAddress(addr)
if err != nil {
return nil, err
}
s, err := getNode(ctx, host)
if err != nil {
return nil, err
}
if network == "" {
network = "tcp"
}
return s.Listen(network, ":"+port)
}
func getTLSListener(c context.Context, _ string, addr string, _ net.ListenConfig) (any, error) {
ctx, ok := c.(caddy.Context)
if !ok {
return nil, fmt.Errorf("context is not a caddy.Context: %T", c)
}
network, host, port, err := caddy.SplitNetworkAddress(addr)
if err != nil {
return nil, err
}
s, err := getNode(ctx, host)
if err != nil {
return nil, err
}
if network == "" {
network = "tcp"
}
ln, err := s.Listen(network, ":"+port)
if err != nil {
return nil, err
}
localClient, _ := s.LocalClient()
ln = tls.NewListener(ln, &tls.Config{
GetCertificate: localClient.GetCertificate,
})
return ln, nil
}
func getUDPListener(c context.Context, _ string, addr string, _ net.ListenConfig) (any, error) {
ctx, ok := c.(caddy.Context)
if !ok {
return nil, fmt.Errorf("context is not a caddy.Context: %T", c)
}
network, host, port, err := caddy.SplitNetworkAddress(addr)
if err != nil {
return nil, err
}
s, err := getNode(ctx, host)
if err != nil {
return nil, err
}
st, err := s.Up(context.Background())
if err != nil {
return nil, err
}
if network == "" {
network = "udp4"
}
var ap netip.AddrPort
for _, ip := range st.TailscaleIPs {
// TODO(will): watch for Tailscale IP changes and update listener
if (network == "udp4" && ip.Is4()) || (network == "udp6" && ip.Is6()) {
p, _ := strconv.Atoi(port)
ap = netip.AddrPortFrom(ip, uint16(p))
break
}
}
return s.Server.ListenPacket(network, ap.String())
}
// nodes are the Tailscale nodes that have been configured and started.
// Node configuration comes from the global Tailscale Caddy app.
// When nodes are no longer in used (e.g. all listeners have been closed), they are shutdown.
//
// Callers should use getNode() to get a node by name, rather than accessing this pool directly.
var nodes = caddy.NewUsagePool()
// getNode returns a tailscale node for Caddy apps to interface with.
//
// The specified name will be used to lookup the node configuration from the tailscale caddy app,
// used to register the node the first time it is used.
// Only one tailscale node is created per name, even if multiple listeners are created for the node.
func getNode(ctx caddy.Context, name string) (*tailscaleNode, error) {
appIface, err := ctx.App("tailscale")
if err != nil {
return nil, err
}
app := appIface.(*App)
s, _, err := nodes.LoadOrNew(name, func() (caddy.Destructor, error) {
s := &tsnet.Server{
Logf: func(format string, args ...any) {
app.logger.Sugar().Debugf(format, args...)
},
UserLogf: func(format string, args ...any) {
app.logger.Sugar().Infof(format, args...)
},
Ephemeral: getEphemeral(name, app),
RunWebClient: getWebUI(name, app),
}
if s.AuthKey, err = getAuthKey(name, app); err != nil {
return nil, err
}
if s.ControlURL, err = getControlURL(name, app); err != nil {
return nil, err
}
if s.Hostname, err = getHostname(name, app); err != nil {
return nil, err
}
if s.Dir, err = getStateDir(name, app); err != nil {
return nil, err
}
if err := os.MkdirAll(s.Dir, 0700); err != nil {
return nil, err
}
return &tailscaleNode{
s,
}, nil
})
if err != nil {
return nil, err
}
return s.(*tailscaleNode), nil
}
var repl = caddy.NewReplacer()
func getAuthKey(name string, app *App) (string, error) {
if node, ok := app.Nodes[name]; ok {
if node.AuthKey != "" {
return repl.ReplaceOrErr(node.AuthKey, true, true)
}
}
if app.DefaultAuthKey != "" {
return repl.ReplaceOrErr(app.DefaultAuthKey, true, true)
}
// Set authkey to "TS_AUTHKEY_<HOST>".
// If empty, fall back to "TS_AUTHKEY".
authKey := os.Getenv("TS_AUTHKEY_" + strings.ToUpper(name))
if authKey != "" {
app.logger.Warn("Relying on TS_AUTHKEY_{HOST} env var is deprecated. Set caddy config instead.", zap.Any("host", name))
return authKey, nil
}
return os.Getenv("TS_AUTHKEY"), nil
}
func getControlURL(name string, app *App) (string, error) {
if node, ok := app.Nodes[name]; ok {
if node.ControlURL != "" {
return repl.ReplaceOrErr(node.ControlURL, true, true)
}
}
return repl.ReplaceOrErr(app.ControlURL, true, true)
}
func getEphemeral(name string, app *App) bool {
if node, ok := app.Nodes[name]; ok {
if v, ok := node.Ephemeral.Get(); ok {
return v
}
}
return app.Ephemeral
}
func getHostname(name string, app *App) (string, error) {
if app == nil {
return name, nil
}
if node, ok := app.Nodes[name]; ok {
if node.Hostname != "" {
return repl.ReplaceOrErr(node.Hostname, true, true)
}
}
return name, nil
}
func getStateDir(name string, app *App) (string, error) {
if node, ok := app.Nodes[name]; ok {
if node.StateDir != "" {
return repl.ReplaceOrErr(node.StateDir, true, true)
}
}
if app.StateDir != "" {
s, err := repl.ReplaceOrErr(app.StateDir, true, true)
if err != nil {
return "", err
}
return filepath.Join(s, name), nil
}
// By default, tsnet will use the name of the running program in the state directory,
// but we also include the hostname so that a single caddy instance can have multiple nodes.
configDir, err := os.UserConfigDir()
if err != nil {
return "", err
}
return filepath.Join(configDir, "tsnet-caddy-"+name), nil
}
func getWebUI(name string, app *App) bool {
if node, ok := app.Nodes[name]; ok {
if v, ok := node.WebUI.Get(); ok {
return v
}
}
return app.WebUI
}
// tailscaleNode is a wrapper around a tsnet.Server that provides a fully self-contained Tailscale node.
// This node can listen on the tailscale network interface, or be used to connect to other nodes in the tailnet.
type tailscaleNode struct {
*tsnet.Server
}
func (t tailscaleNode) Destruct() error {
return t.Close()
}
func (t *tailscaleNode) Listen(network string, addr string) (net.Listener, error) {
ln, err := t.Server.Listen(network, addr)
if err != nil {
return nil, err
}
serverListener := &tsnetServerListener{
name: t.Hostname,
Listener: ln,
}
return serverListener, nil
}
type tsnetServerListener struct {
name string
net.Listener
}
func (t *tsnetServerListener) Unwrap() net.Listener {
if t == nil {
return nil
}
return t.Listener
}
func (t *tsnetServerListener) Close() error {
if err := t.Listener.Close(); err != nil {
return err
}
// Decrement usage count of this node.
// If usage reaches zero, then the node is actually shutdown.
_, err := nodes.Delete(t.name)
return err
}
// tsnetMuxTransport is an [http.RoundTripper] that sends requests to the LocalAPI
// for the tsnet server that matches the ClientHelloInfo server name.
// If no tsnet server matches, a default Transport is used.
type tsnetMuxTransport struct {
defaultTransport *http.Transport
defaultTransportOnce sync.Once
}
func (t *tsnetMuxTransport) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := req.Context()
var rt http.RoundTripper
clientHello, ok := ctx.Value(certmagic.ClientHelloInfoCtxKey).(*tls.ClientHelloInfo)
if ok && clientHello != nil {
nodes.Range(func(key, value any) bool {
if n, ok := value.(*tailscaleNode); ok && n != nil {
for _, d := range n.CertDomains() {
// Tailscale doesn't do wildcard certs, but caddy uses MatchWildcard
// for the built-in Tailscale cert manager, so we do so here as well.
if certmagic.MatchWildcard(clientHello.ServerName, d) {
if lc, err := n.LocalClient(); err == nil {
rt = &localAPITransport{lc}
}
return false
}
}
}
return true
})
}
if rt == nil {
t.defaultTransportOnce.Do(func() {
t.defaultTransport = &http.Transport{
DialContext: tscert.TailscaledDialer,
}
})
rt = t.defaultTransport
}
return rt.RoundTrip(req)
}
// localAPITransport is an [http.RoundTripper] that sends requests to a [tailscale.LocalClient]'s LocalAPI.
type localAPITransport struct {
*tailscale.LocalClient
}
func (t *localAPITransport) RoundTrip(req *http.Request) (*http.Response, error) {
return t.DoLocalRequest(req)
}