Repository navigation
Expand file tree
/
Copy pathtailcat.go
More file actions
2806 lines (2586 loc) · 90.9 KB
/
Copy pathtailcat.go
File metadata and controls
2806 lines (2586 loc) · 90.9 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Package tailcat implements a control-plane-free network pipe built on
// Tailscale's data plane which provides encryption (WireGuard) and NAT traversal.
// This is the library behind the "tailcat" CLI command (cmd/tailcat).
//
// A [Server] listens for incoming clients via a DERP relay. Clients discover
// the server through a compact [Addr] (a tailcat address) that encodes the
// server's WireGuard and path-discovery public keys, optional WireGuard
// pre-shared key, and DERP region. DERP is used only for the initial
// bootstrap; once both sides learn each other's endpoints, Tailscale's
// magicsock layer upgrades to a direct peer-to-peer UDP path whenever possible,
// just like the normal Tailscale data plane. DERP remains available as a
// fallback relay if a direct path cannot be established.
//
// Once connected, the two sides exchange arbitrary TCP streams and UDP
// datagrams over the WireGuard tunnel with no Tailscale account or coordination
// server required.
// Optionally, the server can run an SSH server on port 22, either requiring
// authorized public keys or relying on the tunnel for client identity.
//
// The name "tailcat" is a nod to the classic "netcat" tool, but with
// Tailscale's WireGuard encryption + NAT traversal.
//
// Using Tailscale's DERP servers is not required; you can run your own DERP
// server and provide its region information in the tailcat address.
//
// This package has no API stability promises: types, functions, and
// the wire format may all change. See the Stability section of the
// README (https://github.com/tailscale/tailcat/#readme) for details,
// including the terms of Tailscale's public DERP relays.
package tailcat
import (
"cmp"
"context"
"crypto/hmac"
cryptorand "crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"maps"
"math/rand"
"net"
"net/http"
"net/netip"
"reflect"
"runtime"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/fxamacker/cbor/v2"
"github.com/tailscale/wireguard-go/device"
go4mem "go4.org/mem"
"go4.org/netipx"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
"gvisor.dev/gvisor/pkg/waiter"
"tailscale.com/disco"
"tailscale.com/envknob"
"tailscale.com/health"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnstate"
"tailscale.com/ipn/store/mem"
"tailscale.com/net/dns"
"tailscale.com/net/netmon"
"tailscale.com/net/netns"
"tailscale.com/net/tsaddr"
"tailscale.com/net/tsdial"
"tailscale.com/tailcfg"
"tailscale.com/tsd"
"tailscale.com/types/ipproto"
"tailscale.com/types/key"
"tailscale.com/types/logger"
"tailscale.com/types/netmap"
"tailscale.com/types/nettype"
"tailscale.com/types/views"
"tailscale.com/util/eventbus"
"tailscale.com/util/mak"
"tailscale.com/wgengine"
"tailscale.com/wgengine/filter"
"tailscale.com/wgengine/netstack"
"tailscale.com/wgengine/router"
"tailscale.com/wgengine/wgcfg"
)
// Verbose controls whether extra diagnostic logging is emitted during
// DERP region auto-detection (netcheck).
var Verbose = false
// DefaultDERPMapURL is the URL of the JSON-encoded [tailcfg.DERPMap]
// that [ConnInfo.Expand] fetches when no alternate DERP map source is
// specified via options.
const DefaultDERPMapURL = "https://tailcat.dev/derpmap.json"
// DERPMapURL is an option for [ConnInfo.Expand] specifying an
// alternate URL to fetch the DERP map from instead of
// [DefaultDERPMapURL].
type DERPMapURL string
// DERPMapCache is an option for [ConnInfo.Expand] and [FetchDERPMap]
// that caches fetched DERP maps. Without one, a process-wide
// in-memory cache is used; provide an implementation (like the
// tailcat CLI's on-disk one) to persist across processes.
// Implementations just store bytes; the freshness policy lives in the
// fetcher: a stored map younger than an hour is used without any
// network traffic, an older one is revalidated with If-None-Match
// (the ETag is opaque to us), and a stored map of any age is used as
// a fallback if the fetch fails or times out.
type DERPMapCache interface {
// Get returns the previously stored DERP map response for url:
// its raw JSON, the server's ETag (or ""), and when it was
// stored. It returns ok == false if nothing usable is stored.
Get(url string) (data []byte, etag string, storedAt time.Time, ok bool)
// Put stores the DERP map response for url, replacing any prior
// entry and marking it stored as of now. An empty etag means the
// server sent none.
Put(url string, data []byte, etag string) error
}
// derpMapCacheMaxAge is how old a cached DERP map may be and still be
// used without revalidating with the server.
const derpMapCacheMaxAge = time.Hour
// ExpandForServer is an option for [ConnInfo.Expand] that marks the
// DERP map fetch as being on behalf of a tailcat server (which will
// listen on the chosen region) rather than a client. It is sent as a
// hint header to the DERP map server.
var ExpandForServer expandForServer
type expandForServer struct{}
// Addr is a compact, URL-safe tailcat address that a server gives to clients
// so they can connect. It is the "tc"-prefixed base64url encoding of a
// CBOR-encoded [ConnInfo]. A typical Addr looks like "tcomFwWC…".
type Addr string
// ConnInfo describes how to reach a server: its WireGuard and path-discovery
// public keys, WireGuard pre-shared key, and which DERP relay region to use. It is serialized into an
// [Addr] for exchange,
// via the wire types in wire.go.
type ConnInfo struct {
ServerPublic NodePublic // a key.NodePublic
// ServerDiscoPublic is the server's public key for path discovery.
// It is deliberately independent from ServerPublic: disco packets carry
// this key in cleartext on direct UDP paths, while ServerPublic is the
// unguessable part of the server's tailcat address.
ServerDiscoPublic DiscoPublic // a key.DiscoPublic
// PresharedKey is mixed into the WireGuard handshake. It is an independent
// random secret, providing post-quantum confidentiality and preventing a
// DERP operator that observes the peers' node public keys from joining the
// tunnel. When non-zero, treat the entire tailcat address as a secret
// because it contains this key. The zero value disables the pre-shared-key
// layer for compatibility with old clients.
PresharedKey PresharedKey
// Hybrid is whether the server uses the experimental hybrid
// post-quantum (ML-KEM-768) WireGuard handshake, which clients must
// then use too: there is no fallback between handshake types. Its
// post-quantum protection doesn't depend on the address staying
// secret, so a hybrid address carries a shorter, 128-bit pre-shared
// key (see [PresharedKey.ForHybrid]), if any.
Hybrid bool `json:",omitempty"`
// Region, if non-empty, lists the regions of a DERPMap.
// Either Region or RegionID must be set. If Region is set
// the client can avoid doing a lookup to discover the DERP map
// but the tailcat address is longer.
//
// As of 2023-09-22, a maximum of 1 region may be provided.
// In the future, a server might advertise its presence in
// multiple DERP regions and clients could try them all.
Region []*tailcfg.DERPRegion `json:",omitempty"`
// RegionID lists the number of one of Tailscale's provided
// DERP servers. If set, Region may be omitted and the tailcat address
// is shorter, at the cost of the client needing to fetch
// the derpmap from tailscale.com once at startup.
// If -1 (for use when saving a keypair to disk for reuse later), a region
// is selected automatically at startup based on latency.
RegionID tailcfg.DERPRegionID `json:",omitempty"`
}
// NodePublic is a wrapper around key.NodePublic just so we can have a slightly
// smaller CBOR representation without the "np" prefix.
type NodePublic struct {
key.NodePublic
}
// DiscoPublic is a wrapper around key.DiscoPublic that uses its raw 32-byte
// representation in tailcat addresses.
type DiscoPublic struct {
key.DiscoPublic
}
const presharedKeyLen = device.NoisePresharedKeySize
// hybridPresharedKeyLen is the length of the pre-shared key in an address
// using the hybrid handshake. The key there only keeps strangers who know
// the server's public key, such as a DERP operator, out of the tunnel, so
// it doesn't need 256 bits. It still needs enough that it can't be guessed
// offline: any client the server admits gets a handshake response, from
// which it can test guesses at the key.
//
// Clients from before the hybrid handshake reject an address with a
// pre-shared key of this length, so they fail early with a parse error
// rather than retrying a handshake that can never succeed. (A hybrid
// address without a pre-shared key gets no such early failure.)
const hybridPresharedKeyLen = 16
// PresharedKey is an optional 256-bit WireGuard pre-shared key. Tailcat
// addresses generated by current servers always contain a non-zero key. It is
// a named form of [device.NoisePresharedKey] so it can define the CBOR and JSON
// encodings used by tailcat addresses and persisted server keys.
type PresharedKey device.NoisePresharedKey
// NewPresharedKey returns a new cryptographically random WireGuard pre-shared
// key.
func NewPresharedKey() (ret PresharedKey) {
for ret.IsZero() {
if _, err := cryptorand.Read(ret[:]); err != nil {
panic(fmt.Sprintf("generating WireGuard pre-shared key: %v", err))
}
}
return ret
}
// ForHybrid returns p truncated to the 128-bit pre-shared key used with
// the hybrid handshake, zero-padded to the WireGuard key size. A hybrid
// address encodes only the first 128 bits, and both peers use this form.
func (p PresharedKey) ForHybrid() PresharedKey {
clear(p[hybridPresharedKeyLen:])
return p
}
// IsZero reports whether p is the zero value.
func (p PresharedKey) IsZero() bool {
var zero PresharedKey
return subtle.ConstantTimeCompare(p[:], zero[:]) == 1
}
// Equal reports whether p and q contain the same key.
func (p PresharedKey) Equal(q PresharedKey) bool {
return subtle.ConstantTimeCompare(p[:], q[:]) == 1
}
// MarshalBinary implements encoding.BinaryMarshaler for CBOR serialization.
func (p PresharedKey) MarshalBinary() ([]byte, error) {
return append([]byte(nil), p[:]...), nil
}
// UnmarshalBinary implements encoding.BinaryUnmarshaler for CBOR serialization.
func (p *PresharedKey) UnmarshalBinary(x []byte) error {
if len(x) != presharedKeyLen {
return fmt.Errorf("invalid WireGuard pre-shared key length %d, want %d", len(x), presharedKeyLen)
}
copy(p[:], x)
return nil
}
// MarshalText implements encoding.TextMarshaler for JSON serialization.
func (p PresharedKey) MarshalText() ([]byte, error) {
ret := make([]byte, len("psk:")+hex.EncodedLen(len(p)))
copy(ret, "psk:")
hex.Encode(ret[len("psk:"):], p[:])
return ret, nil
}
// UnmarshalText implements encoding.TextUnmarshaler for JSON serialization.
func (p *PresharedKey) UnmarshalText(x []byte) error {
const prefix = "psk:"
if len(x) != len(prefix)+hex.EncodedLen(presharedKeyLen) || string(x[:len(prefix)]) != prefix {
return fmt.Errorf("invalid WireGuard pre-shared key %q", x)
}
var ret PresharedKey
if _, err := hex.Decode(ret[:], x[len(prefix):]); err != nil {
return fmt.Errorf("invalid WireGuard pre-shared key: %w", err)
}
*p = ret
return nil
}
// Equal reports whether a and b represent the same disco public key.
func (a DiscoPublic) Equal(b DiscoPublic) bool {
return a.DiscoPublic == b.DiscoPublic
}
// MarshalBinary implements encoding.BinaryMarshaler.
func (p DiscoPublic) MarshalBinary() ([]byte, error) {
return p.DiscoPublic.AppendTo(nil), nil
}
// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (p *DiscoPublic) UnmarshalBinary(x []byte) error {
if len(x) != key.DiscoPublicRawLen {
return fmt.Errorf("invalid disco public key length %d, want %d", len(x), key.DiscoPublicRawLen)
}
p.DiscoPublic = key.DiscoPublicFromRaw32(go4mem.B(x))
return nil
}
// MarshalBinary implements encoding.BinaryMarshaler for CBOR serialization,
// encoding the raw 32-byte key without the "nodekey:" text prefix.
func (p NodePublic) MarshalBinary() ([]byte, error) {
return p.NodePublic.AppendTo(nil), nil
}
// UnmarshalBinary implements encoding.BinaryUnmarshaler for CBOR deserialization.
func (p *NodePublic) UnmarshalBinary(x []byte) error {
if len(x) != key.NodePublicRawLen {
return fmt.Errorf("invalid node public key length %d, want %d", len(x), key.NodePublicRawLen)
}
p.NodePublic = key.NodePublicFromRaw32(go4mem.B(x))
return nil
}
// Equal reports whether a and b represent the same public key.
func (a NodePublic) Equal(b NodePublic) bool {
return a == b
}
// PrivateKey is a node identity: a private key paired with the connection
// info needed to reach this node. Despite its historical name, Public contains
// the secret WireGuard pre-shared key and must be kept private. Its DERP region
// must be populated by the caller before the key is usable.
type PrivateKey struct {
Private key.NodePrivate
Public ConnInfo
}
// NewPrivateKey returns a new PrivateKey, but without
// the DERP region populated. It's up to the caller to
// populate that.
func NewPrivateKey() *PrivateKey {
ret := &PrivateKey{
Private: key.NewNode(),
}
ret.Public.ServerPublic = NodePublic{ret.Private.Public()}
ret.Public.ServerDiscoPublic = DiscoPublic{discoPrivateForNode(ret.Private).Public()}
ret.Public.PresharedKey = NewPresharedKey()
return ret
}
// locoBackend is like tailscaled's LocalBackend, but crazier.
// It serves a similar purpose (to be the hub of the world)
// but there's no controlclient involved, because there's
// no control plane.
type locoBackend struct {
sys tsd.System
priv key.NodePrivate
pub key.NodePublic
addr netip.Addr
addrPrefix netip.Prefix
ns *netstack.Impl
dm *tailcfg.DERPMap
logf logger.Logf
serverPub key.NodePublic // non-zero if we're a client (server's public key)
serverDiscoPub key.DiscoPublic // non-zero if we're a client (server's disco key)
presharedKey PresharedKey
hybrid bool // whether to use the hybrid post-quantum WireGuard handshake
isServer bool
// discoPublic returns the node's disco public key, memoized to
// avoid redoing the curve25519 derivation for every client that
// joins.
discoPublic func() key.DiscoPublic
// onDERPRecv is called for non-disco DERP packets before the
// peer map lookup. Set before createEngine.
onDERPRecv func(regionID tailcfg.DERPRegionID, src key.NodePublic, pkt []byte) bool
// allowClient is the server's [Server.AllowClient] hook, or nil
// to allow all clients. Set before Start.
allowClient func(key.NodePublic) bool
mu sync.Mutex
clients map[key.NodePublic]*tailcfg.Node // for the server
nextClientID tailcfg.NodeID // for the server; never reused after a removal
pendingAllow map[key.NodePublic]bool // client keys with an allowClient call in flight
nm *netmap.NetworkMap
eps []netip.AddrPort // our current local UDP endpoints, sorted
closeOnce sync.Once
// clientInstance is, for the server, the meow instance ID last seen
// from each client in clients. It has an entry exactly when clients
// does, which is zero for a client too old to send one.
clientInstance map[key.NodePublic]meowInstanceID
// meowInstance is, for a client, the instance ID it sends in its
// meow pings.
meowInstance meowInstanceID
}
func (b *locoBackend) derpRegionID() tailcfg.DERPRegionID {
if b.dm == nil {
panic("no derp map")
}
for _, r := range b.dm.Regions {
return r.RegionID
}
panic("no derp regions in derp map")
}
func (b *locoBackend) Close() error {
b.closeOnce.Do(func() {
if b.ns != nil {
b.ns.Close()
}
if e, ok := b.sys.Engine.GetOK(); ok {
e.Close()
}
if m, ok := b.sys.NetMon.GetOK(); ok {
m.Close()
}
if d, ok := b.sys.Dialer.GetOK(); ok {
d.Close()
}
if bus, ok := b.sys.Bus.GetOK(); ok {
bus.Close()
}
})
return nil
}
// Server listens for clients over a WireGuard tunnel relayed through DERP.
// Incoming TCP connections and UDP flows are dispatched via the OnTCP/OnUDP
// callbacks (for traffic addressed to the server itself) and their Forward
// counterparts (for traffic the server relays to other addresses), or
// accepted from listeners created by [Server.Listen], which take precedence
// over the callbacks for their ports.
//
// The zero value is a usable server: optionally populate the
// configuration fields, then call [Server.Start], which picks
// defaults for anything unset. [Server.Listen] starts the server
// itself if needed, so callers using only listeners can skip Start.
// Fields documented as needing to be set before Start must likewise
// be set before the first Listen call.
type Server struct {
// Key is the server's node identity.
// If zero, Start generates a new ephemeral key.
Key key.NodePrivate
// PresharedKey is the WireGuard pre-shared key clients must know to
// connect. If zero, Start generates a new ephemeral key and includes it in
// [Server.TailcatAddr]. A persistent server must restore this value along
// with Key so its address remains usable across restarts.
PresharedKey PresharedKey
// DisablePresharedKey disables the pre-shared-key layer and causes Start to
// ignore PresharedKey. This is not recommended, but produces shorter
// addresses compatible with tailcat clients v0.5.0 and earlier.
DisablePresharedKey bool
// Hybrid, if true, makes the server use the experimental hybrid
// post-quantum (ML-KEM-768) WireGuard handshake with all clients.
// Clients must support it too; older ones reject the server's
// address. The server uses only the first 128 bits of PresharedKey
// (see [PresharedKey.ForHybrid]), giving shorter addresses.
//
// It must be set before calling Start.
Hybrid bool
// Logf is the logger used for debug messages.
// If nil, log.Printf is used.
Logf logger.Logf
// Region, if non-nil, is the DERP region to use as the bootstrap
// relay, without fetching any DERP map.
Region *tailcfg.DERPRegion
// RegionID, if non-zero and Region is nil, is the ID of the DERP
// map region to use. If zero, the nearest region is picked based
// on latency at Start.
RegionID tailcfg.DERPRegionID
// DERPMapURL, if non-empty, is an alternate URL to fetch the DERP
// map from when Region is nil. If empty, [DefaultDERPMapURL] is
// used.
DERPMapURL string
// DERPMapCache, if non-nil, caches fetched DERP maps. If nil, a
// process-wide in-memory cache is used.
DERPMapCache DERPMapCache
// AllowClient, if non-nil, reports whether the client with node
// key k may connect. It is consulted when a client that is not
// already connected announces itself. A client it rejects is
// silently ignored and is asked about again if it retries, which
// clients do about once a second while trying to connect. If nil,
// all clients are allowed.
//
// It is called without any server lock held and may block, for
// example on a lookup in another service, and may call other
// Server methods. A slow answer delays only that client, and at
// most one call per key is in flight at a time. Because a rejected
// client keeps retrying, an expensive hook should remember its
// negative answers itself.
//
// AllowClient decides admission only; it is not asked again about
// a connected client. Use [Server.DisconnectClient] to drop one.
// For a fixed or hand-maintained list of keys, use a [KeySet]:
//
// var allow tailcat.KeySet
// allow.Add(k)
// s.AllowClient = allow.Contains
//
// It must be set before calling Start.
AllowClient func(k key.NodePublic) bool
lb *locoBackend // non-nil once Start has been called
// startMu serializes Start and the implicit start in Listen.
startMu sync.Mutex
// listenerMu guards the listener maps below and serializes packet
// filter rebuilds as the listener set changes.
listenerMu sync.Mutex
tcpListeners map[uint16]*listener // keyed by port on the server's own address
udpListeners map[uint16]*listener // keyed by port on the server's own address
// AllowProxy, if non-nil, reports whether
// a TCP or UDP proxy is allowed for that target.
AllowProxy func(netip.AddrPort) bool
// OnTCP, if non-nil, specifies a func that returns a handler to handle
// incoming connections to the provided port. If nil or if it returns nil,
// then a RST is sent.
//
// This only applies to connections directly to the server node and not
// when being a subnet router. See OnTCPForward for relayed connections.
// Connections to a port with an active [Server.Listen] listener go to
// that listener and are never offered to OnTCP.
//
// It must be set before calling Start.
OnTCP func(port uint16) (handler func(net.Conn))
// OnTCPForward, if non-nil, specifies a func that returns a handler to handle
// incoming connections to the provided IP:port. If nil or if it returns nil,
// then a RST is sent.
//
// This only applies to connections relayed through the server and not to the server
// itself. See OnTCP for direct connections to the server.
//
// It must be set before calling Start. Setting it also widens the
// packet filter installed at Start to admit traffic to any
// destination, not just the server's own address.
OnTCPForward func(netip.AddrPort) (handler func(net.Conn))
// OnUDP, if non-nil, specifies a func that returns a handler for an
// incoming UDP flow to the provided port. Each handler receives a connected
// packet connection for one client source IP:port. Datagram boundaries are
// preserved, and LocalAddr and RemoteAddr report the destination and source
// of the flow. If nil or if it returns nil, the flow is dropped.
//
// This only applies to packets addressed directly to the server node and not
// when being a subnet router. See OnUDPForward for relayed packets.
// Flows to a port with an active [Server.Listen] listener go to that
// listener and are never offered to OnUDP.
//
// It must be set before calling Start.
OnUDP func(port uint16) (handler func(ConnPacketConn))
// OnUDPForward is like OnUDP for UDP flows addressed through the server to
// another IP:port. Setting it also widens the packet filter installed at
// Start to admit UDP traffic to any destination.
//
// It must be set before calling Start.
OnUDPForward func(netip.AddrPort) (handler func(ConnPacketConn))
// ServedTCPPorts, if non-nil, restricts which TCP ports on the
// server's own address the packet filter admits new inbound
// connections to. If nil, connections to all ports reach OnTCP,
// which remains the per-port gate either way. Callers that know
// their served ports statically (like the tailcat CLI) can set
// this for defense in depth. Ports with an active [Server.Listen]
// listener are always admitted, whether or not listed here.
//
// Unlike OnTCP's nil-handler response, packets dropped by the
// filter get no RST; a client dialing a filtered port times out.
//
// It must be set before calling Start.
ServedTCPPorts []filter.PortRange
// ServedUDPPorts, if non-nil, restricts which UDP ports on the server's own
// address the packet filter admits. If nil, packets to all ports reach
// OnUDP, which remains the per-flow gate either way. Ports with an
// active [Server.Listen] listener are always admitted, whether or
// not listed here.
//
// It must be set before calling Start.
ServedUDPPorts []filter.PortRange
// UDPIdleTimeout is how long an inactive incoming UDP flow remains open.
// A zero value uses [DefaultUDPIdleTimeout]. Successful reads and writes
// reset the timeout. It must be set before calling Start.
UDPIdleTimeout time.Duration
}
// ConnPacketConn is a connected datagram socket. Read and Write preserve UDP
// datagram boundaries, while the net.PacketConn methods are available to code
// that prefers packet-oriented APIs. LocalAddr and RemoteAddr identify the
// destination and source endpoints of an incoming server flow.
type ConnPacketConn interface {
net.Conn
net.PacketConn
}
// MaxUDPPayload is the largest UDP payload that fits the tunnel's 1280-byte
// IPv6 MTU without IP fragmentation (1280 minus 40 bytes of IPv6 header and 8
// bytes of UDP header). Applications should keep datagrams at or below this
// size; larger writes are not guaranteed to reach the peer.
const MaxUDPPayload = 1232
// DefaultUDPIdleTimeout is the amount of inactivity after which an incoming
// UDP flow is closed.
const DefaultUDPIdleTimeout = 2 * time.Minute
// Start connects to the DERP relay and begins accepting clients,
// first picking defaults for any unset configuration fields: a new
// ephemeral key, log.Printf for logging, and the nearest region of
// the default DERP map.
//
// It returns an error if the server was already started, including
// implicitly by [Server.Listen].
func (s *Server) Start() error {
return s.StartContext(context.Background())
}
// StartContext is Start with a context bounding relay discovery and startup.
// Cancelling ctx after startup does not stop the server; use Close instead.
func (s *Server) StartContext(ctx context.Context) error {
s.startMu.Lock()
defer s.startMu.Unlock()
return s.startLocked(ctx)
}
// startLocked implements Start, with ctx bounding the startup network
// work (fetching the DERP map and picking a region).
// s.startMu must be held.
func (s *Server) startLocked(ctx context.Context) error {
if s.lb != nil {
return errors.New("tailcat: Server.Start called twice")
}
if s.UDPIdleTimeout < 0 {
return errors.New("tailcat: Server.UDPIdleTimeout must not be negative")
}
logf := s.Logf
if logf == nil {
logf = log.Printf
}
priv := s.Key
if priv.IsZero() {
priv = key.NewNode()
}
psk := s.PresharedKey
if s.DisablePresharedKey {
psk = PresharedKey{}
} else if psk.IsZero() {
psk = NewPresharedKey()
}
if s.Hybrid {
psk = psk.ForHybrid()
}
reg := s.Region
if reg == nil {
ci := &ConnInfo{RegionID: cmp.Or(s.RegionID, -1)}
opts := []any{ExpandForServer}
if s.DERPMapURL != "" {
opts = append(opts, DERPMapURL(s.DERPMapURL))
}
if s.DERPMapCache != nil {
opts = append(opts, s.DERPMapCache)
}
if err := ci.Expand(ctx, opts...); err != nil {
return err
}
reg = ci.Region[0]
}
if reg.RegionID == 0 {
return fmt.Errorf("missing RegionID in %v", logger.AsJSON(reg))
}
lb := newLocoBackend(priv, psk)
lb.hybrid = s.Hybrid
lb.logf = logf
lb.dm = &tailcfg.DERPMap{}
mak.Set(&lb.dm.Regions, reg.RegionID, reg)
lb.allowClient = s.AllowClient
sys := &lb.sys
bus := eventbus.New()
sys.Set(bus)
sys.Set(health.NewTracker(bus))
sys.Set(newNetMon(bus, logf))
dialer := &tsdial.Dialer{Logf: logf} // mutated below (before used)
sys.Set(dialer)
var store ipn.StateStore = new(mem.Store)
sys.Set(store)
lb.isServer = true
lb.onDERPRecv = func(regionID tailcfg.DERPRegionID, src key.NodePublic, pkt []byte) bool {
if !IsMeowPacket(pkt) {
return false
}
if IsMeowedPacket(pkt) {
return true // server ignores meowed
}
if _, discoPub, ok := ParseMeowPing(pkt); ok {
inst := parseMeowInstance(pkt)
mc := lb.sys.MagicSock.Get()
go func() {
// Only reply once the client is fully added as a peer:
// "meowed" is the ack that tells the client it can
// start dialing. Disallowed clients get no reply.
if lb.onMeow(src, discoPub, inst) {
mc.SendDERPPacketTo(src, regionID, EncodeMeowed())
}
}()
return true
}
return false
}
if err := createEngine(logf, lb); err != nil {
lb.Close()
return fmt.Errorf("createEngine: %w", err)
}
ns, err := newNetstack(logf, sys)
if err != nil {
lb.Close()
return fmt.Errorf("newNetstack: %w", err)
}
ns.ProcessLocalIPs = true
ns.ProcessSubnets = true
ns.GetTCPHandlerForFlow = func(src, dst netip.AddrPort) (handler func(net.Conn), intercept bool) {
if dst.Addr() == lb.addr {
if ln := s.listenerForPort("tcp", dst.Port()); ln != nil {
return ln.handle, true
}
if s.OnTCP == nil {
return nil, true // send RST
}
return s.OnTCP(dst.Port()), true
}
if s.OnTCPForward == nil {
return nil, true // send RST
}
if nat64Prefix.Contains(dst.Addr()) {
var a4 [4]byte
d6 := dst.Addr().As16()
copy(a4[:], d6[12:16])
dst = netip.AddrPortFrom(netip.AddrFrom4(a4), dst.Port())
}
return s.OnTCPForward(dst), true
}
ns.GetUDPHandlerForFlow = func(src, dst netip.AddrPort) (handler func(nettype.ConnPacketConn), intercept bool) {
var h func(ConnPacketConn)
if dst.Addr() == lb.addr {
if ln := s.listenerForPort("udp", dst.Port()); ln != nil {
h = func(c ConnPacketConn) { ln.handle(c) }
} else if s.OnUDP != nil {
h = s.OnUDP(dst.Port())
}
} else if s.OnUDPForward != nil {
if nat64Prefix.Contains(dst.Addr()) {
var a4 [4]byte
d6 := dst.Addr().As16()
copy(a4[:], d6[12:16])
dst = netip.AddrPortFrom(netip.AddrFrom4(a4), dst.Port())
}
h = s.OnUDPForward(dst)
}
if h == nil {
return nil, true
}
return func(c nettype.ConnPacketConn) { h(newIdlePacketConn(c, s.udpIdleTimeout())) }, true
}
lb.ns = ns
sys.Set(ns)
dialer.UseNetstackForIP = func(ip netip.Addr) bool {
_, ok := lb.peerByIP(ip)
return ok
}
dialer.NetstackDialTCP = func(ctx context.Context, dst netip.AddrPort) (net.Conn, error) {
return ns.DialContextTCP(ctx, dst)
}
dialer.NetstackDialUDP = func(ctx context.Context, dst netip.AddrPort) (net.Conn, error) {
panic("unreachable from tailcat") // but required by Dialer currently
}
sys.Tun.Get().Start()
s.lb = lb
s.rebuildFilter()
if err := lb.Start(); err != nil {
s.lb = nil
lb.Close()
return err
}
return nil
}
func (s *Server) udpIdleTimeout() time.Duration {
if s.UDPIdleTimeout != 0 {
return s.UDPIdleTimeout
}
return DefaultUDPIdleTimeout
}
var allPorts = filter.PortRange{First: 0, Last: 65535}
// rebuildFilter builds and installs the packet filter. It must be
// called after s.lb is set, and again whenever the set of active
// listeners changes.
func (s *Server) rebuildFilter() {
s.listenerMu.Lock()
defer s.listenerMu.Unlock()
s.installFilterLocked()
}
// installFilterLocked builds and installs the packet filter.
// s.listenerMu must be held.
func (s *Server) installFilterLocked() {
s.lb.sys.Engine.Get().SetFilter(s.buildFilterLocked())
}
// appendListenerPorts appends one single-port range per port of m to
// ranges and returns the result.
func appendListenerPorts(ranges []filter.PortRange, m map[uint16]*listener) []filter.PortRange {
for port := range m {
ranges = append(ranges, filter.PortRange{First: port, Last: port})
}
return ranges
}
// buildFilterLocked returns the packet filter enforcing what the server is
// configured to serve: inbound TCP connections and UDP flows are admitted only
// to the server's own configured and listened-on ports, plus to any
// destination for protocols whose Forward callback is set (exit node mode).
// Everything else from the tunnel is dropped before reaching
// netstack; the OnTCP/OnTCPForward callbacks and the listener
// map remain the per-connection gates behind it.
// s.listenerMu must be held.
func (s *Server) buildFilterLocked() *filter.Filter {
lb := s.lb
selfPorts := []filter.PortRange{allPorts}
if s.ServedTCPPorts != nil {
selfPorts = appendListenerPorts(slices.Clone(s.ServedTCPPorts), s.tcpListeners)
}
var selfDsts []filter.NetPortRange
for _, pr := range selfPorts {
selfDsts = append(selfDsts, filter.NetPortRange{Net: lb.addrPrefix, Ports: pr})
}
matches := []filter.Match{{
IPProto: views.SliceOf([]ipproto.Proto{ipproto.TCP}),
Srcs: []netip.Prefix{allIPv6},
Dsts: selfDsts,
}}
if s.OnUDP != nil || len(s.udpListeners) > 0 {
var udpPorts []filter.PortRange
switch {
case s.OnUDP == nil:
// Without OnUDP, only listener ports can be served.
udpPorts = appendListenerPorts(nil, s.udpListeners)
case s.ServedUDPPorts != nil:
udpPorts = appendListenerPorts(slices.Clone(s.ServedUDPPorts), s.udpListeners)
default:
udpPorts = []filter.PortRange{allPorts}
}
udpDsts := make([]filter.NetPortRange, 0, len(udpPorts))
for _, pr := range udpPorts {
udpDsts = append(udpDsts, filter.NetPortRange{Net: lb.addrPrefix, Ports: pr})
}
matches = append(matches, filter.Match{
IPProto: views.SliceOf([]ipproto.Proto{ipproto.UDP}),
Srcs: []netip.Prefix{allIPv6},
Dsts: udpDsts,
})
}
var localNets netipx.IPSetBuilder
localNets.AddPrefix(lb.addrPrefix)
if s.OnTCPForward != nil || s.OnUDPForward != nil {
localNets.AddPrefix(allIPv6)
}
if s.OnTCPForward != nil {
matches = append(matches, filter.Match{
IPProto: views.SliceOf([]ipproto.Proto{ipproto.TCP}),
Srcs: []netip.Prefix{allIPv6},
Dsts: []filter.NetPortRange{{Net: allIPv6, Ports: allPorts}},
})
}
if s.OnUDPForward != nil {
matches = append(matches, filter.Match{
IPProto: views.SliceOf([]ipproto.Proto{ipproto.UDP}),
Srcs: []netip.Prefix{allIPv6},
Dsts: []filter.NetPortRange{{Net: allIPv6, Ports: allPorts}},
})
}
local, _ := localNets.IPSet()
// The logIPs set lets the filter log the packets it drops (the
// engine's tstun wrapper asks for drop logging by default), so a
// verbose server reports filtered connection attempts instead of
// silently eating them. Both endpoints of a flow must be in the
// set for it to be logged, so it spans the whole ULA range that
// tcAddrForKey assigns from, not just our own address.
return filter.New(matches, nil, local, tailcatULASet(), nil, lb.logf)
}
// Addr returns the server's IPv6 address derived from its public key.
// It must only be called after the server has started, via
// [Server.Start] or [Server.Listen].
func (s *Server) Addr() netip.Addr { return s.lb.addr }
// Close shuts down the server, closing any listeners created by
// [Server.Listen] along with the WireGuard engine and DERP connections.
func (s *Server) Close() error {
if s.lb == nil {
return nil // never started
}
s.listenerMu.Lock()
for _, ln := range s.tcpListeners {
ln.closeLocked(false)
}
for _, ln := range s.udpListeners {
ln.closeLocked(false)
}
s.listenerMu.Unlock()
return s.lb.Close()
}
// DrainTCP waits until every TCP connection in the server's netstack
// has fully closed, meaning the peer has acknowledged all sent data
// and the final FIN. It returns nil once drained, or ctx's error.
//
// The whole TCP stack runs inside this process, so exiting right
// after a [net.Conn] Close can lose the FIN before it is ever
// transmitted, leaving the peer waiting for an EOF that never comes.
// A process that closes a connection and then exits should first
// call DrainTCP with a timeout bounding ctx, in case the peer is
// gone and the FIN is never acknowledged.
//
// It is meant for the passive closer (the side that closes second),
// which goes straight to CLOSED once its FIN is acked. A connection
// this side closed first instead parks in TIME-WAIT and would block
// DrainTCP until the TIME-WAIT timer fires.
func (s *Server) DrainTCP(ctx context.Context) error {
// Wait blocks until the endpoint is fully closed (EventHUp).
// Non-TCP endpoints return immediately. A waiter goroutine may
// outlive an early ctx cancellation; it exits with the process
// or when its endpoint eventually closes.
for _, ep := range tcpipStackOf(s.lb.ns).RegisteredEndpoints() {
done := make(chan struct{})
go func() {
ep.Wait()
close(done)
}()
select {
case <-done:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
// DrainTCP waits until none of the client's TCP connections have
// segments left to send or retransmit. It returns nil once drained,
// or ctx's error.
//
// It is meant to be called after the last connection has been closed
// or has reached EOF. Like [Server.DrainTCP], it exists because the
// whole TCP stack runs inside this process: a client that reads the
// server's EOF and exits immediately can lose the final ACK of the
// server's FIN before it is ever transmitted, leaving the server
// retransmitting its FIN to a dead peer until it gives up.
func (c *Client) DrainTCP(ctx context.Context) error {
for {
busy := false
for _, ep := range tcpipStackOf(c.lb.ns).RegisteredEndpoints() {