Compare commits

...

2659 Commits

Author SHA1 Message Date
Andrew Lytvynov bcb55fdeb6
clientupdate: mention when Alpine system upgrade is needed (#12306)
Alpine APK repos are versioned, and contain different package sets.
Older APK releases and repos don't have the latest tailscale package.
When we report "no update available", check whether pkgs.tailscale.com
has a newer tarball release. If it does, it's possible that the system
is on an older Alpine release. Print additional messages to suggest the
user to upgrade their OS.

Fixes #11309

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 hours ago
Irbe Krumina c2a4719e9e
cmd/tailscale/cli: allow 'tailscale up' to succeed if --stateful-filtering is not explicitly set on linux (#12312)
This fixes an issue where, on containerized environments an upgrade
1.66.3 -> 1.66.4 failed with default containerboot configuration.
This was because containerboot by default runs 'tailscale up'
that requires all previously set flags to be explicitly provided
on subsequent runs and we explicitly set --stateful-filtering
to true on 1.66.3, removed that settingon 1.66.4.

Updates tailscale/tailscale#12307

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
Co-authored-by: Andrew Lytvynov <awly@tailscale.com>
10 hours ago
Andrew Dunham 36d0ac6f8e tailcfg: use strings.CutPrefix for CheckTag; add test
Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I42eddc7547a6dd50c4d5b2a9fc88a19aac9767aa
11 hours ago
ChandonPierre 0a5bd63d32
ipn/store/kubestore, cmd/containerboot: allow overriding client api server URL via ENV (#12115)
Updates tailscale/tailscale#11397

Signed-off-by: Chandon Pierre <cpierre@coreweave.com>
13 hours ago
Irbe Krumina 1ec0273473
docs/k8s: fix subnet router manifests (#12305)
In https://github.com/tailscale/tailscale/pull/11363
I changed the subnet router manifest to run in tun
mode (for performance reasons), but did not
change the security context to give it net_admin,
which is required to for the tailscale socket.

Updates tailscale/tailscale#12083

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
14 hours ago
Brad Fitzpatrick f227083539 derp: add some guardrails for derpReason metrics getting out of sync
The derp metrics got out of sync in 74eb99aed1 (2023-03).

They were fixed in 0380cbc90d (2024-05).

This adds some further guardrails (atop the previous fix) to make sure
they don't get out of sync again.

Updates #12288

Change-Id: I809061a81f8ff92f45054d0253bc13871fc71634
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
15 hours ago
Marwan Sulaiman 7e357e1636 tsweb: rename AccessLogRecord's When to Time
This change makes our access log record more consistent with the
new log/tslog package formatting of "time". Note that we can
change slog itself to call "time" "when" but we're chosing
to make this breaking change to be consistent with the std lib's
defaults.

Updates tailscale/corp#17071

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
16 hours ago
Spike Curtis 0380cbc90d
derp: fix dropReason metrics labels (#12288)
Updates #2745
Updates #7552

Signed-off-by: Spike Curtis <spike@coder.com>
17 hours ago
Anton Tolchanov 32120932a5 cmd/tailscale/cli: print node signature in `tailscale lock status`
- Add current node signature to `ipnstate.NetworkLockStatus`;
- Print current node signature in a human-friendly format as part
  of `tailscale lock status`.

Examples:

```
$ tailscale lock status
Tailnet lock is ENABLED.

This node is accessible under tailnet lock. Node signature:
SigKind: direct
Pubkey: [OTB3a]
KeyID: tlpub:44a0e23cd53a4b8acc02f6732813d8f5ba8b35d02d48bf94c9f1724ebe31c943
WrappingPubkey: tlpub:44a0e23cd53a4b8acc02f6732813d8f5ba8b35d02d48bf94c9f1724ebe31c943

This node's tailnet-lock key: tlpub:44a0e23cd53a4b8acc02f6732813d8f5ba8b35d02d48bf94c9f1724ebe31c943

Trusted signing keys:
	tlpub:44a0e23cd53a4b8acc02f6732813d8f5ba8b35d02d48bf94c9f1724ebe31c943	1	(self)
	tlpub:6fa21d242a202b290de85926ba3893a6861888679a73bc3a43f49539d67c9764	1	(pre-auth key kq3NzejWoS11KTM59)
```

For a node created via a signed auth key:

```
This node is accessible under tailnet lock. Node signature:
SigKind: rotation
Pubkey: [e3nAO]
Nested:
  SigKind: credential
  KeyID: tlpub:6fa21d242a202b290de85926ba3893a6861888679a73bc3a43f49539d67c9764
  WrappingPubkey: tlpub:3623b0412cab0029cb1918806435709b5947ae03554050f20caf66629f21220a
```

For a node that rotated its key a few times:

```
This node is accessible under tailnet lock. Node signature:
SigKind: rotation
Pubkey: [DOzL4]
Nested:
  SigKind: rotation
  Pubkey: [S/9yU]
  Nested:
    SigKind: rotation
    Pubkey: [9E9v4]
    Nested:
      SigKind: direct
      Pubkey: [3QHTJ]
      KeyID: tlpub:44a0e23cd53a4b8acc02f6732813d8f5ba8b35d02d48bf94c9f1724ebe31c943
      WrappingPubkey: tlpub:2faa280025d3aba0884615f710d8c50590b052c01a004c2b4c2c9434702ae9d0
```

Updates tailscale/corp#19764

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
23 hours ago
Andrew Lytvynov 776a05223b
ipn/ipnlocal: support c2n updates with old systemd versions (#12296)
The `--wait` flag for `systemd-run` was added in systemd 232. While it
is quite old, it doesn't hurt to special-case them and skip the `--wait`
flag. The consequence is that we lose the update command output in logs,
but at least auto-updates will work.

Fixes #12136

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 day ago
Brad Fitzpatrick 1ea100e2e5 cmd/tailscaled, ipn/conffile: support ec2 user-data config file
Updates #1412
Updates #1866

Change-Id: I4d08fb233b80c2078b3b28ffc18559baabb4a081
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 days ago
Brad Fitzpatrick 2d2b62c400 wgengine/router: probe generally-unused "ip" command style lazily
This busybox fwmaskWorks check was added before we moved away from
using the "ip" command to using netlink directly.

So it's now just wasted work (and log spam on Gokrazy) to check the
"ip" command capabilities if we're never going to use it.

Do it lazily instead.

Updates #12277

Change-Id: I8ab9acf64f9c0d8240ce068cb9ec8c0f6b1ecee7
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 days ago
Brad Fitzpatrick 909a292a8d util/linuxfw: don't try cleaning iptables on gokrazy
It just generates log spam.

Updates #12277

Change-Id: I5f65c0859e86de0a5349f9d26c9805e7c26b9371
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 days ago
Walter Poupore 0acb61fbf8
serve.go, tsnet.go: Fix "in in" typo (#12279)
Fixes #cleanup

Signed-off-by: Walter Poupore <walterp@tailscale.com>
2 days ago
Andrea Gottardo dd77111462
xcode/iOS: set MatchDomains when no route requires a custom DNS resolver (#10576)
Updates https://github.com/tailscale/corp/issues/15802.

On iOS exclusively, this PR adds logic to use a split DNS configuration in more cases, with the goal of improving battery life. Acting as the global DNS resolver on iOS should be avoided, as it leads to frequent wakes of IPNExtension.

We try to determine if we can have Tailscale only handle DNS queries for resources inside the tailnet, that is, all routes in the DNS configuration do not require a custom resolver (this is the case for app connectors, for instance).

If so, we set all Routes as MatchDomains. This enables a split DNS configuration which will help preserve battery life. Effectively, for the average Tailscale user who only relies on MagicDNS to resolve *.ts.net domains, this means that Tailscale DNS will only be used for those domains.

This PR doesn't affect users with Override Local DNS enabled. For these users, there should be no difference and Tailscale will continue acting as a global DNS resolver.

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
3 days ago
Percy Wegmann 08a9551a73 ssh/tailssh: fall back to using su when no TTY available on Linux
This allows pam authentication to run for ssh sessions, triggering
automation like pam_mkhomedir.

Updates #11854

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 days ago
Claire Wang f1d10c12ac
ipn/ipnlocal: allowed suggested exit nodes policy (#12240)
Updates tailscale/corp#19681

Signed-off-by: Claire Wang <claire@tailscale.com>
4 days ago
signed-long 5ad0dad15e
go generate directives reorder for 'make kube-generate-all' (#12210)
Fixes #11980

Signed-off-by: Michael Long <michaelongdev@gmail.com>
5 days ago
Irbe Krumina d0d33f257f
cmd/k8s-operator: add a note pointing at ProxyClass (#12246)
Updates tailscale/tailscale#12242

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 days ago
Andrew Dunham 8e4a29433f util/pool: add package for storing and using a pool of items
This can be used to implement a persistent pool (i.e. one that isn't
cleared like sync.Pool is) of items–e.g. database connections.

Some benchmarks vs. a naive implementation that uses a single map
iteration show a pretty meaningful improvement:

    $ benchstat -col /impl ./bench.txt
    goos: darwin
    goarch: arm64
    pkg: tailscale.com/util/pool
                       │    Pool     │                   map                    │
                       │   sec/op    │     sec/op      vs base                  │
    Pool_AddDelete-10    10.56n ± 2%     15.11n ±  1%    +42.97% (p=0.000 n=10)
    Pool_TakeRandom-10   56.75n ± 4%   1899.50n ± 20%  +3246.84% (p=0.000 n=10)
    geomean              24.49n          169.4n         +591.74%

Updates tailscale/corp#19900

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ie509cb65573c4726cfc3da9a97093e61c216ca18
1 week ago
James Tucker 87ee559b6f net/netcheck: apply some polish suggested from #12161
Apply some post-submit code review suggestions.

Updates #12161
Updates tailscale/corp#19106

Signed-off-by: James Tucker <james@tailscale.com>
1 week ago
Maisem Ali 9a64c06a20 all: do not depend on the testing package
Discovered while looking for something else.

Updates tailscale/corp#18935

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 week ago
Jordan Whited 4214e5f71b
logtail/backoff: update Backoff.BackOff docs (#12229)
Update #cleanup

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 week ago
James Tucker 538c2e8f7c tool/gocross: add debug data to CGO builds
We don't build a lot of tools with CGO, but we do build some, and it's
extremely valuable for production services in particular to have symbols
included - for perf and so on.

I tested various other builds that could be affected negatively, in
particular macOS/iOS, but those use split-dwarf already as part of their
build path, and Android which does not currently use gocross.

One binary which is normally 120mb only grew to 123mb, so the trade-off
is definitely worthwhile in context.

Updates tailscale/corp#20296

Signed-off-by: James Tucker <james@tailscale.com>
1 week ago
Brad Fitzpatrick 3c9be07214 cmd/derper: support TXT-mediated unpublished bootstrap DNS rollouts
Updates tailscale/coral#127

Change-Id: I2712c50630d0d1272c30305fa5a1899a19ffacef
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 week ago
Irbe Krumina 72f0f53ed0
cmd/k8s-operator: fix typo (#12217)
Fixes#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 week ago
James Tucker 9351eec3e1 net/netcheck: remove hairpin probes
Palo Alto reported interpreting hairpin probes as LAND attacks, and the
firewalls may be responding to this by shutting down otherwise in use NAT sessions
prematurely. We don't currently make use of the outcome of the hairpin
probes, and they contribute to other user confusion with e.g. the
AirPort Extreme hairpin session workaround. We decided in response to
remove the whole probe feature as a result.

Updates #188
Updates tailscale/corp#19106
Updates tailscale/corp#19116

Signed-off-by: James Tucker <james@tailscale.com>
2 weeks ago
Andrew Lytvynov c9179bc261
various: disable stateful filtering by default (#12197)
After some analysis, stateful filtering is only necessary in tailnets
that use `autogroup:danger-all` in `src` in ACLs. And in those cases
users explicitly specify that hosts outside of the tailnet should be
able to reach their nodes. To fix local DNS breakage in containers, we
disable stateful filtering by default.

Updates #12108

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
2 weeks ago
License Updater 6db1219185 licenses: update license notices
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
2 weeks ago
Charlotte Brandhorst-Satzkorn 4f4f317174 api.md: direct TOC links to new publicapi docs location
This change updates the existing api.md TOC links to point at the new
publicapi folder/files. It also removes the body of the docs from the
file, to avoid the docs becoming out of sync.

This change also renames overview.md to readme.md.

Updates tailscale/corp#19526

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 weeks ago
Brad Fitzpatrick 964282d34f ipn,wgengine: remove vestigial Prefs.AllowSingleHosts
It was requested by the first customer 4-5 years ago and only used
for a brief moment of time. We later added netmap visibility trimming
which removes the need for this.

It's been hidden by the CLI for quite some time and never documented
anywhere else.

This keeps the CLI flag, though, out of caution. It just returns an
error if it's set to anything but true (its default).

Fixes #12058

Change-Id: I7514ba572e7b82519b04ed603ff9f3bdbaecfda7
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 weeks ago
Brad Fitzpatrick 1384c24e41 control/controlclient: delete unused Client.Login Oauth2Token field
Updates #12172 (then need to update other repos)

Change-Id: I439f65e0119b09e00da2ef5c7a4f002f93558578
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 weeks ago
Andrew Dunham 47b3476eb7 util/lru: add Clear method
Updates tailscale/corp#20109

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I751a669251a70f0134dd1540c19b274a97608a93
2 weeks ago
Charlotte Brandhorst-Satzkorn c56e0c4934
publicapi: include device and user invites API documentation (#12168)
This change includes the device and user invites API docs in the
new publicapi documentation structure.

Updates tailscale/corp#19526

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 weeks ago
Jordan Whited adb7a86559
cmd/stunc: support ipv6 address targets (#12166)
Updates #cleanup

Signed-off-by: Jordan Whited <jordan@tailscale.com>
2 weeks ago
James Tucker 8d1249550a net/netcheck,wgengine/magicsock: add potential workaround for Palo Alto DIPP misbehavior
Palo Alto firewalls have a typically hard NAT, but also have a mode
called Persistent DIPP that is supposed to provide consistent port
mapping suitable for STUN resolution of public ports. Persistent DIPP
works initially on most Palo Alto firewalls, but some models/software
versions have a bug which this works around.

The bug symptom presents as follows:

- STUN sessions resolve a consistent public IP:port to start with
- Much later netchecks report the same IP:Port for a subset of
  sessions, most often the users active DERP, and/or the port related
  to sustained traffic.
- The broader set of DERPs in a full netcheck will now consistently
  observe a new IP:Port.
- After this point of observation, new inbound connections will only
  succeed to the new IP:Port observed, and existing/old sessions will
  only work to the old binding.

In this patch we now advertise the lowest latency global endpoint
discovered as we always have, but in addition any global endpoints that
are observed more than once in a single netcheck report. This should
provide viable endpoints for potential connection establishment across
a NAT with this behavior.

Updates tailscale/corp#19106

Signed-off-by: James Tucker <james@tailscale.com>
2 weeks ago
Charlotte Brandhorst-Satzkorn 6831a29f8b
publicapi: create new home for API docs and split into catagory files (#12116)
This change creates a new folder called publicapi that will become the
future home to the Tailscale public API docs.

This change also splits the existing API docs (still located in api.md)
into separate files, for easier reading and contribution.

Updates tailscale/corp#19526

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 weeks ago
Andrea Gottardo e5f67f90a2
xcode: allow ICMP ping relay on macOS + iOS platforms (#12048)
Fixes tailscale/tailscale#10393
Fixes tailscale/corp#15412
Fixes tailscale/corp#19808

On Apple platforms, exit nodes and subnet routers have been unable to relay pings from Tailscale devices to non-Tailscale devices due to sandbox restrictions imposed on our network extensions by Apple. The sandbox prevented the code in netstack.go from spawning the `ping` process which we were using.

Replace that exec call with logic to send an ICMP echo request directly, which appears to work in userspace, and not trigger a sandbox violation in the syslog.

Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
2 weeks ago
Percy Wegmann 59848fe14b drive: rewrite LOCK paths
Fixes #12097

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 weeks ago
James Tucker 87f00d76c4 tool/gocross: treat empty GOOS/GOARCH as native GOOS/GOARCH
Tracking down the side effect can otherwise be a pain, for example on
Darwin an empty GOOS resulted in CGO being implicitly disabled. The user
intended for `export GOOS=` to act like unset, and while this is a
misunderstanding, the main toolchain would treat it this way.

Fixes tailscale/corp#20059

Signed-off-by: James Tucker <james@tailscale.com>
2 weeks ago
Irbe Krumina 76c30e014d
cmd/containerboot: warn when an ingress proxy with an IPv4 tailnet address is being created for an IPv6 backend(s) (#12159)
Updates tailscale/tailscale#12156

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 weeks ago
Maisem Ali 8feb4ff5d2 version: add GitCommitTime to Meta
Updates tailscale/corp#1297

Signed-off-by: Maisem Ali <maisem@tailscale.com>
2 weeks ago
Maisem Ali 359ef61263 Revert "version: add Info func to expose EmbeddedInfo"
This reverts commit e3dec086e6.

Going to reuse Meta instead as that is already exported.

Updates tailscale/corp#1297

Signed-off-by: Maisem Ali <maisem@tailscale.com>
2 weeks ago
Sonia Appasamy 89947606b2 api.md: document device invite apis
Updates tailscale/corp#18153

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
2 weeks ago
Sonia Appasamy b094e8c925 api.md: document user invite apis
Updates tailscale/corp#18153

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
2 weeks ago
Maisem Ali e3dec086e6 version: add Info func to expose EmbeddedInfo
To be used to in a different repo.

Updates tailscale/corp#1297

Signed-off-by: Maisem Ali <maisem@tailscale.com>
2 weeks ago
Kevin Liang 7f83f9fc83 Net/DNS/Publicdns: update the IPv6 range that we use to recreate route endpoint for control D
In this commit I updated the Ipv6 range we use to generate Control D DOH ip, we were using the NextDNSRanges to generate Control D DOH ip, updated to use the correct range.

Updates: #7946
Signed-off-by: Kevin Liang <kevinliang@tailscale.com>
2 weeks ago
Brad Fitzpatrick 6877d44965 prober: plumb a now-required netmon to derphttp
Updates #11896

Change-Id: Ie2f9cd024d85b51087d297aa36c14a9b8a2b8129
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 weeks ago
Maisem Ali 1f51bb6891 net/tstun: do SNAT after filterPacketOutboundToWireGuard
In a configuration where the local node (ip1) has a different IP (ip2)
that it uses to communicate with a peer (ip3) we would do UDP flow
tracking on the `ip2->ip3` tuple. When we receive the response from
the peer `ip3->ip2` we would dnat it back to `ip3->ip1` which would
then not match the flow track state and the packet would get dropped.

To fix this, we should do flow tracking on the `ip1->ip3` tuple instead
of `ip2->ip3` which requires doing SNAT after the running filterPacketOutboundToWireGuard.

Updates tailscale/corp#19971, tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
2 weeks ago
Andrea Gottardo 60266be298
version: fix macOS uploads by increasing build number prefix (#12134)
Fixes tailscale/corp#19979

A build with version number 275 was uploaded to the App Store without bumping OSS first. The presence of that build is causing any 274.* build to be rejected. To address this, added -1 to the year component, which means new builds will use the 275.* prefix.

Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
3 weeks ago
Andrew Dunham c6d42b1093 derp: remove stats goroutine, use a timer
Without changing behaviour, don't create a goroutine per connection that
sits and sleeps, but rather use a timer that wakes up and gathers
statistics on a regular basis.

Fixes #12127

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ibc486447e403070bdc3c2cd8ae340e7d02854f21
3 weeks ago
Irbe Krumina 7ef2f72135
util/linuxfw: fix IPv6 availability check for nftables (#12009)
* util/linuxfw: fix IPv6 NAT availability check for nftables

When running firewall in nftables mode,
there is no need for a separate NAT availability check
(unlike with iptables, there are no hosts that support nftables, but not IPv6 NAT - see tailscale/tailscale#11353).
This change fixes a firewall NAT availability check that was using the no-longer set ipv6NATAvailable field
by removing the field and using a method that, for nftables, just checks that IPv6 is available.

Updates tailscale/tailscale#12008

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
3 weeks ago
Brad Fitzpatrick 8aa5c3534d ipn/ipnlocal: simplify authURL vs authURLSticky, remove interact field
The previous LocalBackend & CLI 'up' changes improved some stuff, but
might've been too aggressive in some edge cases.

This simplifies the authURL vs authURLSticky distinction and removes
the interact field, which seemed to just just be about duplicate URL
suppression in IPN bus, back from when the IPN bus was a single client
at a time. This moves that suppression to a different spot.

Fixes #12119
Updates #12028
Updates #12042

Change-Id: I1f8800b1e82ccc1c8a0d7abba559e7404ddf41e4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 weeks ago
Parker Higgins 7b3e30f391
words: add some fruit with scales (#8460)
Signed-off-by: Parker Higgins <parker@tailscale.com>
3 weeks ago
Maisem Ali 79b2d425cf types/views: move AsMap to Map from *Map
This was a typo in 2e19790f61.
It should have been on `Map` and not on `*Map` as otherwise
it doesn't allow for chaining like `someView.SomeMap().AsMap()`
and requires first assigning it to a variable.

Updates #typo

Signed-off-by: Maisem Ali <maisem@tailscale.com>
3 weeks ago
Charlotte Brandhorst-Satzkorn fc1ae97e10
words: I had a feline we were missing some words (#12098)
pspspsps

Updates #tailscale/corp#14698

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
3 weeks ago
Maisem Ali 486a423716 tsnet: split user facing and backend logging
This adds a new `UserLogf` field to the `Server` struct.
When set this any logs generated by Server are logged using
`UserLogf` and all spammy backend logs are logged to `Logf`.

If it `UserLogf` is unset, we default to `log.Printf` and
if `Logf` is unset we discard all the spammy logs.

Fixes #12094

Signed-off-by: Maisem Ali <maisem@tailscale.com>
3 weeks ago
Percy Wegmann 7209c4f91e drive: parse depth 1 PROPFIND results to include children in cache
Clients often perform a PROPFIND for the parent directory before
performing PROPFIND for specific children within that directory.
The PROPFIND for the parent directory is usually done at depth 1,
meaning that we already have information for all of the children.
By immediately adding that to the cache, we save a roundtrip to
the remote peer on the PROPFIND for the specific child.

Updates tailscale/corp#19779

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 weeks ago
Irbe Krumina d86d1e7601
cmd/k8s-operator,cmd/containerboot,ipn,k8s-operator: turn off stateful filter for egress proxies. (#12075)
Turn off stateful filtering for egress proxies to allow cluster
traffic to be forwarded to tailnet.

Allow configuring stateful filter via tailscaled config file.

Deprecate EXPERIMENTAL_TS_CONFIGFILE_PATH env var and introduce a new
TS_EXPERIMENTAL_VERSIONED_CONFIG env var that can be used to provide
containerboot a directory that should contain one or more
tailscaled config files named cap-<tailscaled-cap-version>.hujson.
Containerboot will pick the one with the newest capability version
that is not newer than its current capability version.

Proxies with this change will not work with older Tailscale
Kubernetes operator versions - users must ensure that
the deployed operator is at the same version or newer (up to
4 version skew) than the proxies.

Updates tailscale/tailscale#12061

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
Co-authored-by: Maisem Ali <maisem@tailscale.com>
3 weeks ago
Claire Wang e070af7414
ipnlocal, magicsock: add more description to storing last suggested exit (#11998)
node related functions
Updates tailscale/corp#19681

Signed-off-by: Claire Wang <claire@tailscale.com>
3 weeks ago
Andrew Dunham 5708fc0639 wgengine/router: print Docker warning when stateful filtering is enabled
When Docker is detected on the host and stateful filtering is enabled,
Docker containers may be unable to reach Tailscale nodes (depending on
the network settings of a container). Detect Docker when stateful
filtering is enabled and print a health warning to aid users in noticing
this issue.

We avoid printing the warning if the current node isn't advertising any
subnet routes and isn't an exit node, since without one of those being
true, the node wouldn't have the correct AllowedIPs in WireGuard to
allow a Docker container to connect to another Tailscale node anyway.

Updates #12070

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Idef538695f4d101b0ef6f3fb398c0eaafc3ae281
3 weeks ago
Andrew Dunham 25e32cc3ae util/linuxfw: fix table name in DelStatefulRule
Updates #12061
Follow-up to #12072

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I2ba8c4bff14d93816760ff5eaa1a16f17bad13c1
3 weeks ago
Maisem Ali 21abb7f402 cmd/tailscale: add missing set flags for linux
We were missing `snat-subnet-routes`, `stateful-filtering`
and `netfilter-mode`. Add those to set too.

Fixes #12061

Signed-off-by: Maisem Ali <maisem@tailscale.com>
3 weeks ago
Anton Tolchanov ac638f32c0 util/linuxfw: fix stateful packet filtering in nftables mode
To match iptables:
b5dbf155b1/util/linuxfw/iptables_runner.go (L536)

Updates #12066

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 weeks ago
Irbe Krumina b5dbf155b1
cmd/k8s-operator: default nameserver image to tailscale/k8s-nameserver:unstable (#11991)
We are now publishing nameserver images to tailscale/k8s-nameserver,
so we can start defaulting the images if users haven't set
them explicitly, same as we already do with proxy images.

The nameserver images are currently only published for unstable
track, so we have to use the static 'unstable' tag.
Once we start publishing to stable, we can make the operator
default to its own tag (because then we'll know that for each
operator tag X there is also a nameserver tag X as we always
cut all images for a given tag.

Updates tailscale/tailscale#10499

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
3 weeks ago
Andrew Dunham 8f7f9ac17e wgengine/netstack: handle 4via6 routes that are advertised by the same node
Previously, a node that was advertising a 4via6 route wouldn't be able
to make use of that same route; the packet would be delivered to
Tailscale, but since we weren't accepting it in handleLocalPackets, the
packet wouldn't be delivered to netstack and would never hit the 4via6
logic. Let's add that support so that usage of 4via6 is consistent
regardless of where the connection is initiated from.

Updates #11304

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic28dc2e58080d76100d73b93360f4698605af7cb
3 weeks ago
Nick O'Neill 7901925ad3
VERSION.txt: this is v1.67.0 (#12063)
Signed-off-by: Nick O'Neill <nick@tailscale.com>
3 weeks ago
Sonia Appasamy 8130656780 api.md: remove extraneous commas in json examples
Updates #cleanup

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
3 weeks ago
Anton Tolchanov 6f4a1dc6bf ipn/ipnlocal: fix another read of keyExpired outside mutex
Updates #12039

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 weeks ago
Brad Fitzpatrick e968b0ecd7 cmd/tailscale,controlclient,ipnlocal: fix 'up', deflake tests more
The CLI's "up" is kinda chaotic and LocalBackend.Start is kinda
chaotic and they both need to be redone/deleted (respectively), but
this fixes some buggy behavior meanwhile. We were previously calling
StartLoginInteractive (to start the controlclient's RegisterRequest)
redundantly in some cases, causing test flakes depending on timing and
up's weird state machine.

We only need to call StartLoginInteractive in the client if Start itself
doesn't. But Start doesn't tell us that. So cheat a bit and a put the
information about whether there's a current NodeKey in the ipn.Status.
It used to be accessible over LocalAPI via GetPrefs as a private key but
we removed that for security. But a bool is fine.

So then only call StartLoginInteractive if that bool is false and don't
do it in the WatchIPNBus loop.

Fixes #12028
Updates #12042

Change-Id: I0923c3f704a9d6afd825a858eb9a63ca7c1df294
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 weeks ago
Brad Fitzpatrick e5ef35857f ipn/ipnlocal: fix read of keyExpired outside mutex
Fixes #12039

Change-Id: I28c8a282ce12619f17103e9535841f15394ce685
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 weeks ago
Brad Fitzpatrick 21509db121 ipn/ipnlocal, all: plumb health trackers in tests
I saw some panics in CI, like:

    2024-05-08T04:30:25.9553518Z ## WARNING: (non-fatal) nil health.Tracker (being strict in CI):
    2024-05-08T04:30:25.9554043Z goroutine 801 [running]:
    2024-05-08T04:30:25.9554489Z tailscale.com/health.(*Tracker).nil(0x0)
    2024-05-08T04:30:25.9555086Z 	tailscale.com/health/health.go:185 +0x70
    2024-05-08T04:30:25.9555688Z tailscale.com/health.(*Tracker).SetUDP4Unbound(0x0, 0x0)
    2024-05-08T04:30:25.9556373Z 	tailscale.com/health/health.go:532 +0x2f
    2024-05-08T04:30:25.9557296Z tailscale.com/wgengine/magicsock.(*Conn).bindSocket(0xc0003b4808, 0xc0003b4878, {0x1fbca53, 0x4}, 0x0)
    2024-05-08T04:30:25.9558301Z 	tailscale.com/wgengine/magicsock/magicsock.go:2481 +0x12c5
    2024-05-08T04:30:25.9559026Z tailscale.com/wgengine/magicsock.(*Conn).rebind(0xc0003b4808, 0x0)
    2024-05-08T04:30:25.9559874Z 	tailscale.com/wgengine/magicsock/magicsock.go:2510 +0x16f
    2024-05-08T04:30:25.9561038Z tailscale.com/wgengine/magicsock.NewConn({0xc000063c80, 0x0, 0xc000197930, 0xc000197950, 0xc000197960, {0x0, 0x0}, 0xc000197970, 0xc000198ee0, 0x0, ...})
    2024-05-08T04:30:25.9562402Z 	tailscale.com/wgengine/magicsock/magicsock.go:476 +0xd5f
    2024-05-08T04:30:25.9563779Z tailscale.com/wgengine.NewUserspaceEngine(0xc000063c80, {{0x22c8750, 0xc0001976b0}, 0x0, {0x22c3210, 0xc000063c80}, {0x22c31d8, 0x2d3c900}, 0x0, 0x0, ...})
    2024-05-08T04:30:25.9564982Z 	tailscale.com/wgengine/userspace.go:389 +0x159d
    2024-05-08T04:30:25.9565529Z tailscale.com/ipn/ipnlocal.newTestBackend(0xc000358b60)
    2024-05-08T04:30:25.9566086Z 	tailscale.com/ipn/ipnlocal/serve_test.go:675 +0x2a5
    2024-05-08T04:30:25.9566612Z ta

Updates #11874

Change-Id: I3432ed52d670743e532be4642f38dbd6e3763b1b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 weeks ago
Brad Fitzpatrick 727c0d6cfd ipn/ipnserver: close a small race in ipnserver, ~simplify code
There was a small window in ipnserver after we assigned a LocalBackend
to the ipnserver's atomic but before we Start'ed it where our
initalization Start could conflict with API calls from the LocalAPI.

Simplify that a bit and lay out the rules in the docs.

Updates #12028

Change-Id: Ic5f5e4861e26340599184e20e308e709edec68b1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 weeks ago
Maisem Ali 32bc596062 ipn/ipnlocal: acquire b.mu once in Start
We used to Lock, Unlock, Lock, Unlock quite a few
times in Start resulting in all sorts of weird race
conditions. Simplify it all and only Lock/Unlock once.

Updates #11649

Signed-off-by: Maisem Ali <maisem@tailscale.com>
3 weeks ago
Maisem Ali 9380e2dfc6 ipn/ipnlocal: use lockAndGetUnlock in Start
This removes one of the Lock,Unlock,Lock,Unlock at least in
the Start function. Still has 3 more of these.

Updates #11649

Signed-off-by: Maisem Ali <maisem@tailscale.com>
3 weeks ago
Maisem Ali e1011f1387 ipn/ipnlocal: call SetNetInfoCallback from NewLocalBackend
Instead of calling it from Start everytime, call it from NewLocalBackend
once.

Updates #11649

Signed-off-by: Maisem Ali <maisem@tailscale.com>
3 weeks ago
Maisem Ali 85b9a6c601 net/netcheck: do not add derps if IPv4/IPv6 is set to "none"
It was documented as such but seems to have been dropped in a
refactor, restore the behavior. This brings down the time it
takes to run a single integration test by 2s which adds up
quite a bit.

Updates tailscale/corp#19786

Signed-off-by: Maisem Ali <maisem@tailscale.com>
3 weeks ago
Brad Fitzpatrick d7bdd8e2a7 go.toolchain.rev: update to Go 1.22.3
Updates #12044

Change-Id: I4ad16f2bfcec13735cb10713e028b2c5527501ed
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 weeks ago
kari-ts 3c4c9dc1d2
web: use EditPrefs instead of passing UpdatePrefs to starting (#12040)
Web version of https://github.com/tailscale/tailscale-android/pull/370
This allows us to update the prefs rather than creating new prefs

Updates tailscale/tailscale#11731

Signed-off-by: kari-ts <kari@tailscale.com>
3 weeks ago
Brad Fitzpatrick 80df8ffb85 control/controlclient: early return and outdent some code
I found this too hard to read before.

This is pulled out of #12033 as it's unrelated cleanup in retrospect.

Updates #12028

Change-Id: I727c47e573217e3d1973c5b66a76748139cf79ee
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Andrew Lytvynov 471731771c
ipn/ipnlocal: set default NoStatefulFiltering in ipn.NewPrefs (#12031)
This way the default gets populated on first start, when no existing
state exists to migrate. Also fix `ipn.PrefsFromBytes` to preserve empty
fields, rather than layering `NewPrefs` values on top.

Updates https://github.com/tailscale/corp/issues/19623

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
4 weeks ago
Paul Scott 78fa698fe6 cmd/tailscale/cli/ffcomplete: remove fullstop from ShortHelp
Updates #cleanup

Signed-off-by: Paul Scott <paul@tailscale.com>
4 weeks ago
Maisem Ali 482890b9ed tailcfg: bump capver for using NodeAttrUserDialUseRoutes for DNS
Missed in f62e678df8.

Updates tailscale/corp#18725
Updates #4529

Signed-off-by: Maisem Ali <maisem@tailscale.com>
4 weeks ago
Maisem Ali af97e7a793 tailcfg,all: add/plumb Node.IsJailed
This adds a new bool that can be sent down from control
to do jailing on the client side. Previously this would
only be done from control by modifying the packet filter
we sent down to clients. This would result in a lot of
additional work/CPU on control, we could instead just
do this on the client. This has always been a TODO which
we keep putting off, might as well do it now.

Updates tailscale/corp#19623

Signed-off-by: Maisem Ali <maisem@tailscale.com>
4 weeks ago
Maisem Ali e67069550b ipn/ipnlocal,net/tstun,wgengine: create and plumb jailed packet filter
This plumbs a packet filter for jailed nodes through to the
tstun.Wrapper; the filter for a jailed node is equivalent to a "shields
up" filter. Currently a no-op as there is no way for control to
tell the client whether a peer is jailed.

Updates tailscale/corp#19623

Co-authored-by: Andrew Dunham <andrew@du.nham.ca>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
Change-Id: I5ccc5f00e197fde15dd567485b2a99d8254391ad
4 weeks ago
Nick Khyl f62e678df8 net/dns/resolver, control/controlknobs, tailcfg: use UserDial instead of SystemDial to dial DNS servers
Now that tsdial.Dialer.UserDial has been updated to honor the configured routes
and dial external network addresses without going through Tailscale, while also being
able to dial a node/subnet router on the tailnet, we can start using UserDial to forward
DNS requests. This is primarily needed for DNS over TCP when forwarding requests
to internal DNS servers, but we also update getKnownDoHClientForProvider to use it.

Updates tailscale/corp#18725

Signed-off-by: Nick Khyl <nickk@tailscale.com>
4 weeks ago
Andrew Lytvynov c28f5767bf
various: implement stateful firewalling on Linux (#12025)
Updates https://github.com/tailscale/corp/issues/19623


Change-Id: I7980e1fb736e234e66fa000d488066466c96ec85

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Co-authored-by: Andrew Dunham <andrew@du.nham.ca>
4 weeks ago
Maisem Ali 5ef178fdca net/tstun: refactor peerConfig to allow storing more details
This refactors the peerConfig struct to allow storing more
details about a peer and not just the masq addresses. To be
used in a follow up change.

As a side effect, this also makes the DNAT logic on the inbound
packet stricter. Previously it would only match against the packets
dst IP, not it also takes the src IP into consideration. The beahvior
is at parity with the SNAT case.

Updates tailscale/corp#19623

Co-authored-by: Andrew Dunham <andrew@du.nham.ca>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
Change-Id: I5f40802bebbf0f055436eb8824e4511d0052772d
4 weeks ago
Brad Fitzpatrick f3d2fd22ef cmd/tailscale/cli: don't start WatchIPNBus until after up's initial Start
The CLI "up" command is a historical mess, both on the CLI side and
the LocalBackend side. We're getting closer to cleaning it up, but in
the meantime it was again implicated in flaky tests.

In this case, the background goroutine running WatchIPNBus was very
occasionally running enough to get to its StartLoginInteractive call
before the original goroutine did its Start call. That meant
integration tests were very rarely but sometimes logging in with the
default control plane URL out on the internet
(controlplane.tailscale.com) instead of the localhost control server
for tests.

This also might've affected new Headscale etc users on initial "up".

Fixes #11960
Fixes #11962

Change-Id: I36f8817b69267a99271b5ee78cb7dbf0fcc0bd34
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Brad Fitzpatrick aadb8d9d21 ipn/ipnlocal: don't send an empty BrowseToURL w/ WatchIPNBus NotifyInitialState
I noticed this while working on the following fix to #11962.

Updates #11962

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Change-Id: I4c5894d8899d1ae8c42f54ecfd4d05a4a7ac598c
4 weeks ago
Brad Fitzpatrick e26f76a1c4 tstest/integration: add more debugging, logs to catch flaky test
Updates #11962

Change-Id: I1ab0db69bdf8d1d535aa2cef434c586311f0fe18
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Nick Khyl caa3d7594f ipn/ipnlocal, net/tsdial: plumb routes into tsdial and use them in UserDial
We'd like to use tsdial.Dialer.UserDial instead of SystemDial for DNS over TCP.
This is primarily necessary to properly dial internal DNS servers accessible
over Tailscale and subnet routes. However, to avoid issues when switching
between Wi-Fi and cellular, we need to ensure that we don't retain connections
to any external addresses on the old interface. Therefore, we need to determine
which dialer to use internally based on the configured routes.

This plumbs routes and localRoutes from router.Config to tsdial.Dialer,
and updates UserDial to use either the peer dialer or the system dialer,
depending on the network address and the configured routes.

Updates tailscale/corp#18725
Fixes #4529

Signed-off-by: Nick Khyl <nickk@tailscale.com>
4 weeks ago
Brad Fitzpatrick ce8969d82b net/portmapper: add envknob to disable portmapper in localhost integration tests
Updates #11962

Change-Id: I8212cd814985b455d96986de0d4c45f119516cb3
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Brad Fitzpatrick 7e0dd61e61 ipn/ipnlocal, tstest/integration: add panic to catch flaky test in the act
Updates #11962

Change-Id: Ifa24b82f9c76639bfd83278a7c2fe9cf42897bbb
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
License Updater 258b5042fe licenses: update license notices
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
4 weeks ago
Brad Fitzpatrick c3c18027c6 all: make more tests pass/skip in airplane mode
Updates tailscale/corp#19786

Change-Id: Iedc6730fe91c627b556bff5325bdbaf7bf79d8e6
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Claire Wang 41f2195899
util/syspolicy: add auto exit node related keys (#11996)
Updates tailscale/corp#19681

Signed-off-by: Claire Wang <claire@tailscale.com>
4 weeks ago
Brad Fitzpatrick 1a963342c7 util/set: add Of variant of SetOf that takes variadic parameter
set.Of(1, 2, 3) is prettier than set.SetOf([]int{1, 2, 3}).

I was going to change the signature of SetOf but then I noticed its
name has stutter anyway, so I kept it for compatibility. People can
prefer to use set.Of for new code or slowly migrate.

Also add a lazy Make method, which I often find myself wanting,
without having to resort to uglier mak.Set(&set, k, struct{}{}).

Updates #cleanup

Change-Id: Ic6f3870115334efcbd65e79c437de2ad3edb7625
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Will Norris 80decd83c1 tsweb: remove redundant bumpStartIfNeeded func
Updates #12001

Signed-off-by: Will Norris <will@tailscale.com>
4 weeks ago
Maisem Ali ed843e643f types/views: add AppendStrings util func
Updates tailscale/corp#19623

Signed-off-by: Maisem Ali <maisem@tailscale.com>
4 weeks ago
Maisem Ali fd6ba43b97 types/views: remove duplicate SliceContainsFunc
We already have `(Slice[T]).ContainsFunc`.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
4 weeks ago
Will Norris 46980c9664 tsweb: ensure in-flight requests are always marked as finished
The inflight request tracker only starts recording a new bucket after
the first non-error request. Unfortunately, it's written in such a way
that ONLY successful requests are ever marked as being finished. Once a
bucket has had at least one successful request and begun to be tracked,
all subsequent error cases are never marked finished and always appear
as in-flight.

This change ensures that if a request is recorded has having been
started, we also mark it as finished at the end.

Updates tailscale/corp#19767

Signed-off-by: Will Norris <will@tailscale.com>
4 weeks ago
Percy Wegmann 817badf9ca ipn/ipnlocal: reuse transport across Taildrive remotes
This prevents us from opening a new connection on each HTTP
request.

Updates #11967

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 weeks ago
Percy Wegmann 2cf764e998 drive: actually cache results on statcache
Updates #11967

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 weeks ago
Irbe Krumina 406293682c
cmd/k8s-operator: cleanup runReconciler signature (#11993)
Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 weeks ago
Claire Wang 35872e86d2
ipnlocal, magicsock: store last suggested exit node id in local backend (#11959)
Updates tailscale/corp#19681

Signed-off-by: Claire Wang <claire@tailscale.com>
4 weeks ago
Brad Fitzpatrick b62cfc430a tstest/integration/testcontrol: fix data race
Noticed in earlier GitHub actions failure.

Fixes #11994

Change-Id: Iba8d753caaa3dacbe2da9171d96c5f99b12e62d7
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Andrew Dunham e9505e5432 ipn/ipnlocal: plumb health.Tracker into profileManager constructor
Setting the field after-the-fact wasn't working because we could migrate
prefs on creation, which would set health status for auto updates.

Updates #11986

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I41d79ebd61d64829a3a9e70586ce56f62d24ccfd
4 weeks ago
Brad Fitzpatrick e42c4396cf net/netcheck: don't spam on ICMP socket permission denied errors
While debugging a failing test in airplane mode on macOS, I noticed
netcheck logspam about ICMP socket creation permission denied errors.

Apparently macOS just can't do those, or at least not in airplane
mode. Not worth spamming about.

Updates #cleanup

Change-Id: I302620cfd3c8eabb25202d7eef040c01bd8a843c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Brad Fitzpatrick 15fc6cd966 derp/derphttp: fix netcheck HTTPS probes
The netcheck client, when no UDP is available, probes distance using
HTTPS.

Several problems:

* It probes using /derp/latency-check.
* But cmd/derper serves the handler at /derp/probe
* Despite the difference, it work by accident until c8f4dfc8c0
  which made netcheck's probe require a 2xx status code.
* in tests, we only use derphttp.Handler, so the cmd/derper-installed
  mux routes aren't preesnt, so there's no probe. That breaks
  tests in airplane mode. netcheck.Client then reports "unexpected
  HTTP status 426" (Upgrade Required)

This makes derp handle both /derp/probe and /derp/latency-check
equivalently, and in both cmd/derper and derphttp.Handler standalone
modes.

I notice this when wgengine/magicsock TestActiveDiscovery was failing
in airplane mode (no wifi). It still doesn't pass, but it gets
further.

Fixes #11989

Change-Id: I45213d4bd137e0f29aac8bd4a9ac92091065113f
4 weeks ago
Brad Fitzpatrick 1fe0983f2d cmd/derper,tstest/nettest: skip network-needing test in airplane mode
Not buying wifi on a short flight is a good way to find tests
that require network. Whoops.

Updates #cleanup

Change-Id: Ibe678e9c755d27269ad7206413ffe9971f07d298
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Brad Fitzpatrick 46f3feae96 ssh/tailssh: plumb health.Tracker in test
In prep for it being required in more places.

Updates #11874

Change-Id: Ib743205fc2a6c6ff3d2c4ed3a2b28cac79156539
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Brad Fitzpatrick 4fa6cbec27 ssh/tailssh: use ptr.To in test
Updates #cleanup

Change-Id: Ic98ba1b63c8205084b30f59f0ca343788edea5b0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Brad Fitzpatrick ee3bd4dbda derp/derphttp, net/netcheck: plumb netmon.Monitor to derp netcheck client
Fixes #11981

Change-Id: I0e15a09f93aefb3cfddbc12d463c1c08b83e09fd
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 weeks ago
Percy Wegmann a03cb866b4 drive: use secret token to authenticate access to file server on localhost
This prevents Mark-of-the-Web bypass attacks in case someone visits the
localhost WebDAV server directly.

Fixes tailscale/corp#19592

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 weeks ago
Percy Wegmann 745fb31bd4 drive: use secret token to authenticate access to file server on localhost
This prevents Mark-of-the-Web bypass attacks in case someone visits the
localhost WebDAV server directly.

Fixes tailscale/corp#19592

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 weeks ago
Percy Wegmann 07e783c7be drive: use secret token to authenticate access to file server on localhost
This prevents Mark-of-the-Web bypass attacks in case someone visits the
localhost WebDAV server directly.

Fixes tailscale/corp#19592

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 weeks ago
Percy Wegmann 3349e86c0a drive: use secret token to authenticate access to file server on localhost
This prevents Mark-of-the-Web bypass attacks in case someone visits the
localhost WebDAV server directly.

Fixes tailscale/corp#19592

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 weeks ago
Percy Wegmann 0c11fd978b drive: use secret token to authenticate access to file server on localhost
This prevents Mark-of-the-Web bypass attacks in case someone visits the
localhost WebDAV server directly.

Fixes tailscale/corp#19592

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 weeks ago
Percy Wegmann 9d22ec0ba2 drive: use secret token to authenticate access to file server on localhost
This prevents Mark-of-the-Web bypass attacks in case someone visits the
localhost WebDAV server directly.

Fixes tailscale/corp#19592

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 weeks ago
Irbe Krumina cd633a7252
cmd/k8s-operator/deploy,k8s-operator: document that metrics are unstable (#11979)
Updates#11292

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 weeks ago
Andrew Dunham f97d0ac994 net/dns/resolver: add better error wrapping
To aid in debugging exactly what's going wrong, instead of the
not-particularly-useful "dns udp query: context deadline exceeded" error
that we currently get.

Updates #3786
Updates #10768
Updates #11620
(etc.)

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I76334bf0681a8a2c72c90700f636c4174931432c
4 weeks ago
Claire Wang e0287a4b33
wgengine: add exit destination logging enable for wgengine logger (#11952)
Updates tailscale/corp#18625
Co-authored-by: Kevin Liang <kevinliang@tailscale.com>
Signed-off-by: Claire Wang <claire@tailscale.com>
4 weeks ago
Irbe Krumina 19b31ac9a6
cmd/{k8s-operator,k8s-nameserver},k8s-operator: update nameserver config with records for ingress/egress proxies (#11019)
cmd/k8s-operator: optionally update dnsrecords Configmap with DNS records for proxies.

This commit adds functionality to automatically populate
DNS records for the in-cluster ts.net nameserver
to allow cluster workloads to resolve MagicDNS names
associated with operator's proxies.

The records are created as follows:
* For tailscale Ingress proxies there will be
a record mapping the MagicDNS name of the Ingress
device and each proxy Pod's IP address.
* For cluster egress proxies, configured via
tailscale.com/tailnet-fqdn annotation, there will be
a record for each proxy Pod, mapping
the MagicDNS name of the exposed
tailnet workload to the proxy Pod's IP.

No records will be created for any other proxy types.
Records will only be created if users have configured
the operator to deploy an in-cluster ts.net nameserver
by applying tailscale.com/v1alpha1.DNSConfig.

It is user's responsibility to add the ts.net nameserver
as a stub nameserver for ts.net DNS names.
https://kubernetes.io/docs/tasks/administer-cluster/dns-custom-nameservers/#configuration-of-stub-domain-and-upstream-nameserver-using-coredns
https://cloud.google.com/kubernetes-engine/docs/how-to/kube-dns#upstream_nameservers

See also https://github.com/tailscale/tailscale/pull/11017

Updates tailscale/tailscale#10499

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 weeks ago
Maisem Ali a49ed2e145 derp,ipn/ipnlocal: stop calling rand.Seed
It's deprecated and using it gets us the old slow behavior
according to https://go.dev/blog/randv2.

> Having eliminated repeatability of the global output stream, Go 1.20
> was also able to make the global generator scale better in programs
> that don’t call rand.Seed, replacing the Go 1 generator with a very
> cheap per-thread wyrand generator already used inside the Go
> runtime. This removed the global mutex and made the top-level
> functions scale much better. Programs that do call rand.Seed fall
> back to the mutex-protected Go 1 generator.

Updates #7123

Change-Id: Ia5452e66bd16b5457d4b1c290a59294545e13291
Signed-off-by: Maisem Ali <maisem@tailscale.com>
4 weeks ago
Brad Fitzpatrick 96712e10a7 health, ipn/ipnlocal: move more health warning code into health.Tracker
In prep for making health warnings rich objects with metadata rather
than a bunch of strings, start moving it all into the same place.

We'll still ultimately need the stringified form for the CLI and
LocalAPI for compatibility but we'll next convert all these warnings
into Warnables that have severity levels and such, and legacy
stringification will just be something each Warnable thing can do.

Updates #4136

Change-Id: I83e189435daae3664135ed53c98627c66e9e53da
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Andrew Dunham be663c84c1 net/tstun: rename natConfig to peerConfig
So that we can use this for additional, non-NAT configuration without it
being confusing.

Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I1658d59c9824217917a94ee76d2d08f0a682986f
1 month ago
Andrew Dunham 10497acc95 net/tstun: refactor natConfig to not be per-family
This was a holdover from the older, pre-BART days and is no longer
necessary.

Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I71b892bab1898077767b9ff51cef33d59c08faf8
1 month ago
Andrew Lytvynov 13e1355546
scripts/installer.sh: remove unnecessary escaping in grep (#11950)
Updates #11263

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Percy Wegmann 843afe7c53 ssh/tailssh: add integration test
Updates tailscale/corp#11854

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Jonathan Nobels 45b9aa0d83
net/netmon: remove spammy log statements (#11953)
Updates tailscale/corp#18960

Tests in corp called us using the wrong logging calls.  Removed.
This is logged downstream anyway.

Signed-off-by: Jonathan Nobels <jonathan@tailscale.com>
1 month ago
Paul Scott 4c08410011 cmd/tailscale/cli: set localClient.UseSocketOnly during flag parsing
This configures localClient correctly during flag parsing, so that the --socket
option is effective when generating tab-completion results. For example, the
following would not connect to the system Tailscale for tab-completion results:

    tailscale --socket=/tmp/tailscaled.socket switch <TAB>

Updates #3793

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Paul Scott ba34943133 cmd/tailscale/cli/ffcomplete: omit and clean completion results
Updates #3793

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Jonathan Nobels fa1303d632
net/netmon: swap to swift-derived defaultRoute on macos (#11936)
Updates tailscale/corp#18960

iOS uses Apple's NetworkMonitor to track the default interface and
there's no reason we shouldn't also use this on macOS, for the same
reasons noted in the comments for why this change was made on iOS.

This eliminates the need to load and parse the routing table when
querying the defaultRouter() in almost all cases.

A slight modification here (on both platforms) to fallback to the default
BSD logic in the unhappy-path rather than making assumptions that
may not hold.  If netmon is eventually parsing AF_ROUTE and able
to give a consistently correct answer for the  default interface index,
we can fall back to that and eliminate the Swift dependency.

Signed-off-by: Jonathan Nobels <jonathan@tailscale.com>
1 month ago
Gabe Gorelick de85610be0
cmd/k8s-operator/deploy/chart: allow users to configure additional labels for the operator's Pod via Helm chart values.
cmd/k8s-operator/deploy/chart: allow users to configure additional labels for the operator's Pod via Helm chart values.

Fixes #11947

Signed-off-by: Gabe Gorelick <gabe@hightouch.io>
1 month ago
Percy Wegmann 2648d475d7 drive: don't allow DELETE on read-only shares
Fixes tailscale/corp#19646

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Brad Fitzpatrick 7455e027e9 util/slicesx: add AppendMatching
We had this in a different repo, but moving it here, as this a more
fitting package.

Updates #cleanup

Change-Id: I5fb9b10e465932aeef5841c67deba4d77d473d57
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Andrew Dunham fe009c134e ipn/ipnlocal: reset the dialPlan only when the URL is unchanged
Also, reset it in a few more places (e.g. logout, new blank profiles,
etc.) to avoid a few more cases where a pre-existing dialPlan can cause
a new Headscale server take 10+ seconds to connect.

Updates #11938

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I3095173a5a3d9720507afe4452548491e9e45a3e
1 month ago
Brad Fitzpatrick c47f9303b0 types/views: use slices.Contains{,Func}
Updates #8419

Change-Id: Ib1a9cb3fb425284b7e02684072a4e7a35975f35c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Joe Tsai 5db80cf2d8
syncs: fix AtomicValue for interface kinds (#11943)
If AtomicValue[T] is used with a T that is an interface kind,
then Store may panic if different concret types are ever stored.

Fix this by always wrapping in a concrete type.
Technically, this is only needed if T is an interface kind,
but there is no harm in doing it also for non-interface kinds.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 month ago
Irbe Krumina 44aa809cb0
cmd/{k8s-nameserver,k8s-operator},k8s-operator: add a kube nameserver, make operator deploy it (#11919)
* cmd/k8s-nameserver,k8s-operator: add a nameserver that can resolve ts.net DNS names in cluster.

Adds a simple nameserver that can respond to A record queries for ts.net DNS names.
It can respond to queries from in-memory records, populated from a ConfigMap
mounted at /config. It dynamically updates its records as the ConfigMap
contents changes.
It will respond with NXDOMAIN to queries for any other record types
(AAAA to be implemented in the future).
It can respond to queries over UDP or TCP. It runs a miekg/dns
DNS server with a single registered handler for ts.net domain names.
Queries for other domain names will be refused.

The intended use of this is:
1) to allow non-tailnet cluster workloads to talk to HTTPS tailnet
services exposed via Tailscale operator egress over HTTPS
2) to allow non-tailnet cluster workloads to talk to workloads in
the same cluster that have been exposed to tailnet over their
MagicDNS names but on their cluster IPs.

DNSConfig CRD can be used to configure
the operator to deploy kube nameserver (./cmd/k8s-nameserver) to cluster.

Updates tailscale/tailscale#10499

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
Shaw Drastin 1fe073098c
Reset dial plan when switching profile (#11933)
When switching profile, the server URL can change (e.g.
because of switching to a self-hosted headscale instance).

If it is not reset here, dial plans returned by old
server (e.g. tailscale control server) will be used to
connect to new server (e.g. self-hosted headscale server),
and the register request will be blocked by it until
timeout, leading to very slow profile switches.

Updates #11938 11938

Signed-off-by: Shaw Drastin <showier.drastic0a@icloud.com>
1 month ago
Jordan Whited a47ce618bd
net/tstun: implement env var for disabling UDP GRO on Linux (#11924)
Certain device drivers (e.g. vxlan, geneve) do not properly handle
coalesced UDP packets later in the stack, resulting in packet loss.

Updates #11026

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 month ago
Mario Minardi ec04c677c0
api.md: add documentation for new split DNS endpoints (#11922)
Add documentation for GET/PATCH/PUT `api/v2/tailnet/<ID>/dns/split-dns`.
These endpoints allow for reading, partially updating, and replacing the
split DNS settings for a given tailnet.

Updates https://github.com/tailscale/corp/issues/19483

Signed-off-by: Mario Minardi <mario@tailscale.com>
1 month ago
Andrew Lytvynov 7ba8f03936
ipn/ipnlocal: fix TestOnTailnetDefaultAutoUpdate on unsupported platforms (#11921)
Fixes #11894

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Irbe Krumina 7d9c3f9897
cmd/k8s-operator/deploy/manifests: check if IPv6 module is loaded before using it (#11867)
Before attempting to enable IPv6 forwarding in the proxy init container
check if the relevant module is found, else the container crashes
on hosts that don't have it.

Updates#11860

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
Andrew Lytvynov d02f1be46a
scripts/installer.sh: enable Alpine community repo if needed (#11837)
The tailscale package is in the community Alpine repo. Check if it's
commented out in `/etc/apk/repositories` and run `setup-apkrepos -c -1`
if it's not.

Fixes #11263

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Claire Wang 5254f6de06
tailcfg: add suggest exit node UI node attribute (#11918)
Add node attribute to determine whether or not to show suggested exit
node in UI.
Updates tailscale/corp#19515

Signed-off-by: Claire Wang <claire@tailscale.com>
1 month ago
Andrew Lytvynov ce5c80d0fe
clientupdate: exec systemctl instead of using dbus to restart (#11923)
Shell out to "systemctl", which lets us drop an extra dependency.

Updates https://github.com/tailscale/corp/issues/18935

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Fran Bull 6a0fbacc28 appc: setting AdvertiseRoutes explicitly discards app connector routes
This fixes bugs where after using the cli to set AdvertiseRoutes users
were finding that they had to restart tailscaled before the app
connector would advertise previously learned routes again. And seems
more in line with user expectations.

Fixes #11006
Signed-off-by: Fran Bull <fran@tailscale.com>
1 month ago
Fran Bull c27dc1ca31 appc: unadvertise routes when reconfiguring app connector
If the controlknob to persist app connector routes is enabled, when
reconfiguring an app connector unadvertise routes that are no longer
relevant.

Updates #11008
Signed-off-by: Fran Bull <fran@tailscale.com>
1 month ago
Fran Bull fea2e73bc1 appc: write discovered domains to StateStore
If the controlknob is on.
This will allow us to remove discovered routes associated with a
particular domain.

Updates #11008
Signed-off-by: Fran Bull <fran@tailscale.com>
1 month ago
Fran Bull 1bd1b387b2 appc: add flag shouldStoreRoutes and controlknob for it
When an app connector is reconfigured and domains to route are removed,
we would like to no longer advertise routes that were discovered for
those domains. In order to do this we plan to store which routes were
discovered for which domains.

Add a controlknob so that we can enable/disable the new behavior.

Updates #11008
Signed-off-by: Fran Bull <fran@tailscale.com>
1 month ago
Fran Bull 79836e7bfd appc: add RouteInfo struct and persist it to StateStore
Lays the groundwork for the ability to persist app connectors discovered
routes, which will allow us to stop advertising routes for a domain if
the app connector no longer monitors that domain.

Updates #11008
Signed-off-by: Fran Bull <fran@tailscale.com>
1 month ago
Andrew Dunham b2b49cb3d5 wgengine/wgcfg/nmcfg: skip expired peers
Updates tailscale/corp#19315

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I1ad0c8796efe3dd456280e51efaf81f6d2049772
1 month ago
Mario Minardi 74c399483c
api.md: explicitly set content-type headers in POST CURL examples (#11916)
Explicitly set `-H "Content-Type: application/json"` in CURL examples
for POST endpoints as the default content type used by CURL is otherwise
`application/x-www-form-urlencoded` and these endpoints expect JSON data.

Updates https://github.com/tailscale/tailscale/issues/11914

Signed-off-by: Mario Minardi <mario@tailscale.com>
1 month ago
Irbe Krumina 1452faf510
cmd/containerboot,kube,ipn/store/kubestore: allow interactive login on kube, check Secret create perms, allow empty state Secret (#11326)
cmd/containerboot,kube,ipn/store/kubestore: allow interactive login and empty state Secrets, check perms

* Allow users to pre-create empty state Secrets

* Add a fake internal kube client, test functionality that has dependencies on kube client operations.

* Fix an issue where interactive login was not allowed in an edge case where state Secret does not exist

* Make the CheckSecretPermissions method report whether we have permissions to create/patch a Secret if it's determined that these operations will be needed

Updates tailscale/tailscale#11170

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
Kristoffer Dalby 1e6cdb7d86 api.md: fix missing links after move of device posture
Updates tailscale/corp#18572

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
1 month ago
Brad Fitzpatrick b9adbe2002 net/{interfaces,netmon}, all: merge net/interfaces package into net/netmon
In prep for most of the package funcs in net/interfaces to become
methods in a long-lived netmon.Monitor that can cache things.  (Many
of the funcs are very heavy to call regularly, whereas the long-lived
netmon.Monitor can subscribe to things from the OS and remember
answers to questions it's asked regularly later)

Updates tailscale/corp#10910
Updates tailscale/corp#18960
Updates #7967
Updates #3299

Change-Id: Ie4e8dedb70136af2d611b990b865a822cd1797e5
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick 6b95219e3a net/netmon, add: add netmon.State type alias of interfaces.State
... in prep for merging the net/interfaces package into net/netmon.

This is a no-op change that updates a bunch of the API signatures ahead of
a future change to actually move things (and remove the type alias)

Updates tailscale/corp#10910
Updates tailscale/corp#18960
Updates #7967
Updates #3299

Change-Id: I477613388f09389214db0d77ccf24a65bff2199c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Irbe Krumina 45f0721530
cmd/containerboot: wait on tailscaled process only (#11897)
Modifies containerboot to wait on tailscaled process
only, not on any child process of containerboot.
Waiting on any subprocess was racing with Go's
exec.Cmd.Run, used to run iptables commands and
that starts its own subprocesses and waits on them.

Containerboot itself does not run anything else
except for tailscaled, so there shouldn't be a need
to wait on anything else.

Updates tailscale/tailscale#11593

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
Brad Fitzpatrick 3672f29a4e net/netns, net/dns/resolver, etc: make netmon required in most places
The goal is to move more network state accessors to netmon.Monitor
where they can be cheaper/cached. But first (this change and others)
we need to make sure the one netmon.Monitor is plumbed everywhere.

Some notable bits:

* tsdial.NewDialer is added, taking a now-required netmon

* because a tsdial.Dialer always has a netmon, anything taking both
  a Dialer and a NetMon is now redundant; take only the Dialer and
  get the NetMon from that if/when needed.

* netmon.NewStatic is added, primarily for tests

Updates tailscale/corp#10910
Updates tailscale/corp#18960
Updates #7967
Updates #3299

Change-Id: I877f9cb87618c4eb037cee098241d18da9c01691
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick 4f73a26ea5 ipn/ipnlocal: skip TestOnTailnetDefaultAutoUpdate on macOS for now
While it's broken.

Updates #11894

Change-Id: I24698707ffe405471a14ab2683aea7e836531da8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick 7a62dddeac net/netcheck, wgengine/magicsock: make netmon.Monitor required
This has been a TODO for ages. Time to do it.

The goal is to move more network state accessors to netmon.Monitor
where they can be cheaper/cached.

Updates tailscale/corp#10910
Updates tailscale/corp#18960
Updates #7967
Updates #3299

Change-Id: I60fc6508cd2d8d079260bda371fc08b6318bcaf1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick 4dece0c359 net/netutil: remove a use of deprecated interfaces.GetState
I'm working on moving all network state queries to be on
netmon.Monitor, removing old APIs.

Updates tailscale/corp#10910
Updates tailscale/corp#18960
Updates #7967
Updates #3299

Change-Id: If0de137e0e2e145520f69e258597fb89cf39a2a3
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick 7f587d0321 health, wgengine/magicsock: remove last of health package globals
Fixes #11874
Updates #4136

Change-Id: Ib70e6831d4c19c32509fe3d7eee4aa0e9f233564
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Jonathan Nobels 71e9258ad9
ipn/ipnlocal: fix null dereference for early suggested exit node queries (#11885)
Fixes tailscale/corp#19558

A request for the suggested exit nodes that occurs too early in the
VPN lifecycle would result in a null deref of the netmap and/or
the netcheck report.  This checks both and errors out.

Signed-off-by: Jonathan Nobels <jonathan@tailscale.com>
1 month ago
Brad Fitzpatrick 745931415c health, all: remove health.Global, finish plumbing health.Tracker
Updates #11874
Updates #4136

Change-Id: I414470f71d90be9889d44c3afd53956d9f26cd61
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick a4a282cd49 control/controlclient: plumb health.Tracker
Updates #11874
Updates #4136

Change-Id: Ia941153bd83523f0c8b56852010f5231d774d91a
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick 6d69fc137f ipn/{ipnlocal,localapi},wgengine{,/magicsock}: plumb health.Tracker
Down to 25 health.Global users. After this remains controlclient &
net/dns & wgengine/router.

Updates #11874
Updates #4136

Change-Id: I6dd1856e3d9bf523bdd44b60fb3b8f7501d5dc0d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Irbe Krumina df8f40905b
cmd/k8s-operator,k8s-operator: optionally serve tailscaled metrics on Pod IP (#11699)
Adds a new .spec.metrics field to ProxyClass to allow users to optionally serve
client metrics (tailscaled --debug) on <Pod-IP>:9001.
Metrics cannot currently be enabled for proxies that egress traffic to tailnet
and for Ingress proxies with tailscale.com/experimental-forward-cluster-traffic-via-ingress annotation
(because they currently forward all cluster traffic to their respective backends).

The assumption is that users will want to have these metrics enabled
continuously to be able to monitor proxy behaviour (as opposed to enabling
them temporarily for debugging). Hence we expose them on Pod IP to make it
easier to consume them i.e via Prometheus PodMonitor.

Updates tailscale/tailscale#11292

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
Brad Fitzpatrick 723c775dbb tsd, ipnlocal, etc: add tsd.System.HealthTracker, start some plumbing
This adds a health.Tracker to tsd.System, accessible via
a new tsd.System.HealthTracker method.

In the future, that new method will return a tsd.System-specific
HealthTracker, so multiple tsnet.Servers in the same process are
isolated. For now, though, it just always returns the temporary
health.Global value. That permits incremental plumbing over a number
of changes. When the second to last health.Global reference is gone,
then the tsd.System.HealthTracker implementation can return a private
Tracker.

The primary plumbing this does is adding it to LocalBackend and its
dozen and change health calls. A few misc other callers are also
plumbed. Subsequent changes will flesh out other parts of the tree
(magicsock, controlclient, etc).

Updates #11874
Updates #4136

Change-Id: Id51e73cfc8a39110425b6dc19d18b3975eac75ce
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick cb66952a0d health: permit Tracker method calls on nil receiver
In prep for tsd.System Tracker plumbing throughout tailscaled,
defensively permit all methods on Tracker to accept a nil receiver
without crashing, lest I screw something up later. (A health tracking
system that itself causes crashes would be no good.) Methods on nil
receivers should not be called, so a future change will also collect
their stacks (and panic during dev/test), but we should at least not
crash in prod.

This also locks that in with a test using reflect to automatically
call all methods on a nil receiver and check they don't crash.

Updates #11874
Updates #4136

Change-Id: I8e955046ebf370ec8af0c1fb63e5123e6282a9d3
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Chris Palmer 7349b274bd
safeweb: handle mux pattern collisions more generally (#11801)
Fixes #11800

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
1 month ago
Brad Fitzpatrick 5b32264033 health: break Warnable into a global and per-Tracker value halves
Previously it was both metadata about the class of warnable item as
well as the value.

Now it's only metadata and the value is per-Tracker.

Updates #11874
Updates #4136

Change-Id: Ia1ed1b6c95d34bc5aae36cffdb04279e6ba77015
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick ebc552d2e0 health: add Tracker type, in prep for removing global variables
This moves most of the health package global variables to a new
`health.Tracker` type.

But then rather than plumbing the Tracker in tsd.System everywhere,
this only goes halfway and makes one new global Tracker
(`health.Global`) that all the existing callers now use.

A future change will eliminate that global.

Updates #11874
Updates #4136

Change-Id: I6ee27e0b2e35f68cb38fecdb3b2dc4c3f2e09d68
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Claire Wang d5fc52a0f5
tailcfg: add auto exit node attribute (#11871)
Updates tailscale/corp#19515

Signed-off-by: Claire Wang <claire@tailscale.com>
1 month ago
Sonia Appasamy 18765cd4f9 release/dist/qnap: omit .qpkg.codesigning files
Updates tailscale/tailscale-qpkg#135

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
1 month ago
Percy Wegmann 955ad12489 ipn/ipnlocal: only show Taildrive peers to which ACLs grant us access
This improves convenience and security.

* Convenience - no need to see nodes that can't share anything with you.
* Security - malicious nodes can't expose shares to peers that aren't
             allowed to access their shares.

Updates tailscale/corp#19432

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Sonia Appasamy 5d4b4ffc3c release/dist/qnap: update perms for tmpDir files
Allows all users to read all files, and .sh/.cgi files to be
executable.

Updates tailscale/tailscale-qpkg#135

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
1 month ago
Lee Briggs 14ac41febc
cmd/k8s-operator,k8s-operator: proxyclass affinity (#11862)
add ability to set affinity rules to proxyclass

Updates#11861

Signed-off-by: Lee Briggs <lee@leebriggs.co.uk>
1 month ago
Anton Tolchanov 31e6bdbc82 ipn/ipnlocal: always stop the engine on auth when key has expired
If seamless key renewal is enabled, we typically do not stop the engine
(deconfigure networking). However, if the node key has expired there is
no point in keeping the connection up, and it might actually prevent
key renewal if auth relies on endpoints routed via app connectors.

Fixes tailscale/corp#5800

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 month ago
Andrea Gottardo 1d3e77f373
util/syspolicy: add ReadStringArray interface (#11857)
Fixes tailscale/corp#19459

This PR adds the ability for users of the syspolicy handler to read string arrays from the MDM solution configured on the system.

Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
1 month ago
Sonia Appasamy 0cce456ee5 release/dist/qnap: use tmp file directory for qpkg building
This change allows for the release/dist/qnap package to be used
outside of the tailscale repo (notably, will be used from corp),
by using an embedded file system for build files which gets
temporarily written to a new folder during qnap build runs.

Without this change, when used from corp, the release/dist/qnap
folder will fail to be found within the corp repo, causing
various steps of the build to fail.

The file renames in this change are to combine the build files
into a /files folder, separated into /scripts and /Tailscale.

Updates tailscale/tailscale-qpkg#135

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
1 month ago
Percy Wegmann c8e912896e wgengine/router: consolidate routes before reconfiguring router for mobile clients
This helps reduce memory pressure on tailnets with large numbers
of routes.

Updates tailscale/corp#19332

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Irbe Krumina add62af7c6
util/linuxfw,go.{mod,sum}: don't log errors when deleting non-existant chains and rules (#11852)
This PR bumps iptables to a newer version that has a function to detect
'NotExists' errors and uses that function to determine whether errors
received on iptables rule and chain clean up are because the rule/chain
does not exist- if so don't log the error.

Updates corp#19336

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
Irbe Krumina 3af0f526b8
cmd{containerboot,k8s-operator},util/linuxfw: support ExternalName Services (#11802)
* cmd/containerboot,util/linuxfw: support proxy backends specified by DNS name

Adds support for optionally configuring containerboot to proxy
traffic to backends configured by passing TS_EXPERIMENTAL_DEST_DNS_NAME env var
to containerboot.
Containerboot will periodically (every 10 minutes) attempt to resolve
the DNS name and ensure that all traffic sent to the node's
tailnet IP gets forwarded to the resolved backend IP addresses.

Currently:
- if the firewall mode is iptables, traffic will be load balanced
accross the backend IP addresses using round robin. There are
no health checks for whether the IPs are reachable.
- if the firewall mode is nftables traffic will only be forwarded
to the first IP address in the list. This is to be improved.

* cmd/k8s-operator: support ExternalName Services

 Adds support for exposing endpoints, accessible from within
a cluster to the tailnet via DNS names using ExternalName Services.
This can be done by annotating the ExternalName Service with
tailscale.com/expose: "true" annotation.
The operator will deploy a proxy configured to route tailnet
traffic to the backend IPs that service.spec.externalName
resolves to. The backend IPs must be reachable from the operator's
namespace.

Updates tailscale/tailscale#10606

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
License Updater bf46bff678 licenses: update license notices
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 month ago
Percy Wegmann b7e5122226 util/osuser: add unit test for parseGroupIds
Updates #11682

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Andrew Dunham e985c6e58f ssh/tailssh: try fetching group IDs for user with the 'id' command
Since the tailscaled binaries that we distribute are static and don't
link cgo, we previously wouldn't fetch group IDs that are returned via
NSS. Try shelling out to the 'id' command, similar to how we call
'getent', to detect such cases.

Updates #11682

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I9bdc938bd76c71bc130d44a97cc2233064d64799
1 month ago
Kristoffer Dalby 9779eb6dba api.md: move device posture api to api.md
Updates tailscale/corp#18572

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
1 month ago
Brad Fitzpatrick c07aa2cfed syncs: fix flaky test by deleting the code it tested (Watch)
Fixes #11766

Change-Id: Id5a875aab23eb1b48a57dc379d0cdd42412fd18b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Joe Tsai 63b3c82587
ipn/local: log OS-specific diagnostic information as JSON (#11700)
There is an undocumented 16KiB limit for text log messages.
However, the limit for JSON messages is 256KiB.
Even worse, logging JSON as text results in significant overhead
since each double quote needs to be escaped.

Instead, use logger.Logf.JSON to explicitly log the info as JSON.

We also modify osdiag to return the information as structured data
rather than implicitly have the package log on our behalf.
This gives more control to the caller on how to log.

Updates #7802

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 month ago
Andrew Lytvynov 06502b9048
ipn/ipnlocal: reset auto-updates if unsupported on profile load (#11838)
Prior to
1613b18f82 (diff-314ba0d799f70c8998940903efb541e511f352b39a9eeeae8d475c921d66c2ac),
nodes could set AutoUpdate.Apply=true on unsupported platforms via
`EditPrefs`. Specifically, this affects tailnets where default
auto-updates are on.

Fix up those invalid prefs on profile reload, as a migration.

Updates #11544

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Sonia Appasamy 0a84215036 release/dist/qnap: add qnap target builder
Creates new QNAP builder target, which builds go binaries then uses
docker to build into QNAP packages. Much of the docker/script code
here is pulled over from https://github.com/tailscale/tailscale-qpkg,
with adaptation into our builder structures.

The qnap/Tailscale folder contains static resources needed to build
Tailscale qpkg packages, and is an exact copy of the existing folder
in the tailscale-qpkg repo.

Builds can be run with:
```
sudo ./tool/go run ./cmd/dist build qnap
```

Updates tailscale/tailscale-qpkg#135

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
1 month ago
Andrew Lytvynov b743b85dad
ipn/ipnlocal,ssh/tailssh: reject c2n /update if SSH conns are active (#11820)
Since we already track active SSH connections, it's not hard to
proactively reject updates until those finish. We attempt to do the same
on the control side, but the detection latency for new connections is in
the minutes, which is not fast enough for common short sessions.

Handle a `force=true` query parameter to override this behavior, so that
control can still trigger an update on a server where some long-running
abandoned SSH session is open.

Updates https://github.com/tailscale/corp/issues/18556

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Brad Fitzpatrick 5100bdeba7 types/persist: remove unused field Persist.Provider
It was only obviously unused after the previous change, c39cde79d.

Updates #19334

Change-Id: I9896d5fa692cb4346c070b4a339d0d12340c18f7
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick c39cde79d2 tailcfg: remove some unused fields from RegisterResponseAuth
Fixes #19334

Change-Id: Id6463f28af23078a7bc25b9280c99d4491bd9651
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Brad Fitzpatrick 05bfa022f2 tailcfg: pointerify RegisterRequest.Auth, omitemptify RegisterResponseAuth
We were storing server-side lots of:

    "Auth":{"Provider":"","LoginName":"","Oauth2Token":null,"AuthKey":""},

That was about 7% of our total storage of pending RegisterRequest
bodies.

Updates tailscale/corp#19327

Change-Id: Ib73842759a2b303ff5fe4c052a76baea0d68ae7d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Andrew Dunham 375617c5c8 net/tsdial: assume all connections are affected if no default route is present
If this happens, it results in us pessimistically closing more
connections than might be necessary, but is more correct since we won't
"miss" a change to the default route interface and keep trying to send
data over a nonexistent interface, or one that can't reach the internet.

Updates tailscale/corp#19124

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ia0b8b04cb8cdcb0da0155fd08751c9dccba62c1a
1 month ago
Nick Khyl 9e1c86901b wgengine\router: fix the Tailscale-In firewall rule to work on domain networks
The Network Location Awareness service identifies networks authenticated against
an Active Directory domain and categorizes them as "Domain Authenticated".
This includes the Tailscale network if a Domain Controller is reachable through it.

If a network is categories as NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED,
it is not possible to override its category, and we shouldn't attempt to do so.
Additionally, our Windows Firewall rules should be compatible with both private
and domain networks.

This fixes both issues.

Fixes #11813

Signed-off-by: Nick Khyl <nickk@tailscale.com>
1 month ago
Andrew Lytvynov bff527622d
ipn/ipnlocal,clientupdate: disallow auto-updates in containers (#11814)
Containers are typically immutable and should be updated as a whole (and
not individual packages within). Deny enablement of auto-updates in
containers.

Also, add the missing check in EditPrefs in LocalAPI, to catch cases
like tailnet default auto-updates getting enabled for nodes that don't
support it.

Updates #11544

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Andrew Lytvynov b3fb3bf084
clientupdate: return OS-specific version from LatestTailscaleVersion (#11812)
We don't always have the same latest version for all platforms (like
with 1.64.2 is only Synology+Windows), so we should use the OS-specific
result from pkgs JSON response instead of the main Version field.

Updates #11795

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Irbe Krumina bbe194c80d
cmd/k8s-operator: correctly determine cluster domain (#11512)
Kubernetes cluster domain defaults to 'cluster.local', but can also be customized.
We need to determine cluster domain to set up in-cluster forwarding to our egress proxies.
This was previously hardcoded to 'cluster.local', so was the egress proxies were not usable in clusters with custom domains.
This PR ensures that we attempt to determine the cluster domain by parsing /etc/resolv.conf.
In case the cluster domain cannot be determined from /etc/resolv.conf, we fall back to 'cluster.local'.

Updates tailscale/tailscale#10399,tailscale/tailscale#11445

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
Percy Wegmann d16c1293e9 ipn/ipnlocal: remove origin and referer headers from Taildrive requests
peerapi does not want these, but rclone includes them.
Removing them allows rclone to work with Taildrive configured
as a WebDAV remote.

Updates #cleanup

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Percy Wegmann 94c0403104 ipn/ipnlocal: strip origin and referer headers from Taildrive requests
peerapi does not want these, but rclone includes them.
Stripping them out allows rclone to work with Taildrive configured
as a WebDAV remote.

Updates #cleanup

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Percy Wegmann 787f8c08ec drive: rewrite Location headers
This ensures that MOVE, LOCK and any other verbs that use the Location
header work correctly.

Fixes #11758

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Claire Wang c24f2eee34
tailcfg: rename exit node destination network flow log node attribute (#11779)
Updates tailscale/corp#18625

Signed-off-by: Claire Wang <claire@tailscale.com>
1 month ago
kari-ts 048cb61dd0
interfaces: create android impl (#11784)
-Move Android impl into interfaces_android.go
-Instead of using ip route to get the interface name, use the one passed in by Android (ip route is restricted in Android 13+ per termux/termux-app#2993)

Follow-up will be to do the same for router

Fixes tailscale/corp#19215
Fixes tailscale/corp#19124

Signed-off-by: kari-ts <kari@tailscale.com>
1 month ago
Aaron Klotz 7132b782d4 hostinfo: use Distro field for distinguishing Windows Server builds
Some editions of Windows server share the same build number as their
client counterpart; we must use an additional field found in the OS
version information to distinguish between them.

Even though "Distro" has Linux connotations, it is the most appropriate
hostinfo field. What is Windows Server if not an alternate distribution
of Windows? This PR populates Distro with "Server" when applicable.

Fixes #11785

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 month ago
Percy Wegmann 02c6af2a69 cmd/tailscale: clarify Taildrive grants in help text
Fixes #cleanup

Signed-off-by: Percy Wegmann <percy@tailscale.com>
1 month ago
Chris Palmer bdfaef4879
safeweb: allow object-src: self in CSP (#11782)
This change is safe (self is still safe, by
definition), and makes the code match the comment.

Updates #cleanup

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
1 month ago
Andrew Lytvynov e775de3c63
go.mod: bump golang.org/x/net (#11775)
One more place to pick up a fix for
https://pkg.go.dev/vuln/GO-2024-2687.

Updates https://github.com/tailscale/corp/issues/18893

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Adrian Dewhurst c8b0adb382 docs/windows/policy: add missing key expiration warning interval
Fixes #11345

Change-Id: Ib53b639690b77d1b7d857304dca2119f197227ce
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
1 month ago
Brad Fitzpatrick 03d5d1f0f9 wgengine/magicsock: disable portmapper in tunchan-faked tests
Most of the magicsock tests fake the network, simulating packets going
out and coming in. There's no reason to actually hit your router to do
UPnP/NAT-PMP/PCP during in tests. But while debugging thousands of
iterations of tests to deflake some things, I saw it slamming my
router. This stops that.

Updates #11762

Change-Id: I59b9f48f8f5aff1fa16b4935753d786342e87744
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
Andrew Lytvynov 22bd506129
ipn/ipnlocal: hold the mutex when in onTailnetDefaultAutoUpdate (#11786)
Turns out, profileManager is not safe for concurrent use and I missed
all the locking infrastructure in LocalBackend, oops.

I was not able to reproduce the race even with `go test -count 100`, but
this seems like an obvious fix.

Fixes #11773

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Chris Palmer 88a7767492
safeweb: set SameSite=Strict, with an option for Lax (#11781)
Fixes #11780

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
1 month ago
dependabot[bot] dd48cad89a build(deps-dev): bump vite from 5.1.4 to 5.1.7 in /client/web
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 5.1.4 to 5.1.7.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.1.7/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.1.7/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
1 month ago
Andrew Dunham b85c2b2313 net/dns/resolver: use SystemDial in DoH forwarder
This ensures that we close the underlying connection(s) when a major
link change happens. If we don't do this, on mobile platforms switching
between WiFi and cellular can result in leftover connections in the
http.Client's connection pool which are bound to the "wrong" interface.

Updates #10821
Updates tailscale/corp#19124

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ibd51ce2efcaf4bd68e14f6fdeded61d4e99f9a01
1 month ago
Paul Scott 82394debb7 cmd/tailscale: add shell tab-completion
The approach is lifted from cobra: `tailscale completion bash` emits a bash
script for configuring the shell's autocomplete:

    . <( tailscale completion bash )

so that typing:

    tailscale st<TAB>

invokes:

    tailscale completion __complete -- st

RELNOTE=tailscale CLI now supports shell tab-completion

Fixes #3793

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Brad Fitzpatrick 21a0fe1b9b ipn/store: omit AWS & Kubernetes support on 'small' Linux GOARCHes
This removes AWS and Kubernetes support from Linux binaries by default
on GOARCH values where people don't typically run on AWS or use
Kubernetes, such as 32-bit mips CPUs.

It primarily focuses on optimizing for the static binaries we
distribute. But for people building it themselves, they can set
ts_kube or ts_aws (the opposite of ts_omit_kube or ts_omit_aws) to
force it back on.

Makes tailscaled binary ~2.3MB (~7%) smaller.

Updates #7272, #10627 etc

Change-Id: I42a8775119ce006fa321462cb2d28bc985d1c146
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 month ago
dependabot[bot] 449be38e03
build(deps): bump google.golang.org/protobuf from 1.32.0 to 1.33.0 (#11410)
* build(deps): bump google.golang.org/protobuf from 1.32.0 to 1.33.0

Bumps google.golang.org/protobuf from 1.32.0 to 1.33.0.

---
updated-dependencies:
- dependency-name: google.golang.org/protobuf
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

* cmd/{derper,stund}: update depaware.txt

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Andrew Lytvynov <awly@tailscale.com>
1 month ago
Irbe Krumina 3ef7f895c8
go.{mod,sum}: bump nftables to the latest commit (#11772)
Updates#deps

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
1 month ago
Andrew Dunham 226486eb9a net/interfaces: handle removed interfaces in State.Equal
This wasn't previously handling the case where an interface in s2 was
removed and not present in s1, and would cause the Equal method to
incorrectly return that the states were equal.

Updates tailscale/corp#19124

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I3af22bc631015d1ddd0a1d01bfdf312161b9532d
1 month ago
Paul Scott 454a03a766 cmd/tailscale/cli: prepend "tailscale" to usage errors
Updates #11626

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Paul Scott d07ede461a cmd/tailscale/cli: fix "subcommand required" errors when typod
Fixes #11672

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Paul Scott 3ff3445e9d cmd/tailscale/cli: improve ShortHelp/ShortUsage unit test, fix new errors
Updates #11364

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Paul Scott eb34b8a173 cmd/tailscale/cli: remove explicit usageFunc - its default
Updates #cleanup

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Paul Scott a50e4e604e cmd/tailscale/cli: remove duplicate "tailscale " in drive subcmd usage
Updates #cleanup

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Paul Scott 62d4be873d cmd/tailscale/cli: fix drive --help usage identation
Updates #cleanup

Signed-off-by: Paul Scott <paul@tailscale.com>
1 month ago
Brad Fitzpatrick 7c1d6e35a5 all: use Go 1.22 range-over-int
Updates #11058

Change-Id: I35e7ef9b90e83cac04ca93fd964ad00ed5b48430
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 068db1f972 net/interfaces: delete unused unexported function
It should've been deleted in 11ece02f52.

Updates #9040

Change-Id: If8a136bdb6c82804af658c9d2b0a8c63ce02d509
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Jonathan Nobels 7e2b4268d6
ipn/{localapi, ipnlocal}: forget the prior exit node when localAPI is used to zero the ExitNodeID (#11681)
Updates tailscale/corp#18724

When localAPI clients directly set ExitNodeID to "", the expected behaviour is that the prior exit node also gets zero'd - effectively setting the UI state back to 'no exit node was ever selected'

The IntenalExitNodePrior has been changed to be a non-opaque type, as it is read by the UI to render the users last selected exit node, and must be concrete. Future-us can either break this, or deprecate it and replace it with something more interesting.

Signed-off-by: Jonathan Nobels <jonathan@tailscale.com>
2 months ago
Brad Fitzpatrick 0fba9e7570 cmd/tailscale/cli: prevent concurrent Start calls in 'up'
Seems to deflake tstest/integration tests. I can't reproduce it
anymore on one of my VMs that was consistently flaking after a dozen
runs before. Now I can run hundreds of times.

Updates #11649
Fixes #7036

Change-Id: I2f7d4ae97500d507bdd78af9e92cd1242e8e44b8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Irbe Krumina 26f9bbc02b
cmd/k8s-operator,k8s-operator: document tailscale.com Custom Resource Definitions better. (#11665)
Updates tailscale/tailscale#10880

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Adrian Dewhurst ca5cb41b43 tailcfg: document use of CapMap for peers
Updates tailscale/corp#17516
Updates #11508

Change-Id: Iad2dafb38ffb9948bc2f3dfaf9c268f7d772cf56
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
2 months ago
Brad Fitzpatrick 3c1e2bba5b ipn/ipnlocal: remove outdated iOS hacky workaround in Start
We haven't needed this hack for quite some time Andrea says.

Updates #11649

Change-Id: Ie854b7edd0a01e92495669daa466c7c0d57e7438
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick dd6c76ea24 ipn: remove unused Options.LegacyMigrationPrefs
I'm on a mission to simplify LocalBackend.Start and its locking
and deflake some tests.

I noticed this hasn't been used since March 2023 when it was removed
from the Windows client in corp 66be796d33c.

So, delete.

Updates #11649

Change-Id: I40f2cb75fb3f43baf23558007655f65a8ec5e1b2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 7ec0dc3834 ipn/ipnlocal: make StartLoginInteractive take (yet unused) context
In prep for future fix to undermentioned issue.

Updates tailscale/tailscale#7036

Change-Id: Ide114db917dcba43719482ffded6a9a54630d99e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Claire Wang 9171b217ba
cmd/tailscale, ipn/ipnlocal: add suggest exit node CLI option (#11407)
Updates tailscale/corp#17516

Signed-off-by: Claire Wang <claire@tailscale.com>
2 months ago
Charlotte Brandhorst-Satzkorn 449f46c207
wgengine/magicsock: rebind/restun if a syscall.EPERM error is returned (#11711)
We have seen in macOS client logs that the "operation not permitted", a
syscall.EPERM error, is being returned when traffic is attempted to be
sent. This may be caused by security software on the client.

This change will perform a rebind and restun if we receive a
syscall.EPERM error on clients running darwin. Rebinds will only be
called if we haven't performed one specifically for an EPERM error in
the past 5 seconds.

Updates #11710

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 months ago
Will Norris 14c8b674ea Revert "licenses: add gliderlabs/ssh license"
The gliderlabs/ssh license is actually already included in the standard
package listing.  I'm not sure why I thought it wasn't.

Updates tailscale/corp#5780

This reverts commit 11dca08e93.

Signed-off-by: Will Norris <will@tailscale.com>
2 months ago
Brad Fitzpatrick 952e06aa46 wgengine/router: don't attempt route cleanup on Synology
Trying to run iptables/nftables on Synology pauses for minutes with
lots of errors and ultimately does nothing as it's not used and we
lack permissions.

This fixes a regression from db760d0bac (#11601) that landed
between Synology testing on unstable 1.63.110 and 1.64.0 being cut.

Fixes #11737

Change-Id: Iaf9563363b8e45319a9b6fe94c8d5ffaecc9ccef
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Irbe Krumina 38fb23f120
cmd/k8s-operator,k8s-operator: allow users to configure proxy env vars via ProxyClass (#11743)
Adds new ProxyClass.spec.statefulSet.pod.{tailscaleContainer,tailscaleInitContainer}.Env field
that allow users to provide key, value pairs that will be set as env vars for the respective containers.
Allow overriding all containerboot env vars,
but warn that this is not supported and might break (in docs + a warning when validating ProxyClass).

Updates tailscale/tailscale#10709

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Brad Fitzpatrick 9258bcc360 Makefile: fix default SYNO_ARCH in Makefile
It was broken with the move to dist in 32e0ba5e68 which doesn't accept
amd64 anymore.

Updates #cleanup

Change-Id: Iaaaba2d73c6a09a226934fe8e5c18b16731ee7a6
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick b9aa7421d6 ipn/ipnlocal: remove some dead code (legacyBackend methods) from LocalBackend
Nothing used it.

Updates #11649

Change-Id: Ic1c331d947974cd7d4738ff3aafe9c498853689e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick a6739c49df paths: set default state path on AIX
Updates #11361

Change-Id: I196727a540be6b7c75303f9958490b1d76189fd6
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 271cfdb3d3 util/syspolicy: clean up doc grammar and consistency
Updates #cleanup

Change-Id: I912574cbd5ef4d8b7417b8b2a9b9a2ccfef88840
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick bad3159b62 ipn/ipnlocal: delete useless SetControlClientGetterForTesting use
Updates #11649

Change-Id: I56c069b9c97bd3e30ff87ec6655ec57e1698427c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 8186cd0349 ipn/ipnlocal: delete redundant TestStatusWithoutPeers
We have tstest/integration nowadays.

And this test was one of the lone holdouts using the to-be-nuked
SetControlClientGetterForTesting.

Updates #11649

Change-Id: Icf8a6a2e9b8ae1ac534754afa898c00dc0b7623b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 68043a17c2 ipn/ipnlocal: centralize assignments to cc + ccAuto in new method
cc vs ccAuto is a mess. It needs to go. But this is a baby step towards
getting there.

Updates #11649

Change-Id: I34f33934844e580bd823a7d8f2b945cf26c87b3b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 970b1e21d0 ipn/ipnlocal: inline assertClientLocked into its now sole caller
Updates #11649

Change-Id: I8e2a5e59125a0cad5c0a8c9ed8930585f1735d03
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 170c618483 ipn/ipnlocal: remove dead code now that Android uses LocalAPI instead
The new Android app and its libtailscale don't use this anymore;
it uses LocalAPI like other clients now.

Updates #11649

Change-Id: Ic9f42b41e0e0280b82294329093dc6c275f41d50
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Flakes Updater 65f215115f go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
2 months ago
Brad Fitzpatrick a1abd12f35 cmd/tailscaled, net/tstun: build for aix/ppc64
At least in userspace-networking mode.

Fixes #11361

Change-Id: I78d33f0f7e05fe9e9ee95b97c99b593f8fe498f2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
kari-ts 1cd51f95c7
ipnlocal: enable allow LAN for android (#11709)
Updates tailscale/corp#18984
Updates tailscale/corp#18202
2 months ago
Claire Wang 976d3c7b5f
tailcfg: add exit destination for network flow logs node attribute (#11698)
Updates tailscale/corp#18625

Signed-off-by: Claire Wang <claire@tailscale.com>
2 months ago
Joe Tsai 7a77a2edf1
logtail: optimize JSON processing (#11671)
Changes made:

* Avoid "encoding/json" for JSON processing, and instead use
"github.com/go-json-experiment/json/jsontext".
Use jsontext.Value.IsValid for validation, which is much faster.
Use jsontext.AppendQuote instead of our own JSON escaping.

* In drainPending, use a different maxLen depending on lowMem.
In lowMem mode, it is better to perform multiple uploads
than it is to construct a large body that OOMs the process.

* In drainPending, if an error is encountered draining,
construct an error message in the logtail JSON format
rather than something that is invalid JSON.

* In appendTextOrJSONLocked, use jsontext.Decoder to check
whether the input is a valid JSON object. This is faster than
the previous approach of unmarshaling into map[string]any and
then re-marshaling that data structure.
This is especially beneficial for network flow logging,
which produces relatively large JSON objects.

* In appendTextOrJSONLocked, enforce maxSize on the input.
If too large, then we may end up in a situation where the logs
can never be uploaded because it exceeds the maximum body size
that the Tailscale logs service accepts.

* Use "tailscale.com/util/truncate" to properly truncate a string
on valid UTF-8 boundaries.

* In general, remove unnecessary spaces in JSON output.

Performance:

    name       old time/op    new time/op    delta
    WriteText     776ns ± 2%     596ns ± 1%   -23.24%  (p=0.000 n=10+10)
    WriteJSON     110µs ± 0%       9µs ± 0%   -91.77%  (p=0.000 n=8+8)

    name       old alloc/op   new alloc/op   delta
    WriteText      448B ± 0%        0B       -100.00%  (p=0.000 n=10+10)
    WriteJSON    37.9kB ± 0%     0.0kB ± 0%   -99.87%  (p=0.000 n=10+10)

    name       old allocs/op  new allocs/op  delta
    WriteText      1.00 ± 0%      0.00       -100.00%  (p=0.000 n=10+10)
    WriteJSON     1.08k ± 0%     0.00k ± 0%   -99.91%  (p=0.000 n=10+10)

For text payloads, this is 1.30x faster.
For JSON payloads, this is 12.2x faster.

Updates #cleanup
Updates tailscale/corp#18514

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2 months ago
Aaron Klotz 4d5d669cd5 net/dns: unconditionally write NRPT rules to local settings
We were being too aggressive when deciding whether to write our NRPT rules
to the local registry key or the group policy registry key.

After once again reviewing the document which calls itself a spec
(see issue), it is clear that the presence of the DnsPolicyConfig subkey
is the important part, not the presence of values set in the DNSClient
subkey. Furthermore, a footnote indicates that the presence of
DnsPolicyConfig in the GPO key will always override its counterpart in
the local key. The implication of this is important: we may unconditionally
write our NRPT rules to the local key. We copy our rules to the policy
key only when it contains NRPT rules belonging to somebody other than us.

Fixes https://github.com/tailscale/corp/issues/19071

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2 months ago
License Updater 9d021579e7 licenses: update license notices
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
2 months ago
Will Norris 11dca08e93 licenses: add gliderlabs/ssh license
This package is included in the tempfork directory, rather than as a go
module dependency, so is not included in the normal package list.

Updates tailscale/corp#5780

Signed-off-by: Will Norris <will@tailscale.com>
2 months ago
Jenny Zhang 2207643312 VERSION.txt: this is v1.65.0
Signed-off-by: Jenny Zhang <jz@tailscale.com>
2 months ago
Jenny Zhang 09524b58f3 VERSION.txt: this is v1.64.0
Signed-off-by: Jenny Zhang <jz@tailscale.com>
2 months ago
James Tucker a2eb1c22b0 wgengine/magicsock: allow disco communication without known endpoints
Just because we don't have known endpoints for a peer does not mean that
the peer should become unreachable. If we know the peers key, it should
be able to call us, then we can talk back via whatever path it called us
on. First step - don't drop the packet in this context.

Updates tailscale/corp#19106

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Patrick O'Doherty 7f4cda23ac
scripts/installer.sh: add rpm GPG key import (#11686)
Extend the `zypper` install to import importing the GPG key used to sign
the repository packages.

Updates #11635

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
2 months ago
James Tucker 8fa3026614 tsweb: switch to fastuuid for request ID generation
Request ID generation appears prominently in some services cumulative
allocation rate, and while this does not eradicate this issue (the API
still makes UUID objects), it does improve the overhead of this API and
reduce the amount of garbage that it produces.

Updates tailscale/corp#18266
Updates tailscale/corp#19054

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
James Tucker d0f3fa7d7e util/fastuuid: add a more efficient uuid generator
This still generates github.com/google/uuid UUID objects, but does so
using a ChaCha8 CSPRNG from the stdlib rand/v2 package. The public API
is backed by a sync.Pool to provide good performance in highly
concurrent operation.

Under high load the read API produces a lot of extra garbage and
overhead by way of temporaries and syscalls. This implementation reduces
both to minimal levels, and avoids any long held global lock by
utilizing sync.Pool.

Updates tailscale/corp#18266
Updates tailscale/corp#19054

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
James Tucker db760d0bac cmd/tailscaled: move cleanup to an implicit action during startup
This removes a potentially increased boot delay for certain boot
topologies where they block on ExecStartPre that may have socket
activation dependencies on other system services (such as
systemd-resolved and NetworkManager).

Also rename cleanup to clean up in affected/immediately nearby places
per code review commentary.

Fixes #11599

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Nick Khyl 8d83adde07 util/winutil/winenv: add package for current Windows environment details
Package winenv provides information about the current Windows environment.
This includes details such as whether the device is a server or workstation,
and if it is AD domain-joined, MDM-registered, or neither.

Updates tailscale/corp#18342

Signed-off-by: Nick Khyl <nickk@tailscale.com>
2 months ago
Paul Scott da4e92bf01 cmd/tailscale/cli: prefix all --help usages with "tailscale ...", some tidying
Also capitalises the start of all ShortHelp, allows subcommands to be hidden
with a "HIDDEN: " prefix in their ShortHelp, and adds a TS_DUMP_HELP envknob
to look at all --help messages together.

Fixes #11664

Signed-off-by: Paul Scott <paul@tailscale.com>
2 months ago
Percy Wegmann 9da135dd64 cmd/tailscale/cli: moved share.go to drive.go
Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Percy Wegmann 1e0ebc6c6d cmd/tailscale/cli: rename share command to drive
Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Joe Tsai b4ba492701
logtail: require Buffer.Write to not retain the provided slice (#11617)
Buffer.Write has the exact same signature of io.Writer.Write.
The latter requires that implementations to never retain
the provided input buffer, which is an expectation that most
users will have when they see a Write signature.

The current behavior of Buffer.Write where it does retain
the input buffer is a risky precedent to set.
Switch the behavior to match io.Writer.Write.

There are only two implementations of Buffer in existence:
* logtail.memBuffer
* filch.Filch

The former can be fixed by cloning the input to Write.
This will cause an extra allocation in every Write,
but we can fix that will pooling on the caller side
in a follow-up PR.

The latter only passes the input to os.File.Write,
which does respect the io.Writer.Write requirements.

Updates #cleanup
Updates tailscale/corp#18514

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2 months ago
Irbe Krumina 231e44e742
Revert "cmd/{k8s-nameserver,k8s-operator},k8s-operator: add a kube nameserver, make operator deploy it (#11017)" (#11669)
Temporarily reverting this PR to avoid releasing
half finished featue.

This reverts commit 9e2f58f846.

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Andrea Gottardo 0001237253 docs/policy: update ADMX and ADML files with new Windows 1.62 syspolicies
Updates ENG-2776

Updates the .admx and .adml files to include the new ManagedByOrganizationName, ManagedByCaption and ManagedByURL system policies, added in Tailscale v1.62 for Windows.

Co-authored-by: Andrea Gottardo <andrea@gottardo.me>
Signed-off-by: Nick Khyl <nickk@tailscale.com>
2 months ago
Brad Fitzpatrick b27238b654 derp/derphttp: don't block in LocalAddr method
The derphttp.Client mutex is held during connects (for up to 10
seconds) so this LocalAddr method (blocking on said mutex) could also
block for up to 10 seconds, causing a pileup upstream in
magicsock/wgengine and ultimately a watchdog timeout resulting in a
crash.

Updates #11519

Change-Id: Idd1d94ee00966be1b901f6899d8b9492f18add0f
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick e6983baa73
cmd/tailscale/cli: fix macOS crash reading envknob in init (#11667)
And add a test.

Regression from a5e1f7d703

Fixes tailscale/corp#19036

Change-Id: If90984049af0a4820c96e1f77ddf2fce8cb3043f

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Chloé Vulquin 0f3a292ebd
cli/configure: respect $KUBECONFIG (#11604)
cmd/tailscale/cli: respect $KUBECONFIG

* `$KUBECONFIG` is a `$PATH`-like: it defines a *list*.
`tailscale config kubeconfig` works like the rest of the
ecosystem so that if $KUBECONFIG is set it will write to the first existant file in the list, if none exist then
the final entry in the list.
* if `$KUBECONFIG` is an empty string, the old logic takes over.

Notes:

* The logic for file detection is inlined based on what `kind` does.
Technically it's a race condition, since the file could be removed/added
in between the processing steps, but the fallout shouldn't be too bad.
https://github.com/kubernetes-sigs/kind/blob/v0.23.0-alpha/pkg/cluster/internal/kubeconfig/internal/kubeconfig/paths.go

* The sandboxed (App Store) variant relies on a specific temporary
entitlement to access the ~/.kube/config file.
The entitlement is only granted to specific files, and so is not
applicable to paths supplied by the user at runtime.
While there may be other ways to achieve this access to arbitrary
kubeconfig files, it's out of scope for now.

Updates #11645

Signed-off-by: Chloé Vulquin <code@toast.bunkerlabs.net>
2 months ago
Brad Fitzpatrick c71e8db058 cmd/tailscale/cli: stop spamming os.Stdout/os.Stderr in tests
After:

    bradfitz@book1pro tailscale.com % ./tool/go test -c ./cmd/tailscale/cli
    bradfitz@book1pro tailscale.com % ./cli.test
    bradfitz@book1pro tailscale.com %

Before:

    bradfitz@book1pro tailscale.com % ./tool/go test -c ./cmd/tailscale/cli
    bradfitz@book1pro tailscale.com % ./cli.test

    Warning: funnel=on for foo.test.ts.net:443, but no serve config
             run: `tailscale serve --help` to see how to configure handlers

    Warning: funnel=on for foo.test.ts.net:443, but no serve config
             run: `tailscale serve --help` to see how to configure handlers
    USAGE
      funnel <serve-port> {on|off}
      funnel status [--json]

    Funnel allows you to publish a 'tailscale serve'
    server publicly, open to the entire internet.

    Turning off Funnel only turns off serving to the internet.
    It does not affect serving to your tailnet.

    SUBCOMMANDS
      status  show current serve/funnel status
    error: path must be absolute

    error: invalid TCP source "localhost:5432": missing port in address

    error: invalid TCP source "tcp://somehost:5432"
    must be one of: localhost or 127.0.0.1

    tcp://somehost:5432error: invalid TCP source "tcp://somehost:0"
    must be one of: localhost or 127.0.0.1

    tcp://somehost:0error: invalid TCP source "tcp://somehost:65536"
    must be one of: localhost or 127.0.0.1

    tcp://somehost:65536error: path must be absolute

    error: cannot serve web; already serving TCP

    You don't have permission to enable this feature.

This also moves the color handling up to a generic spot so it's
not just one subcommand doing it itself. See
https://github.com/tailscale/tailscale/issues/11626#issuecomment-2041795129

Fixes #11643
Updates #11626

Change-Id: I3a49e659dcbce491f4a2cb784be20bab53f72303
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Anton Tolchanov 5336362e64 prober: export probe class and metrics from bandwidth prober
- Wrap each prober function into a probe class that allows associating
  metric labels and custom metrics with a given probe;
- Make sure all existing probe classes set a `class` metric label;
- Move bandwidth probe size from being a metric label to a separate
  gauge metric; this will make it possible to use it to calculate
  average used bandwidth using a PromQL query;
- Also export transfer time for the bandwidth prober (more accurate than
  the total probe time, since it excludes connection establishment
  time).

Updates tailscale/corp#17912

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
2 months ago
Anton Tolchanov 21671ca374 prober: remove unused notification code
Signed-off-by: Anton Tolchanov <anton@tailscale.com>
2 months ago
Brad Fitzpatrick b0fbd85592 net/tsdial: partially fix "tailscale nc" (UserDial) on macOS
At least in the case of dialing a Tailscale IP.

Updates #4529

Change-Id: I9fd667d088a14aec4a56e23aabc2b1ffddafa3fe
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick a5e1f7d703 ipn/{ipnlocal,localapi}: add API to toggle use of exit node
This is primarily for GUIs, so they don't need to remember the most
recently used exit node themselves.

This adds some CLI commands, but they're disabled and behind the WIP
envknob, as we need to consider naming (on/off is ambiguous with
running an exit node, etc) as well as automatic exit node selection in
the future. For now the CLI commands are effectively developer debug
things to test the LocalAPI.

Updates tailscale/corp#18724

Change-Id: I9a32b00e3ffbf5b29bfdcad996a4296b5e37be7e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Maisem Ali 3f4c5daa15 wgengine/netstack: remove SubnetRouterWrapper
It was used when we only supported subnet routers on linux
and would nil out the SubnetRoutes slice as no other router
worked with it, but now we support subnet routers on ~all platforms.

The field it was setting to nil is now only used for network logging
and nowhere else, so keep the field but drop the SubnetRouterWrapper
as it's not useful.

Updates #cleanup

Change-Id: Id03f9b6ec33e47ad643e7b66e07911945f25db79
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2 months ago
alexelisenko fe22032fb3
net/dns/{publicdns,resolver}: add start of Control D support
Updates #7946

[@bradfitz fixed up version of #8417]

Change-Id: I1dbf6fa8d525b25c0d7ad5c559a7f937c3cd142a
Signed-off-by: alexelisenko <39712468+alexelisenko@users.noreply.github.com>
Signed-off-by: Alex Paguis <alex@windscribe.com>
2 months ago
Brad Fitzpatrick aa084a29c6 ipn/ipnlocal: name the unlockOnce type, plumb more, add Unlock method
This names the func() that Once-unlocked LocalBackend.mu. It does so
both for docs and because it can then have a method: Unlock, for the
few points that need to explicitly unlock early (the cause of all this
mess). This makes those ugly points easy to find, and also can then
make them stricter, panicking if the mutex is already unlocked. So a
normal call to the func just once-releases the mutex, returning false
if it's already done, but the Unlock method is the strict one.

Then this uses it more, so most the b.mu.Unlock calls remaining are
simple cases and usually defers.

Updates #11649

Change-Id: Ia070db66c54a55e59d2f76fdc26316abf0dd4627
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 5e7c0b025c ipn/ipnlocal: add some "lockedOnEntry" helpers + guardrails, fix bug
A number of methods in LocalBackend (with suffixed "LockedOnEntry")
require b.mu be held but unlock it on the way out. That's asymmetric
and atypical and error prone.

This adds a helper method to LocalBackend that locks the mutex and
returns a sync.OnceFunc that unlocks the mutex. Then we pass around
that unlocker func down the chain to make it explicit (and somewhat
type check the passing of ownership) but also let the caller defer
unlock it, in the case of errors/panics that happen before the callee
gets around to calling the unlock.

This revealed a latent bug in LocalBackend.DeleteProfile which double
unlocked the mutex.

Updates #11649

Change-Id: I002f77567973bd77b8906bfa4ec9a2049b89836a
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Flakes Updater efb710d0e5 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
2 months ago
Brad Fitzpatrick 38377c37b5 ipn/localapi: sort localapi handler map keys
Updates #cleanup

Change-Id: I750ed8d033954f1f8786fb35dd16895bb1c5af8e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Maisem Ali 21b32b467e tsweb: handle panics in retHandler
We would have incomplete stats and missing logs in cases
of panics.

Updates tailscale/corp#18687

Signed-off-by: Maisem Ali <maisem@tailscale.com>
2 months ago
Brad Fitzpatrick ac2522092d cmd/tailscale/cli: make exit-node list not random
The output was changing randomly per run, due to range over a map.

Then some misc style tweaks I noticed while debugging.

Fixes #11629

Change-Id: I67aef0e68566994e5744d4828002f6eb70810ee1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
James Tucker 6e334e64a1 net/netcheck,wgengine/magicsock: align DERP frame receive time heuristics
The netcheck package and the magicksock package coordinate via the
health package, but both sides have time based heuristics through
indirect dependencies. These were misaligned, so the implemented
heuristic aimed at reducing DERP moves while there is active traffic
were non-operational about 3/5ths of the time.

It is problematic to setup a good test for this integration presently,
so instead I added comment breadcrumbs along with the initial fix.

Updates #8603

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Irbe Krumina 1fbaf26106
util/linuxfw: fix chain comparison (#11639)
Don't compare pointer fields by pointer value, but by the actual value

Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Charlotte Brandhorst-Satzkorn 8c75da27fc
drive: move normalizeShareName into pkg drive and make func public (#11638)
This change makes the normalizeShareName function public, so it can be
used for validation in control.

Updates tailscale/corp#16827

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 months ago
Will Morrison 306bacc669 cmd/tailscale/cli: Add CLI command to update certs on Synology devices.
Fixes #4674

Signed-off-by: Will Morrison <william.barr.morrison@gmail.com>
2 months ago
Brad Fitzpatrick 9699bb0a20 metrics: fix outdated docs on MultiLabelMap
And make NewMultiLabelMap panic earlier (at construction time)
if the comparable struct type T violates the documented rules,
rather than panicking at Add time.

Updates #cleanup

Change-Id: Ib1a03babdd501b8d699c4f18b1097a56c916c6d5
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Joonas Kuorilehto fe0cfec4ad wgengine/router: enable ip forwarding on gokrazy
Only on Gokrazy, set sysctls to enable IP forwarding so subnet routing
and advertised exit node works.

Fixes #11405

Signed-off-by: Joonas Kuorilehto <joneskoo@derbian.fi>
2 months ago
Joe Tsai 4bbac72868
util/truncate: support []byte as well (#11614)
There are no mutations to the input,
so we can support both ~string and ~[]byte just fine.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2 months ago
Charlotte Brandhorst-Satzkorn 98cf71cd73
tailscale: switch tailfs to drive syntax for api and logs (#11625)
This change switches the api to /drive, rather than the previous /tailfs
as well as updates the log lines to reflect the new value. It also
cleans up some existing tailfs references.

Updates tailscale/corp#16827

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 months ago
Percy Wegmann 853e3e29a0 wgengine/router: provide explicit hook to signal Android when VPN needs to be reconfigured
This allows clients to avoid establishing their VPN multiple times when
both routes and DNS are changing in rapid succession.

Updates tailscale/corp#18928

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Joe Tsai 1a38d2a3b4
util/zstdframe: support specifying a MaxWindowSize (#11595)
Specifying a smaller window size during compression
provides a knob to tweak the tradeoff between memory usage
and the compression ratio.

Updates tailscale/corp#18514

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2 months ago
Andrew Dunham 7d7d159824 prober: support creating multiple probes in ForEachAddr
So that we can e.g. check TLS on multiple ports for a given IP.

Updates tailscale/corp#16367

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I81d840a4c88138de1cbb2032b917741c009470e6
2 months ago
Andrew Dunham ac574d875c prober: add helper function to check all IPs for a DNS hostname
This allows us to check all IP addresses (and address families) for a
given DNS hostname while dynamically discovering new IPs and removing
old ones as they're no longer valid.

Also add a testable example that demonstrates how to use it.

Alternative to #11610
Updates tailscale/corp#16367

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I6d6f39bafc30e6dfcf6708185d09faee2a374599
2 months ago
Brad Fitzpatrick 8d7894c68e clientupdate, net/dns: fix some "tailsacle" typos
Updates #cleanup

Change-Id: I982175e74b0c8c5b3e01a573e5785e6596b7ac39
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 92d3f64e95 go.toolchain.rev: bump to Go 1.22.2
Update tailscale/corp#18893

Change-Id: I4c04f5153ad43429d7f510c9ac2194c3b2fbc6c1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Charlotte Brandhorst-Satzkorn 93618a3518
tailscale: update tailfs functions and vars to use drive naming (#11597)
This change updates all tailfs functions and the majority of the tailfs
variables to use the new drive naming.

Updates tailscale/corp#16827

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 months ago
Brad Fitzpatrick 2409661a0d control/controlclient: delete old naclbox code, require ts2021 Noise
Updates #11585
Updates tailscale/corp#18882

Change-Id: I90e2e4a211c58d429e2b128604614dde18986442
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick b9611461e5 ipn/ipnlocal: q-encode (RFC 2047) Tailscale serve header values
Updates #11603

RELNOTE=Tailscale serve headers are now RFC 2047 Q-encoded

Change-Id: I1314b65ecf5d39a5a601676346ec2c334fdef042
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Claire Wang 262fa8a01e
ipn/ipnlocal: populate peers' capabilities (#11365)
Populates capabilties field of peers in ipn status.
Updates tailscale/corp#17516

Signed-off-by: Claire Wang <claire@tailscale.com>
2 months ago
James Tucker 9eaa56df93 tsweb: update doc on BucketedStatsOptions.Finish to match behavior
I originally came to update this to match the documented behavior, but
the code is deliberately avoiding this behavior currently, making it
hard to decide how to update this. For now just align the documentation
to the behavior.

Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Charlotte Brandhorst-Satzkorn 14683371ee
tailscale: update tailfs file and package names (#11590)
This change updates the tailfs file and package names to their new
naming convention.

Updates #tailscale/corp#16827

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 months ago
Brad Fitzpatrick 1c259100b0 cmd/{derper,derpprobe}: add --version flag
Fixes #11582

Change-Id: If99fc1ab6b89d624fbb07bd104dd882d2c7b50b4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Patrick O'Doherty 1535d0feca
safeweb: move http.Serve for HTTP redirects into lib (#11592)
Refactor the interaction between caller/library when establishing the
HTTP to HTTPS redirects by moving the call to http.Serve into safeweb.
This makes linting for other uses of http.Serve easier without having to
account for false positives created by the old interface.

Updates https://github.com/tailscale/corp/issues/8027

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
2 months ago
James Tucker f384742375 net/packet: allow more ICMP errors
We now allow some more ICMP errors to flow, specifically:

- ICMP parameter problem in both IPv4 and IPv6 (corrupt headers)
- ICMP Packet Too Big (for IPv6 PMTU)

Updates #311
Updates #8102
Updates #11002

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Irbe Krumina 92ca770b8d
util/linuxfw: fix MSS clamping in nftables mode (#11588)
MSS clamping for nftables was mostly not ran due to to an earlier rule in the FORWARD chain issuing accept verdict.
This commit places the clamping rule into a chain of its own to ensure that it gets ran.

Updates tailscale/tailscale#11002

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Kyle Carberry 27038ee3c2 hostinfo: cache device model to speed up init
This was causing a relatively consistent ~10ms of delay on Linux.

Signed-off-by: Kyle Carberry <kyle@carberry.com>
2 months ago
Brad Fitzpatrick ec87e219ae logtail: delete unused code from old way to configure zstd
Updates #cleanup

Change-Id: I666ecf08ea67e461adf2a3f4daa9d1753b2dc1e4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Joe Tsai e2586bc674
logtail: always zstd compress with FastestCompression and LowMemory (#11583)
This is based on empirical testing using actual logs data.

FastestCompression only incurs a marginal <1% compression ratio hit
for a 2.25x reduction in memory use for small payloads
(which are common if log uploads happen at a decently high frequency).
The memory savings for large payloads is much lower
(less than 1.1x reduction).

LowMemory only incurs a marginal <5% hit on performance
for a 1.6-2.0x reduction in memory use for small or large payloads.

The memory gains for both settings justifies the loss of benefits,
which are arguably minimal.

tailscale/corp#18514

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2 months ago
James Tucker 7558a1d594 ipn/ipnlocal: disable sockstats on (unstable) mobile by default
We're tracking down a new instance of memory usage, and excessive memory usage
from sockstats is definitely not going to help with debugging, so disable it by
default on mobile.

Updates tailscale/corp#18514

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Asutorufa e20ce7bf0c net/dns: close ctx when close dns directManager
Signed-off-by: Asutorufa <16442314+Asutorufa@users.noreply.github.com>
2 months ago
Will Norris 1d2af801fa .github/workflows: remove go-licenses action
This is now handled by an action running in corp.

Updates tailscale/corp#18803

Signed-off-by: Will Norris <will@tailscale.com>
2 months ago
License Updater e80b99cdd1 licenses: update license notices
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
2 months ago
Andrew Lytvynov 5aa4cfad06
safeweb: detect mux handler conflicts (#11562)
When both muxes match, and one of them is a wildcard "/" pattern (which
is common in browser muxes), choose the more specific pattern.
If both are non-wildcard matches, there is a pattern overlap, so return
an error.

Updates https://github.com/tailscale/corp/issues/8027

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
2 months ago
Brad Fitzpatrick e7599c1f7e logtail: prevent js/wasm clients from picking TLS client cert
Corp details:
https://github.com/tailscale/corp/issues/18177#issuecomment-2026598715
https://github.com/tailscale/corp/pull/18775#issuecomment-2027505036

Updates tailscale/corp#18177

Change-Id: I7c03a4884540b8519e0996088d085af77991f477
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Irbe Krumina 5fb721d4ad
util/linuxfw,wgengine/router: skip IPv6 firewall configuration in partial iptables mode (#11546)
We have hosts that support IPv6, but not IPv6 firewall configuration
in iptables mode.
We also have hosts that have some support for IPv6 firewall
configuration in iptables mode, but do not have iptables filter table.
We should:
- configure ip rules for all hosts that support IPv6
- only configure firewall rules in iptables mode if the host
has iptables filter table.

Updates tailscale/tailscale#11540

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Patrick O'Doherty af61179c2f
safeweb: add opt-in inline style CSP toggle (#11551)
Allow the use of inline styles with safeweb via an opt-in configuration
item. This will append `style-src "self" "unsafe-inline"` to the default
CSP. The `style-src` directive will be used in lieu of the fallback
`default-src "self"` directive.

Updates tailscale/corp#8027

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
2 months ago
Brad Fitzpatrick b0941b79d6 tsweb: make BucketedStats not track 400s, 404s, etc
Updates tailscale/corp#18687

Change-Id: I142ccb1301ec4201c70350799ff03222bce96668
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 354cac74a9 tsweb/varz: add charset=utf-8 to varz handler
Some of our labels contain UTF-8 and get mojibaked in the browser
right now.

Updates tailscale/corp#18687

Change-Id: I6069cffd6cc8813df415f06bb308bc2fc3ab65c4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
James Tucker 9401b09028 control/controlclient: move client watchdog to cover initial request
The initial control client request can get stuck in the event that a
connection is established but then lost part way through, without any
ICMP or RST. Ensure that the control client will be restarted by timing
out that initial request as well.

Fixes #11542

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Irbe Krumina 9b5176c4d9
cmd/k8s-operator: fix failing tests (#11541)
Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Irbe Krumina 9e2f58f846
cmd/{k8s-nameserver,k8s-operator},k8s-operator: add a kube nameserver, make operator deploy it (#11017)
* cmd/k8s-nameserver,k8s-operator: add a nameserver that can resolve ts.net DNS names in cluster.

Adds a simple nameserver that can respond to A record queries for ts.net DNS names.
It can respond to queries from in-memory records, populated from a ConfigMap
mounted at /config. It dynamically updates its records as the ConfigMap
contents changes.
It will respond with NXDOMAIN to queries for any other record types
(AAAA to be implemented in the future).
It can respond to queries over UDP or TCP. It runs a miekg/dns
DNS server with a single registered handler for ts.net domain names.
Queries for other domain names will be refused.

The intended use of this is:
1) to allow non-tailnet cluster workloads to talk to HTTPS tailnet
services exposed via Tailscale operator egress over HTTPS
2) to allow non-tailnet cluster workloads to talk to workloads in
the same cluster that have been exposed to tailnet over their
MagicDNS names but on their cluster IPs.

Updates tailscale/tailscale#10499

Signed-off-by: Irbe Krumina <irbe@tailscale.com>

* cmd/k8s-operator/deploy/crds,k8s-operator: add DNSConfig CustomResource Definition

DNSConfig CRD can be used to configure
the operator to deploy kube nameserver (./cmd/k8s-nameserver) to cluster.

Signed-off-by: Irbe Krumina <irbe@tailscale.com>

* cmd/k8s-operator,k8s-operator: optionally reconcile nameserver resources

Adds a new reconciler that reconciles DNSConfig resources.
If a DNSConfig is deployed to cluster,
the reconciler creates kube nameserver resources.
This reconciler is only responsible for creating
nameserver resources and not for populating nameserver's records.

Signed-off-by: Irbe Krumina <irbe@tailscale.com>

* cmd/{k8s-operator,k8s-nameserver}: generate DNSConfig CRD for charts, append to static manifests

Signed-off-by: Irbe Krumina <irbe@tailscale.com>

---------

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Patrick O'Doherty b60c4664c7
safeweb: return http.Handler from safeweb.RedirectHTTP (#11538)
Updates #cleanup

Change the return type of the safeweb.RedirectHTTP method to a handler
that can be passed directly to http.Serve without any http.HandlerFunc
wrapping necessary.

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
2 months ago
Brad Fitzpatrick 3e6306a782 derp/derphttp: make CONNECT Host match request-target's authority-form
This CONNECT client doesn't match what Go's net/http.Transport does
(making the two values match).  This makes it match.

This is all pretty unspecified but most clients & doc examples show
these matching. And some proxy implementations (such as Zscaler) care.

Updates tailscale/corp#18716

Change-Id: I135c5facbbcec9276faa772facbde1bb0feb2d26
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Patrick O'Doherty 8f27520633
safeweb: init (#11467)
Updates https://github.com/tailscale/corp/issues/8027

Safeweb is a wrapper around http.Server & tsnet that encodes some
application security defaults.

Safeweb asks developers to split their HTTP routes into two
http.ServeMuxs for serving browser and API-facing endpoints
repsectively. It then wraps these HTTP routes with the
context-appropriate security controls.

safeweb.Server#Serve will serve the HTTP muxes over the provided
listener. Caller are responsible for creating and tearing down their
application's listeners. Applications being served over HTTPS that wish
to implement HTTP redirects can use the Server#HTTPRedirect handler to
do so.

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
2 months ago
Andrea Gottardo 008676f76e
cmd/serve: update warning for sandboxed macOS builds (#11530) 2 months ago
Percy Wegmann 66e4d843c1 ipn/localapi: add support for multipart POST to file-put
This allows sending multiple files via Taildrop in one request.
Progress is tracked via ipn.Notify.

Updates tailscale/corp#18202

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Percy Wegmann bed818a978 ipn/localapi: add support for multipart POST to file-put
This allows sending multiple files via Taildrop in one request.
Progress is tracked via ipn.Notify.

Updates tailscale/corp#18202

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Maisem Ali 0d8cd1645a go.mod: bump github.com/gaissmai/bart
To pick up https://github.com/gaissmai/bart/pull/17.

Updates #deps

Signed-off-by: Maisem Ali <maisem@tailscale.com>
2 months ago
Percy Wegmann eb42a16da9 ipn/ipnlocal: report Taildrive access message on failed responses
For example, if we get a 404 when downloading a file, we'll report access.

Also, to reduce verbosty of logs, this elides 0 length files.

Updates tailscale/corp#17818

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Andrew Lytvynov 5d41259a63
cmd/tailscale/cli: remove Beta tag from tailscale update (#11529)
Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
2 months ago
Charlotte Brandhorst-Satzkorn acb611f034
ipn/localipn: introduce logs for tailfs (#11496)
This change introduces some basic logging into the access and share
pathways for tailfs.

Updates tailscale/corp#17818

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
2 months ago
Irbe Krumina 4cbef20569
cmd/k8s-operator: redact auth key from debug logs (#11523)
Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Brad Fitzpatrick 55baf9474f metrics, tsweb/varz: add multi-label map metrics
Updates tailscale/corp#18640

Change-Id: Ia9ae25956038e9d3266ea165537ac6f02485b74c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Flakes Updater 90a4d6ce69 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
2 months ago
Brad Fitzpatrick 6d90966c1f logtail: move a scratch buffer to Logger
Rather than pass around a scratch buffer, put it on the Logger.

This is a baby step towards removing the background uploading
goroutine and starting it as needed.

Updates tailscale/corp#18514 (insofar as it led me to look at this code)

Change-Id: I6fd94581c28bde40fdb9fca788eb9590bcedae1b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Irbe Krumina 06e22a96b1
.github/workflows: fix path filter for 'Kubernetes manifests' test job (#11520)
Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
Chris Milson-Tokunaga b6dfd7443a
Change type of installCRDs (#11478)
Including the double quotes (`"`) around the value made it appear like the helm chart should expect a string value for `installCRDs`.

Signed-off-by: Chris Milson-Tokunaga <chris.w.milson@gmail.com>
2 months ago
Percy Wegmann 8b8b315258 net/tstun: use gaissmai/bart instead of tempfork/device
This implementation uses less memory than tempfork/device,
which helps avoid OOM conditions in the iOS VPN extension when
switching to a Tailnet with ExitNode routing enabled.

Updates tailscale/corp#18514

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Andrew Lytvynov 1e7050e73a
go.mod: bump github.com/docker/docker (#11515)
There's a vulnerability https://pkg.go.dev/vuln/GO-2024-2659 that
govulncheck flags, even though it's only reachable from tests and
cmd/sync-containers and cannot be exploited there.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
2 months ago
Brad Fitzpatrick a36cfb4d3d tailcfg, ipn/ipnlocal, wgengine/magicsock: add only-tcp-443 node attr
Updates tailscale/corp#17879

Change-Id: I0dc305d147b76c409cf729b599a94fa723aef0e0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 7b34154df2 all: deprecate Node.Capabilities (more), remove PeerChange.Capabilities [capver 89]
First we had Capabilities []string. Then
https://tailscale.com/blog/acl-grants (#4217) brought CapMap, a
superset of Capabilities. Except we never really finished the
transition inside the codebase to go all-in on CapMap. This does so.

Notably, this coverts Capabilities on the wire early to CapMap
internally so the code can only deal in CapMap, even against an old
control server.

In the process, this removes PeerChange.Capabilities support, which no
known control plane sent anyway. They can and should use
PeerChange.CapMap instead.

Updates #11508
Updates #4217

Change-Id: I872074e226b873f9a578d9603897b831d50b25d9
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 4992aca6ec tsweb/varz: flesh out munging of expvar keys into valid Prometheus metrics
From a problem we hit with how badger registers expvars; it broke
trunkd's exported metrics.

Updates tailscale/corp#1297

Change-Id: I42e1552e25f734c6f521b6e993d57a82849464b2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick b104688e04 ipn/ipnlocal, types/netmap: replace hasCapability with set lookup on NetworkMap
When node attributes were super rare, the O(n) slice scans looking for
node attributes was more acceptable. But now more code and more users
are using increasingly more node attributes. Time to make it a map.

Noticed while working on tailscale/corp#17879

Updates #cleanup

Change-Id: Ic17c80341f418421002fbceb47490729048756d2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Percy Wegmann 8c88853db6 ipn/ipnlocal: add c2n /debug/pprof/allocs endpoint
This behaves the same as typical debug/pprof/allocs.

Updates tailscale/corp#18514

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Brad Fitzpatrick f45594d2c9 control/controlclient: free memory on iOS before full netmap work
Updates tailscale/corp#18514

Change-Id: I8d0330334b030ed8692b25549a0ee887ac6d7188
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
James Tucker e0f97738ee localapi: reduce garbage production in bus watcher
Updates #optimization

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
James Tucker 3f7313dbdb util/linuxfw,wgengine/router: enable IPv6 configuration when netfilter is disabled
Updates #11434

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Brad Fitzpatrick 8444937c89 control/controlclient: fix panic regression from earlier load balancer hint header
In the recent 20e9f3369 we made HealthChangeRequest machine requests
include a NodeKey, as it was the oddball machine request that didn't
include one. Unfortunately, that code was sometimes being called (at
least in some of our integration tests) without a node key due to its
registration with health.RegisterWatcher(direct.ReportHealthChange).

Fortunately tests in corp caught this before we cut a release. It's
possible this only affects this particular integration test's
environment, but still worth fixing.

Updates tailscale/corp#1297

Change-Id: I84046779955105763dc1be5121c69fec3c138672
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Joe Tsai 85febda86d
all: use zstdframe where sensible (#11491)
Use the zstdframe package where sensible instead of plumbing
around our own zstd.Encoder just for stateless operations.

This causes logtail to have a dependency on zstd,
but that's arguably okay since zstd support is implicit
to the protocol between a client and the logging service.
Also, virtually every caller to logger.NewLogger was
manually setting up a zstd.Encoder anyways,
meaning that zstd was functionally always a dependency.

Updates #cleanup
Updates tailscale/corp#18514

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2 months ago
Joe Tsai d4bfe34ba7
util/zstdframe: add package for stateless zstd compression (#11481)
The Go zstd package is not friendly for stateless zstd compression.
Passing around multiple zstd.Encoder just for stateless compression
is a waste of memory since the memory is never freed and seldom
used if no compression operations are happening.

For performance, we pool the relevant Encoder/Decoder
with the specific options set.

Functionally, this package is a wrapper over the Go zstd package
with a more ergonomic API for stateless operations.

This package can be used to cleanup various pre-existing zstd.Encoder
pools or one-off handlers spread throughout our codebases.

Performance:

	BenchmarkEncode/Best               1690        610926 ns/op      25.78 MB/s           1 B/op          0 allocs/op
	    zstd_test.go:137: memory: 50.336 MiB
	    zstd_test.go:138: ratio:  3.269x
	BenchmarkEncode/Better            10000        100939 ns/op     156.04 MB/s           0 B/op          0 allocs/op
	    zstd_test.go:137: memory: 20.399 MiB
	    zstd_test.go:138: ratio:  3.131x
	BenchmarkEncode/Default            15775         74976 ns/op     210.08 MB/s         105 B/op          0 allocs/op
	    zstd_test.go:137: memory: 1.586 MiB
	    zstd_test.go:138: ratio:  3.064x
	BenchmarkEncode/Fastest            23222         53977 ns/op     291.81 MB/s          26 B/op          0 allocs/op
	    zstd_test.go:137: memory: 599.458 KiB
	    zstd_test.go:138: ratio:  2.898x
	BenchmarkEncode/FastestLowMemory                   23361         50789 ns/op     310.13 MB/s          15 B/op          0 allocs/op
	    zstd_test.go:137: memory: 334.458 KiB
	    zstd_test.go:138: ratio:  2.898x
	BenchmarkEncode/FastestNoChecksum                  23086         50253 ns/op     313.44 MB/s          26 B/op          0 allocs/op
	    zstd_test.go:137: memory: 599.458 KiB
	    zstd_test.go:138: ratio:  2.900x

	BenchmarkDecode/Checksum                           70794         17082 ns/op     300.96 MB/s           4 B/op          0 allocs/op
	    zstd_test.go:163: memory: 316.438 KiB
	BenchmarkDecode/NoChecksum                         74935         15990 ns/op     321.51 MB/s           4 B/op          0 allocs/op
	    zstd_test.go:163: memory: 316.438 KiB
	BenchmarkDecode/LowMemory                          71043         16739 ns/op     307.13 MB/s           0 B/op          0 allocs/op
	    zstd_test.go:163: memory: 79.347 KiB

We can see that the options are taking effect where compression ratio improves
with higher levels and compression speed diminishes.
We can also see that LowMemory takes effect where the pooled coder object
references less memory than other cases.
We can see that the pooling is taking effect as there are 0 amortized allocations.

Additional performance:

	BenchmarkEncodeParallel/zstd-24                     1857        619264 ns/op        1796 B/op         49 allocs/op
	BenchmarkEncodeParallel/zstdframe-24                1954        532023 ns/op        4293 B/op         49 allocs/op
	BenchmarkDecodeParallel/zstd-24                     5288        197281 ns/op        2516 B/op         49 allocs/op
	BenchmarkDecodeParallel/zstdframe-24                6441        196254 ns/op        2513 B/op         49 allocs/op

In concurrent usage, handling the pooling in this package
has a marginal benefit over the zstd package,
which relies on a Go channel as the pooling mechanism.
In particular, coders can be freed by the GC when not in use.
Coders can be shared throughout the program if they use this package
instead of multiple independent pools doing the same thing.
The allocations are unrelated to pooling as they're caused by the spawning of goroutines.

Updates #cleanup
Updates tailscale/corp#18514
Updates tailscale/corp#17653
Updates tailscale/corp#18005

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2 months ago
Brad Fitzpatrick 6a860cfb35 ipn/ipnlocal: add c2n pprof option to force a GC
Like net/http/pprof has.

Updates tailscale/corp#18514

Change-Id: I264adb6dcf5732d19707783b29b7273b4ca69cf4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Brad Fitzpatrick 5d1c72f76b wgengine/magicsock: don't use endpoint debug ringbuffer on mobile.
Save some memory.

Updates tailscale/corp#18514

Change-Id: Ibcaf3c6d8e5cc275c81f04141d0f176e2249509b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Andrew Dunham 512fc0b502 util/reload: add new package to handle periodic value loading
This can be used to reload a value periodically, whether from disk or
another source, while handling jitter and graceful shutdown.

Updates tailscale/corp#1297

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Iee2b4385c9abae59805f642a7308837877cb5b3f
2 months ago
Adrian Dewhurst 2f7e7be2ea control/controlclient: do not alias peer CapMap
Updates #cleanup

Change-Id: I10fd5e04310cdd7894a3caa3045b86eb0a06b6a0
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
2 months ago
Percy Wegmann 067ed0bf6f ipnlocal: ensure TailFS share notifications are non-nil
This allows the UI to distinguish between 'no shares' versus
'not being notified about shares'.

Updates ENG-2843

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
Brad Fitzpatrick 20e9f3369d control/controlclient: send load balancing hint HTTP request header
Updates tailscale/corp#1297

Change-Id: I0b102081e81dfc1261f4b05521ab248a2e4a1298
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 months ago
Percy Wegmann 15c58cb77c tailfs: include whitespace in test share and filenames
Since TailFS allows spaces in folder and file names, test with spaces.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
2 months ago
James Tucker e37eded256
tool/gocross: add android autoflags (#11465)
Updates tailscale/corp#18202

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Claire Wang 221de01745
control/controlclient: fix sending peer capmap changes (#11457)
Instead of just checking if a peer capmap is nil, compare the previous
state peer capmap with the new peer capmap.
Updates tailscale/corp#17516

Signed-off-by: Claire Wang <claire@tailscale.com>
2 months ago
Andrew Dunham 6da1dc84de wgengine: fix logger data race in tests
Observed in:
    https://github.com/tailscale/tailscale/actions/runs/8350904950/job/22858266932?pr=11463

Updates #11226

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I9b57db4b34b6ad91d240cd9fa7e344fc0376d52d
2 months ago
Andrew Dunham e382e4cee6 syncs: add Swap method
To mimic sync.Map.Swap, sync/atomic.Value.Swap, etc.

Updates tailscale/corp#1297

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: If7627da1bce8b552873b21d7e5ebb98904e9a650
2 months ago
Andrea Gottardo 6288c9b41e
version/prop: remove IsMacAppSandboxEnabled (#11461)
Fixes tailscale/corp#18441

For a few days, IsMacAppStore() has been returning `false` on App Store builds (IPN-macOS target in Xcode).

I regressed this in #11369 by introducing logic to detect the sandbox by checking for the APP_SANDBOX_CONTAINER_ID environment variable. I thought that was a more robust approach instead of checking the name of the executable. However, it appears that on recent macOS versions this environment variable is no longer getting set, so we should go back to the previous logic that checks for the executable path, or HOME containing references to macsys.

This PR also adds additional checks to the logic by also checking XPC_SERVICE_NAME in addition to HOME where possible. That environment variable is set inside the network extension, either macos or macsys and is good to look at if for any reason HOME is not set.
2 months ago
Mario Minardi 68d9e49a5b
api.md: add missing backtick to GET searchpaths doc (#11459)
Add missing backtick to GET searchpaths api documentation.

Updates #cleanup

Signed-off-by: Mario Minardi <mario@tailscale.com>
2 months ago
Will Norris 349799a1ba api.md: format API docs with prettier
Mostly inconsequential minor fixes for consistency.  A couple of changes
to actual JSON examples, but all still very readable, so I think it's
fine.

Updates #cleanup

Signed-off-by: Will Norris <will@tailscale.com>
2 months ago
Irbe Krumina b0c3e6f6c5
cmd/k8s-operator,ipn/conf.go: fix --accept-routes for proxies (#11453)
Fix a bug where all proxies got configured with --accept-routes set to true.
The bug was introduced in https://github.com/tailscale/tailscale/pull/11238.

Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
2 months ago
James Tucker 7fe4cbbaf3
types/views: optimize slices contains under some conditions (#11449)
In control there are conditions where the leaf functions are not being
optimized away (i.e. At is not inlined), resulting in undesirable time
spent copying during SliceContains. This optimization is likely
irrelevant to simpler code or smaller structures.

Updates #optimization

Signed-off-by: James Tucker <james@tailscale.com>
2 months ago
Mario Minardi d2ccfa4edd
cmd/tailscale,ipn/ipnlocal: enable web client over quad 100 by default (#11419)
Enable the web client over 100.100.100.100 by default. Accepting traffic
from [tailnet IP]:5252 still requires setting the `webclient` user pref.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
2 months ago
Will Norris 4d747c1833 api.md: document device expiration endpoint
This was originally built for testing node expiration flows, but is also
useful for customers to force device re-auth without actually deleting
the device from the tailnet.

Updates tailscale/corp#18408

Signed-off-by: Will Norris <will@tailscale.com>
2 months ago
Mario Minardi e0886ad167
ipn/ipnlocal, tailcfg: add disable-web-client node attribute (#11418)
Add a disable-web-client node attribute and add handling for disabling
the web client when this node attribute is set.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
2 months ago
Marwan Sulaiman da7c3d1753 envknob: ensure f is not nil before using it
This PR fixes a panic that I saw in the mac app where
parsing the env file fails but we don't get to see the
error due to the panic of using f.Name()

Fixes #11425

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
3 months ago
Andrea Gottardo 08ebac9acb
version,cli,safesocket: detect non-sandboxed macOS GUI (#11369)
Updates ENG-2848

We can safely disable the App Sandbox for our macsys GUI, allowing us to use `tailscale ssh` and do a few other things that we've wanted to do for a while. This PR:

- allows Tailscale SSH to be used from the macsys GUI binary when called from a CLI
- tweaks the detection of client variants in prop.go, with new functions `IsMacSys()`, `IsMacSysApp()` and `IsMacAppSandboxEnabled()`

Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
3 months ago
Irbe Krumina ea55f96310
cmd/tailscale/cli: fix configuring partially empty kubeconfig (#11417)
When a user deletes the last cluster/user/context from their
kubeconfig via 'kubectl delete-[cluster|user|context] command,
kubectx sets the relevant field in kubeconfig to 'null'.
This was breaking our conversion logic that was assuming that the field
is either non-existant or is an array.

Updates tailscale/corp#18320

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
3 months ago
Anton Tolchanov cf8948da5f net/routetable: increase route limit used by the test
I was running all tests while preparing a recent stable release, and
this was failing because my computer is connected to a fairly large
tailnet.

```
--- FAIL: TestGetRouteTable (0.01s)
    routetable_linux_test.go:32: expected at least one default route;
    ...
```

```
$ ip route show table 52  | wc -l
1051
```

Updates #cleanup

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 months ago
Andrew Lytvynov decd9893e4
ipn/ipnlocal: validate domain of PopBrowserURL on default control URL (#11394)
If the client uses the default Tailscale control URL, validate that all
PopBrowserURLs are under tailscale.com or *.tailscale.com. This reduces
the risk of a compromised control plane opening phishing pages for
example.

The client trusts control for many other things, but this is one easy
way to reduce that trust a bit.

Fixes #11393

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
3 months ago
Andrew Lytvynov 48eef9e6eb
clientupdate: do not allow msiexec to reboot the OS (#11409)
According to
https://learn.microsoft.com/en-us/windows/win32/msi/standard-installer-command-line-options#promptrestart,
`/promptrestart` is ignored with `/quiet` is set, so msiexec.exe can
sometimes silently trigger a reboot. The best we can do to reduce
unexpected disruption is to just prevent restarts, until the user
chooses to do it. Restarts aren't normally needed for Tailscale updates,
but there seem to be some situations where it's triggered.

Updates #18254

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
3 months ago
Anton Tolchanov da3cf12194 VERSION.txt: this is v1.63.0
Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 months ago
Anton Tolchanov f12d2557f9 prober: add a DERP bandwidth probe
Updates tailscale/corp#17912

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 months ago
Anton Tolchanov 5018683d58 prober: remove unused derp prober latency measurements
Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 months ago
Anton Tolchanov 205a10b51a prober: export probe counters and cumulative latency
Updates #cleanup

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 months ago
Andrew Dunham 7429e8912a wgengine/netstack: fix bug with duplicate SYN packets in client limit
This fixes a bug that was introduced in #11258 where the handling of the
per-client limit didn't properly account for the fact that the gVisor
TCP forwarder will return 'true' to indicate that it's handled a
duplicate SYN packet, but not launch the handler goroutine.

In such a case, we neither decremented our per-client limit in the
wrapper function, nor did we do so in the handler function, leading to
our per-client limit table slowly filling up without bound.

Fix this by doing the same duplicate-tracking logic that the TCP
forwarder does so we can detect such cases and appropriately decrement
our in-flight counter.

Updates tailscale/corp#12184

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ib6011a71d382a10d68c0802593f34b8153d06892
3 months ago
Brad Fitzpatrick ad33e47270 ipn/{ipnlocal,localapi}: add debug verb to force spam IPN bus NetMap
To force the problem in its worst case scenario before fixing it.

Updates tailscale/corp#17859

Change-Id: I2c8b8e5f15c7801e1ab093feeafac52ec175a763
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Flakes Updater 04fceae898 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
3 months ago
James Tucker 055117ad45
util/linuxfw: fix support for containers without IPv6 iptables filters (#11381)
There are container environments such as GitHub codespaces that have
partial IPv6 support - routing support is enabled at the kernel level,
but lacking IPv6 filter support in the iptables module.

In the specific example of the codespaces environment, this also has
pre-existing legacy iptables rules in the IPv4 tables, as such the
nascent firewall mode detection will always pick iptables.

We would previously fault trying to install rules to the filter table,
this catches that condition earlier, and disables IPv6 support under
these conditions.

Updates #5621
Updates #11344
Updates #11354

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
James Tucker 43fba6e04d
util/linuxfw: correct logical error in NAT table check (#11380)
Updates #11344
Updates #11354

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
panchajanya 50a570a83f
Code Improvements (#11311)
build_docker, update-flake: cleanup and apply shellcheck fixes

Was editing this file to match my needs while shellcheck warnings
bugged me out.
REV isn't getting used anywhere. Better remove it.

Updates #cleanup

Signed-off-by: Panchajanya1999 <kernel@panchajanya.dev>
Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
Percy Wegmann e496451928 ipn,cmd/tailscale,client/tailscale: add support for renaming TailFS shares
- Updates API to support renaming TailFS shares.
- Adds a CLI rename subcommand for renaming a share.
- Renames the CLI subcommand 'add' to 'set' to make it clear that
  this is an add or update.
- Adds a unit test for TailFS in ipnlocal

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Percy Wegmann 6c160e6321 ipn,tailfs: tie TailFS share configuration to user profile
Previously, the configuration of which folders to share persisted across
profile changes. Now, it is tied to the user's profile.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Percy Wegmann 16ae0f65c0 cmd/viewer: import views when generating byteSliceField
Updates #cleanup

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Andrew Dunham f072d017bd wgengine/magicsock: don't change DERP home when not connected to control
This pretty much always results in an outage because peers won't
discover our new home region and thus won't be able to establish
connectivity.

Updates tailscale/corp#18095

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic0d09133f198b528dd40c6383b16d7663d9d37a7
3 months ago
Sonia Appasamy 54e52532eb version/mkversion: enforce synology versions within int32 range
Synology requires version numbers are within int32 range. This
change updates the version logic to keep things closer within the
range, and errors on building when the range is exceeded.

Updates #cleanup

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
3 months ago
Claire Wang 74e33b9c50
tailcfg: bump CapabilityVersion (#11368)
bump version for adding NodeAttrSuggestExitNode
remove extra s from NodeAttrSuggestExitNode
Updates tailscale/corp#17516

Signed-off-by: Claire Wang <claire@tailscale.com>
3 months ago
Mario Minardi c662bd9fe7
client/web: dedupe packages in yarn.lock (#11327)
Run yarn-deduplicate on yarn.lock to dedupe packages. This is being done
to reduce the number of redundant packages fetched by yarn when existing
versions in the lockfile satisfy the version dependency we need.

See https://github.com/scinos/yarn-deduplicate for details on the tool
used to perform this deduplication.

Updates #cleanup

Signed-off-by: Mario Minardi <mario@tailscale.com>
3 months ago
Andrew Dunham 34176432d6 cmd/derper, types/logger: move log filter to shared package
So we can use it in trunkd to quiet down the logs there.

Updates #5563

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ie3177dc33f5ad103db832aab5a3e0e4f128f973f
3 months ago
Irbe Krumina 3047b6274c
docs/k8s: don't run subnet router in userspace mode (#11363)
There should not be a need to do that unless we run on host network

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
3 months ago
Andrew Dunham 9884d06b80 net/interfaces: fix test hang on Darwin
This test could hang because the subprocess was blocked on writing to
the stdout pipe if we find the address we're looking for early in the
output.

Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I68d82c22a5d782098187ae6d8577e43063b72573
3 months ago
Andrew Dunham 62cf83eb92 go.mod: bump gvisor
The `stack.PacketBufferPtr` type no longer exists; replace it with
`*stack.PacketBuffer` instead.

Updates #8043

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ib56ceff09166a042aa3d9b80f50b2aa2d34b3683
3 months ago
Andrew Dunham 8f27d519bb tsweb: add String method to tsweb.RequestID
In case we want to change the format to something opaque later.

Updates tailscale/corp#2549

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ie2eac8b885b694be607e9d5101d24b650026d89c
3 months ago
Irbe Krumina 90c4067010
util/linuxfw: add container-friendly IPv6 NAT check (#11353)
Remove IPv6 NAT check when routing is being set up
using nftables.
This is unnecessary as support for nftables was
added after support for IPv6.
https://tldp.org/HOWTO/Linux+IPv6-HOWTO/ch18s04.html
https://wiki.nftables.org/wiki-nftables/index.php/Building_and_installing_nftables_from_sources

Additionally, run an extra check for IPv6 NAT support
when the routing is set up with iptables.
This is because the earlier checks rely on
being able to use modprobe and on /proc/net/ip6_tables_names
being populated on start - these conditions are usually not
true in container environments.

Updates tailscale/tailscale#11344

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
3 months ago
Percy Wegmann fd942b5384 ipn/ipnlocal: reduce allocations in TailFS share notifications
This eliminates unnecessary map.Clone() calls and also eliminates
repetitive notifications about the same set of shares.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Percy Wegmann 6f66f5a75a ipn: add comment about thread-safety to StateStore
Updates #cleanup

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Andrea Gottardo 0cb86468ca ipn/localapi: add set-gui-visible endpoint
Updates tailscale/corp#17859

Provides a local API endpoint to be called from the GUI to inform the backend when the client menu is opened or closed.

cc @bradfitz

Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
3 months ago
Percy Wegmann 00373f07ac ipn/ipnlocal: exclude mullvad exit nodes from TailFS peers list
This is a temporary solution to at least omit Mullvad exit nodes
from the list of TailFS peers. Once we can identify peers that are
actually sharing via TailFS, we can remove this, but for alpha it'll
be sufficient to just omit Mullvad.

Updates tailscale/corp#17766

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Sonia Appasamy c58c59ee54 {ipn,cmd/tailscale/cli}: move ServeConfig mutation logic to ipn/serve
Moving logic that manipulates a ServeConfig into recievers on the
ServeConfig in the ipn package. This is setup work to allow the
web client and cli to both utilize these shared functions to edit
the serve config.

Any logic specific to flag parsing or validation is left untouched
in the cli command. The web client will similarly manage its
validation of user's requested changes. If validation logic becomes
similar-enough, we can make a serve util for shared functionality,
which likely does not make sense in ipn.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
3 months ago
Kristoffer Dalby 65255b060b client/tailscale: add postures to UserRuleMatch
Updates tailscale/corp#17770

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
3 months ago
License Updater d59878e457 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
3 months ago
License Updater 797d75c50a licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
3 months ago
License Updater 6a4e5329c3 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
3 months ago
Andrew Dunham 4338db28f7 wgengine/magicsock: prefer link-local addresses to private ones
Since link-local addresses are definitionally more likely to be a direct
(lower-latency, more reliable) connection than a non-link-local private
address, give those a bit of a boost when selecting endpoints.

Updates #8097

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I93fdeb07de55ba39ba5fcee0834b579ca05c2a4e
3 months ago
Sonia Appasamy 65c3c690cf {ipn/serve,cmd/tailscale/cli}: move some shared funcs to ipn
In preparation for changes to allow configuration of serve/funnel
from the web client, this commit moves some functionality that will
be shared between the CLI and web client to the ipn package's
serve.go file, where some other util funcs are already defined.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
3 months ago
Brad Fitzpatrick 8780e33500 go.toolchain.rev: bump Go toolchain to 1.22.1
Updates tailscale/corp#18000

Change-Id: I45de95e974ea55b0dac2218b3c82d124c4793390
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Paul Scott 2fa20e3787 util/cmpver: add Less/LessEq helper funcs
Updates tailscale/corp#17199

Signed-off-by: Paul Scott <paul@tailscale.com>
3 months ago
Claire Wang d610f8eec0
tailcfg: add suggest exit node related node attribute (#11329)
Updates tailscale/corp#17516

Signed-off-by: Claire Wang <claire@tailscale.com>
3 months ago
Chris Palmer 13853e7f29
tsweb: add more test cases for TestCleanRedirectURL (#11331)
Updates #cleanup

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
3 months ago
Irbe Krumina dff6f3377f
docs/k8s: update docs (#11307)
Update docs for static Tailscale deployments on kube
to always use firewall mode autodection when in non-userspace.
Also add a note about running multiple replicas and a few suggestions how folks could do that.

Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
Co-authored-by: Anton Tolchanov <1687799+knyar@users.noreply.github.com>
3 months ago
Percy Wegmann 232a2d627c tailfs: only impersonate unprivileged user if able to sudo -u as that user
When serving TailFS shares, tailscaled executes another tailscaled to act as a
file server. It attempts to execute this child process as an unprivileged user
using sudo -u. This is important to avoid accessing files as root, which would
result in potential privilege escalation.

Previously, tailscaled assumed that it was running as someone who can sudo -u,
and would fail if it was unable to sudo -u.

With this commit, if tailscaled is unable to sudo -u as the requested user, and
tailscaled is not running as root, then tailscaled executes the the file server
process under the same identity that ran tailscaled, since this is already an
unprivileged identity.

In the unlikely event that tailscaled is running as root but is unable to
sudo -u, it will refuse to run the child file server process in order to avoid
privilege escalation.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Flakes Updater 00554ad277 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
3 months ago
Andrew Lytvynov 23fbf0003f
clientupdate: handle multiple versions in "apk info tailscale" output (#11310)
The package info output can list multiple package versions, and not in
descending order. Find the newest version in the output, instead of the
first one.

Fixes #11309

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
3 months ago
Irbe Krumina 097c5ed927
util/linuxfw: insert rather than append nftables DNAT rule (#11303)
Ensure that the latest DNATNonTailscaleTraffic rule
gets inserted on top of any pre-existing rules.

Updates tailscale/tailscale#11281

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
3 months ago
Percy Wegmann e324a5660f ipn: include full tailfs shares in ipn notifications
This allows the Mac application to regain access to restricted
folders after restarts.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Percy Wegmann 80f1cb6227 tailfs: support storing bookmark data on shares
This allows the sandboxed Mac application to store security-
scoped URL bookmarks in order to maintain access to restricted
folders across restarts.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Brad Fitzpatrick f18f591bc6 wgengine: plumb the PeerByKey from wgengine to magicsock
This was just added in 69f4b459 which doesn't yet use it. This still
doesn't yet use it. It just pushes it down deeper into magicsock where
it'll used later.

Updates #7617

Change-Id: If2f8fd380af150ffc763489e1ff4f8ca2899fac6
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Andrew Lytvynov c7474431f1
tsweb: allow empty redirect URL in CleanRedirectURL (#11295)
Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
3 months ago
Brad Fitzpatrick b68a09cb34 ipn/ipnlocal: make active IPN sessions keyed by sessionID
We used a HandleSet before when we didn't have a unique handle. But a
sessionID is a unique handle, so use that instead. Then that replaces
the other map we had.

And now we'll have a way to look up an IPN session by sessionID for
later.

Updates tailscale/corp#17859

Change-Id: I5f647f367563ec8783c643e49f93817b341d9064
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Percy Wegmann 2d5d6f5403 ipn,wgengine: only intercept TailFS traffic on quad 100
This fixes a regression introduced with 993acf4 and released in
v1.60.0.

The regression caused us to intercept all userspace traffic to port
8080 which prevented users from exposing their own services to their
tailnet at port 8080.

Now, we only intercept traffic to port 8080 if it's bound for
100.100.100.100 or fd7a:115c:a1e0::53.

Fixes #11283

Signed-off-by: Percy Wegmann <percy@tailscale.com>
(cherry picked from commit 17cd0626f3)
3 months ago
Ross Zurowski e83e2e881b
client/web: fix Vite CJS deprecation warning (#11288)
Starting in Vite 5, Vite now issues a deprecation warning when using
a CJS-based Vite config file. This commit fixes it by adding the
`"type": "module"` to our package.json to opt our files into ESM module
behaviours.

Fixes #cleanup

Signed-off-by: Ross Zurowski <ross@rosszurowski.com>
3 months ago
Brad Fitzpatrick 69f4b4595a wgengine{,/wgint}: add wgint.Peer wrapper type, add to wgengine.Engine
This adds a method to wgengine.Engine and plumbed down into magicsock
to add a way to get a type-safe Tailscale-safe wrapper around a
wireguard-go device.Peer that only exposes methods that are safe for
Tailscale to use internally.

It also removes HandshakeAttempts from PeerStatusLite that was just
added as it wasn't needed yet and is now accessible ala cart as needed
from the Peer type accessor.

None of this is used yet.

Updates #7617

Change-Id: I07be0c4e6679883e6eeddf8dbed7394c9e79c5f4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
James Tucker 7e17aeb36b .github/workflows: fix regular breakage of go toolchains
This server recently had a common ansible applied, which added a
periodic /tmp cleaner, as is needed on other CI machines to deal with
test tempfile leakage. The setting of $HOME to /tmp means that the go
toolchain in there was regularly getting pruned by the tmp cleaner, but
often incompletely, because it was also in use.

Move HOME to a runner owned directory.

Updates #11248

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
Brad Fitzpatrick b4ff9a578f wgengine: rename local variable from 'found' to conventional 'ok'
Updates #cleanup

Change-Id: I799dc86ea9e4a3a949592abdd8e74282e7e5d086
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Brad Fitzpatrick a8a525282c wgengine: use slices.Clone in two places
Updates #cleanup

Change-Id: I1cb30efb6d09180e82b807d6146f37897ef99307
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Brad Fitzpatrick 74b8985e19 ipn/ipnstate, wgengine: make PeerStatusLite.LastHandshake zero Time means none
... rather than 1970. Code was using IsZero against the 1970 team
(which isn't a zero value), but fortunately not anywhere that seems to
have mattered.

Updates #cleanup

Change-Id: I708a3f2a9398aaaedc9503678b4a8a311e0e019e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Andrew Dunham 3dd8ae2f26 net/tstun: fix spelling of "WireGuard"
Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ida7e30f4689bc18f5f7502f53a0adb5ac3c7981a
3 months ago
Andrew Dunham a20e46a80f
util/cache: fix missing interface methods (#11275)
Updates #cleanup


Change-Id: Ib3a33a7609530ef8c9f3f58fc607a61e8655c4b5

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
3 months ago
Andrew Dunham 23e9447871 tsweb: expose function to generate request IDs
For use in corp.

Updates tailscale/corp#2549

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I71debae1ce9ae48cf69cc44c2ab5c443fc3b2005
3 months ago
Mario Minardi 7912d76da0
client/web: update to typescript 5.3.3 (#11267)
Update typescript to 5.3.3. This is a major bump from the previous
version of 4.8.3. This also requires adding newer versions of
@typescript-eslint/eslint-plugin and @typescript-eslint/parser to our
resolutions as eslint-config-react-app pulls in versions that otherwise
do not support typescript 5.x.

eslint-config-react-app has not been updated in 2 years and is seemingly
abandoned, so we may wish to fork it or move to a different eslint config
in the future.

Updates https://github.com/tailscale/corp/issues/17810

Signed-off-by: Mario Minardi <mario@tailscale.com>
3 months ago
Andrew Dunham c5abbcd4b4 wgengine/netstack: add a per-client limit for in-flight TCP forwards
This is a fun one. Right now, when a client is connecting through a
subnet router, here's roughly what happens:

1. The client initiates a connection to an IP address behind a subnet
   router, and sends a TCP SYN
2. The subnet router gets the SYN packet from netstack, and after
   running through acceptTCP, starts DialContext-ing the destination IP,
   without accepting the connection¹
3. The client retransmits the SYN packet a few times while the dial is
   in progress, until either...
4. The subnet router successfully establishes a connection to the
   destination IP and sends the SYN-ACK back to the client, or...
5. The subnet router times out and sends a RST to the client.
6. If the connection was successful, the client ACKs the SYN-ACK it
   received, and traffic starts flowing

As a result, the notification code in forwardTCP never notices when a
new connection attempt is aborted, and it will wait until either the
connection is established, or until the OS-level connection timeout is
reached and it aborts.

To mitigate this, add a per-client limit on how many in-flight TCP
forwarding connections can be in-progress; after this, clients will see
a similar behaviour to the global limit, where new connection attempts
are aborted instead of waiting. This prevents a single misbehaving
client from blocking all other clients of a subnet router by ensuring
that it doesn't starve the global limiter.

Also, bump the global limit again to a higher value.

¹ We can't accept the connection before establishing a connection to the
remote server since otherwise we'd be opening the connection and then
immediately closing it, which breaks a bunch of stuff; see #5503 for
more details.

Updates tailscale/corp#12184

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I76e7008ddd497303d75d473f534e32309c8a5144
3 months ago
Claire Wang 352c1ac96c
tailcfg: add latitude, longitude for node location (#11162)
Updates tailscale/corp#17590

Signed-off-by: Claire Wang <claire@tailscale.com>
3 months ago
Irbe Krumina 95dcc1745b
cmd/k8s-operator: reconcile tailscale Ingresses when their backend Services change. (#11255)
This is so that if a backend Service gets created after the Ingress, it gets picked up by the operator.

Updates tailscale/tailscale#11251

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
Co-authored-by: Anton Tolchanov <1687799+knyar@users.noreply.github.com>
3 months ago
Irbe Krumina 303125d96d
cmd/k8s-operator: configure all proxies with declarative config (#11238)
Containerboot container created for operator's ingress and egress proxies
are now always configured by passing a configfile to tailscaled
(tailscaled --config <configfile-path>.
It does not run 'tailscale set' or 'tailscale up'.
Upgrading existing setups to this version as well as
downgrading existing setups at this version works.

Updates tailscale/tailscale#10869

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
3 months ago
Irbe Krumina 45d27fafd6
cmd/k8s-operator,k8s-operator,go.{mod,sum},tstest/tools: add Tailscale Kubernetes operator API docs (#11246)
Add logic to autogenerate CRD docs.
.github/workflows/kubemanifests.yaml CI workflow will fail if the doc is out of date with regard to the current CRDs.
Docs can be refreshed by running make kube-generate-all.

Updates tailscale/tailscale#11023

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
3 months ago
Percy Wegmann 05acf76392 tailfs: fix race condition in tailfs_test
Ues a noop authenticator to avoid potential races in gowebdav's
built-in authenticator.

Fixes #11259

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Keli 086ef19439
scripts/installer.sh: auto-start tailscale on Alpine (#11214)
On Alpine, we add the tailscale service but fail to call start.
This means that tailscale does not start up until the user reboots the machine.

Fixes #11161

Signed-off-by: Keli Velazquez <keli@tailscale.com>
3 months ago
Brad Fitzpatrick 1cf85822d0 ipn/ipnstate, wgengine/wgint: add handshake attempts accessors
Not yet used. This is being made available so magicsock/wgengine can
use it to ignore certain sends (UDP + DERP) later on at least mobile,
letting wireguard-go think it's doing its full attempt schedule, but
we can cut it short conditionally based on what we know from the
control plane.

Updates #7617

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Change-Id: Ia367cf6bd87b2aeedd3c6f4989528acdb6773ca7
3 months ago
Brad Fitzpatrick eb28818403 wgengine: make pendOpen time later, after dup check
Otherwise on OS retransmits, we'd make redundant timers in Go's timer
heap that upon firing just do nothing (well, grab a mutex and check a
map and see that there's nothing to do).

Updates #cleanup

Change-Id: Id30b8b2d629cf9c7f8133a3f7eca5dc79e81facb
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Brad Fitzpatrick 219efebad4 wgengine: reduce critical section
No need to hold wgLock while using the device to LookupPeer;
that has its own mutex already.

Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Change-Id: Ib56049fcc7163cf5a2c2e7e12916f07b4f9d67cb
3 months ago
Brad Fitzpatrick 9a8c2f47f2 types/key: remove copy returning array by value
It's unnecessary. Returning an array value is already a copy.

Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Change-Id: If7f350b61003ea08f16a531b7b4e8ae483617939
3 months ago
Anton Tolchanov 8cc5c51888 health: warn about reverse path filtering and exit nodes
When reverse path filtering is in strict mode on Linux, using an exit
node blocks all network connectivity. This change adds a warning about
this to `tailscale status` and the logs.

Example in `tailscale status`:

```
- not connected to home DERP region 22
- The following issues on your machine will likely make usage of exit nodes impossible: [interface "eth0" has strict reverse-path filtering enabled], please set rp_filter=2 instead of rp_filter=1; see https://github.com/tailscale/tailscale/issues/3310
```

Example in the logs:
```
2024/02/21 21:17:07 health("overall"): error: multiple errors:
	not in map poll
	The following issues on your machine will likely make usage of exit nodes impossible: [interface "eth0" has strict reverse-path filtering enabled], please set rp_filter=2 instead of rp_filter=1; see https://github.com/tailscale/tailscale/issues/3310
```

Updates #3310

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 months ago
Nick Khyl 7ef1fb113d cmd/tailscaled, ipn/ipnlocal, wgengine: shutdown tailscaled if wgdevice is closed
Tailscaled becomes inoperative if the Tailscale Tunnel wintun adapter is abruptly removed.
wireguard-go closes the device in case of a read error, but tailscaled keeps running.
This adds detection of a closed WireGuard device, triggering a graceful shutdown of tailscaled.
It is then restarted by the tailscaled watchdog service process.

Fixes #11222

Signed-off-by: Nick Khyl <nickk@tailscale.com>
3 months ago
Nick Khyl b42b9817b0 net/dns: do not wait for the interface registry key to appear if the windowsManager is being closed
The WinTun adapter may have been removed by the time we're closing
the dns.windowsManager, and its associated interface registry key might
also have been deleted. We shouldn't use winutil.OpenKeyWait and wait
for the interface key to appear when performing a cleanup as a part of
the windowsManager shutdown.

Updates #11222

Signed-off-by: Nick Khyl <nickk@tailscale.com>
3 months ago
OSS Updater 82c569a83a go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
3 months ago
Sonia Appasamy 95f26565db client/web: use grants on web UI frontend
Starts using peer capabilities to restrict the management client
on a per-view basis. This change also includes a bulky cleanup
of the login-toggle.tsx file, which was getting pretty unwieldy
in its previous form.

Updates tailscale/corp#16695

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
3 months ago
Sonia Appasamy 9aa704a05d client/web: restrict serveAPI endpoints to peer capabilities
This change adds a new apiHandler struct for use from serveAPI
to aid with restricting endpoints to specific peer capabilities.

Updates tailscale/corp#16695

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
3 months ago
Anton Tolchanov cd9cf93de6 wgengine/netstack: expose TCP forwarder drops via clientmetrics
- add a clientmetric with a counter of TCP forwarder drops due to the
  max attempts;
- fix varz metric types, as they are all counters.

Updates #8210

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
3 months ago
Percy Wegmann 50fb8b9123 tailfs: replace webdavfs with reverse proxies
Instead of modeling remote WebDAV servers as actual
webdav.FS instances, we now just proxy traffic to them.
This not only simplifies the code, but it also allows
WebDAV locking to work correctly by making sure locks are
handled by the servers that need to (i.e. the ones actually
serving the files).

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Brad Fitzpatrick e1bd7488d0 all: remove LenIter, use Go 1.22 range-over-int instead
Updates #11058
Updates golang/go#65685

Change-Id: Ibb216b346e511d486271ab3d84e4546c521e4e22
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
mrrfv ff1391a97e net/dns/publicdns: add Mullvad family DNS to the list of known DoH servers
Adds the new Mullvad family DNS server to the known DNS over HTTPS server list.

Signed-off-by: mrrfv <rm-rfv-no-preserve-root@protonmail.com>
3 months ago
Brad Fitzpatrick 6ad6d6b252 wgengine/wglog: add TS_DEBUG_RAW_WGLOG envknob for raw wg logs
Updates #7617 (part of debugging it)

Change-Id: I1bcbdcf0f929e3bcf83f244b1033fd438aa6dac1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Brad Fitzpatrick 8b9474b06a wgengine/wgcfg: don't send UAPI to disable keep-alives on new peers
That's already the default. Avoid the overhead of writing it on one
side and reading it on the other to do nothing.

Updates #cleanup (noticed while researching something else)

Change-Id: I449c88a022271afb9be5da876bfaf438fe5d3f58
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
James Tucker 8d0d46462b net/dns: timeout DOH requests after 10s without response headers
If a client socket is remotely lost but the client is not sent an RST in
response to the next request, the socket might sit in RTO for extended
lengths of time, resulting in "no internet" for users. Instead, timeout
after 10s, which will close the underlying socket, recovering from the
situation more promptly.

Updates #10967

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
James Tucker 0c5e65eb3f cmd/derper: apply TCP keepalive and timeout to TLS as well
I missed a case in the earlier patch, and so we're still sending 15s TCP
keepalive for TLS connections, now adjusted there too.

Updates tailscale/corp#17587
Updates #3363

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
James Tucker c9b6d19fc9 .github/workflows: fix typo in XDG_CACHE_HOME
This appears to be one of the contributors to this CI target regularly
entering a bad state with a partially written toolchain.

Updates #self

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
James Tucker 651c4899ac net/interfaces: reduce & cleanup logs on iOS
We don't need a log line every time defaultRoute is read in the good
case, and we now only log default interface updates that are actually
changes.

Updates #3363

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
Andrea Gottardo c8c999d7a9
cli/debug: rename DERP debug mode (#11220)
Renames a debug flag in the CLI.

Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
3 months ago
Mario Minardi ac281dd493
client/web: update vite and vitest to latest versions (#11200)
Update vite to 5.1.4, and vitest to 1.3.1 (their latest versions). Also
remove vite-plugin-rewrite-all as this is no longer necessary with vite
5.x and has a dependency on vite 4.x.

Updates https://github.com/tailscale/corp/issues/17715

Signed-off-by: Mario Minardi <mario@tailscale.com>
3 months ago
Percy Wegmann 15b2c674bf cmd/tailscale: add node attribute instructions to share command help
This adds details on how to configure node attributes to allow
sharing and accessing shares.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
James Tucker 131f9094fd wgengine/wglog: quieten WireGuard logs for allowedips
An increasing number of users have very large subnet route
configurations, which can produce very large amounts of log data when
WireGuard is reconfigured. The logs don't contain the actual routes, so
they're largely useless for diagnostics, so we'll just suppress them.

Fixes tailscale/corp#17532

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
Andrew Dunham e8d2fc7f7f net/tshttpproxy: log when we're using a proxy
Updates #11196

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Id6334c10f52f4cfbda9f03dc8096ab7a6c54a088
3 months ago
Mario Minardi 713d2928b1
client/web: update plugin-react-swc to latest version (#11199)
Update plugin-react-swc to the latest version (3.6.0) ahead of updating vite to 5.x.

Updates https://github.com/tailscale/corp/issues/17715

Signed-off-by: Mario Minardi <mario@tailscale.com>
3 months ago
Mario Minardi 72140da000
client/web: update vite-plugin-svgr to latest version (#11197)
Update vite-plugin-svgr to the latest version (4.2.0) ahead of updating
vite to 5.x. This is a major version bump from our previous 3.x, and
requires changing the import paths used for SVGs.

Updates https://github.com/tailscale/corp/issues/17715

Signed-off-by: Mario Minardi <mario@tailscale.com>
3 months ago
James Tucker edbad6d274 cmd/derper: add user timeout and reduce TCP keepalive
The derper sends an in-protocol keepalive every 60-65s, so frequent TCP
keepalives are unnecessary. In this tuning TCP keepalives should never
occur for a DERP client connection, as they will send an L7 keepalive
often enough to always reset the TCP keepalive timer. If however a
connection does not receive an ACK promptly it will now be shutdown,
which happens sooner than it would with a normal TCP keepalive tuning.

This re-tuning reduces the frequency of network traffic from derp to
client, reducing battery cost.

Updates tailscale/corp#17587
Updates #3363

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
Andrea Gottardo 0359c2f94e
util/syspolicy: add 'ResetToDefaults' (#11194)
Updates ENG-2133. Adds the ResetToDefaults visibility policy currently only available on macOS, so that the Windows client can read its value.

Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
3 months ago
Brad Fitzpatrick 10d130b845 cmd/derper, derp, tailcfg: add admission controller URL option
So derpers can check an external URL for whether to permit access
to a certain public key.

Updates tailscale/corp#17693

Change-Id: I8594de58f54a08be3e2dbef8bcd1ff9b728ab297
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Brad Fitzpatrick 2988c1ec52 derp: plumb context to Server.verifyClient
Updates tailscale/corp#17693

Change-Id: If17e02c77d5ad86b820e639176da2d3e61296bae
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Paul Scott 7708ab68c0 cmd/tailscale/cli: pass "-o 'CanonicalizeHostname no'" to ssh
Fixes #10348

Signed-off-by: Paul Scott <paul@tailscale.com>
3 months ago
Percy Wegmann 91a1019ee2 cmd/testwrapper: apply results of all unit tests to coverage for all packages
This allows coverage from tests that hit multiple packages at once
to be reflected in all those packages' coverage.

Updates #cleanup

Signed-off-by: Percy Wegmann <percy@tailscale.com>
3 months ago
Andrea Gottardo d756622432
util/syspolicy: add ManagedBy keys for Windows (#11183) 3 months ago
James Tucker 8fe504241d net/ktimeout: add a package to set TCP user timeout
Setting a user timeout will be a more practical tuning knob for a number
of endpoints, this provides a way to set it.

Updates tailscale/corp#17587

Signed-off-by: James Tucker <james@tailscale.com>
3 months ago
Brad Fitzpatrick a4a909a20b prober: add TLS probe constructor to split dial addr from cert name
So we can probe load balancers by their unique DNS name but without
asking for that cert name.

Updates tailscale/corp#13050

Change-Id: Ie4c0a2f951328df64281ed1602b4e624e3c8cf2e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
Brad Fitzpatrick 794af40f68 ipn/ipnlocal: remove ancient transition mechanism for https certs
And confusing error message that duplicated the valid cert domains.

Fixes tailscale/corp#15876

Change-Id: I098bc45d83c8d1e0a233dcdf3188869cce66e128
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
3 months ago
James Tucker 6c3899e6ee logpolicy: allow longer idle log upload connections
From a packet trace we have seen log connections being closed
prematurely by the client, resulting in unnecessary extra TLS setup
traffic.

Updates #3363
Updates tailscale/corp#9230
Updates tailscale/corp#8564

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Andrew Dunham 70b7201744 net/dns: fix infinite loop when run on Amazon Linux 2023
This fixes an infinite loop caused by the configuration of
systemd-resolved on Amazon Linux 2023 and how that interacts with
Tailscale's "direct" mode. We now drop the Tailscale service IP from the
OS's "base configuration" when we detect this configuration.

Updates #7816

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I73a4ea8e65571eb368c7e179f36af2c049a588ee
4 months ago
Andrea Gottardo 44e337cc0e
tool/gocross: pass flags for visionOS and visionOS Simulator (#11127)
Adds logic in gocross to detect environment variables and pass the right flags so that the backend can be built with the visionOS SDK.

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
4 months ago
Will Norris 6b582cb8b6 cmd/tailscale: support clickable IPv6 web client addresses
Instead of constructing the `ip:port` string ourselves, use
netip.AddrPortFrom which handles IPv6 correctly.

Updates #11164

Signed-off-by: Will Norris <will@tailscale.com>
4 months ago
Will Norris 24487815e1 cmd/tailscale: make web client URL clickable
Updates #11151

Signed-off-by: Will Norris <will@tailscale.com>
4 months ago
San 69f5664075
ipn/ipnlocal: fix doctor API endpoint (#11155)
Small fix to make sure doctor API endpoint returns correctly - I spotted it when checking my tailscaled node and noticed it was handled slightly different compare to the rest

Signed-off-by: San <santrancisco@users.noreply.github.com>
4 months ago
Percy Wegmann 3aca29e00e VERSION.txt: this is v1.61.0
Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
Jason Barnett 4d668416b8 wgengine/router: fix ip rule restoration
Fixes #10857

Signed-off-by: Jason Barnett <J@sonBarnett.com>
4 months ago
Andrew Dunham 52f16b5d10 doctor/ethtool, ipn/ipnlocal: add ethtool bugreport check
Updates #11137

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Idbe862d80e428adb044249c47d9096b87f29d5d8
4 months ago
Patrick O'Doherty 38bba2d23a
clientupdate: disable auto update on NixOS (#11136)
Updates #cleanup

NixOS packages are immutable and attempts to update via our tarball
mechanism will always fail as a result. Instead we now direct users to
update their nix channel or nixpkgs flake input to receive the latest
Tailscale release.

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
4 months ago
Andrew Dunham b7104cde4a util/topk: add package containing a probabilistic top-K tracker
This package uses a count-min sketch and a heap to track the top K items
in a stream of data. Tracking a new item and adding a count to an
existing item both require no memory allocations and is at worst
O(log(k)) complexity.

Change-Id: I0553381be3fef2470897e2bd806d43396f2dbb36
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
4 months ago
Flakes Updater 7ad2bb87a6 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
4 months ago
Brad Fitzpatrick 61a1644c2a go.mod, all: move away from inet.af domain seized by Taliban
Updates inetaf/tcpproxy#39

Change-Id: I7fee276b116bd08397347c6c949011d76a2842cf
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 months ago
Andrew Dunham b0e96a6c39 net/dns: log more info when openresolv commands fail
Updates #11129

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic594868ba3bc31f6d3b0721ecba4090749a81f7f
4 months ago
Nathan Woodburn 7c0651aea6 scripts/installer.sh: add tuxedoOS to the Ubuntu copies
Signed-off-by: Nathan Woodburn <github@nathan.woodburn.au>
4 months ago
Patrick O'Doherty 256ecd0e8f
Revert "tsweb: update ServeMux matching to 1.22.0 syntax (#11090)" (#11125)
This reverts commit 30c9189ed3.

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
4 months ago
Aaron Klotz f7acbefbbb wgengine/router: make the Windows ifconfig implementation reuse existing MibIPforwardRow2 when possible
Looking at profiles, we spend a lot of time in winipcfg.LUID.DeleteRoute
looking up the routing table entry for the provided RouteData.

But we already have the row! We previously obtained that data via the full
table dump we did in getInterfaceRoutes. We can make this a lot faster by
hanging onto a reference to the wipipcfg.MibIPforwardRow2 and executing
the delete operation directly on that.

Fixes #11123

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
4 months ago
Patrick O'Doherty 30c9189ed3
tsweb: update ServeMux matching to 1.22.0 syntax (#11090)
* tsweb: update ServeMux matching to 1.22.0 syntax

Updates #cleanup

Go 1.22.0 introduced the ability to use more expressive routing patterns
that include HTTP method when constructing ServeMux entries.
Applications that attempted to use these patterns in combination with
the old `tsweb.Debugger` would experience a panic as Go would not permit
the use of matching rules with mixed level of specificity. We now
specify the method for each `/debug` handler to prevent
incompatibilities.

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
4 months ago
Irbe Krumina 5bd19fd3e3
cmd/k8s-operator,k8s-operator: proxy configuration mechanism via a new ProxyClass custom resource (#11074)
* cmd/k8s-operator,k8s-operator: introduce proxy configuration mechanism via ProxyClass custom resource.

ProxyClass custom resource can be used to specify customizations
for the proxy resources created by the operator.

Add a reconciler that validates ProxyClass resources
and sets a Ready condition to True or False with a corresponding reason and message.
This is required because some fields (labels and annotations)
require complex validations that cannot be performed at custom resource apply time.
Reconcilers that use the ProxyClass to configure proxy resources are expected to
verify that the ProxyClass is Ready and not proceed with resource creation
if configuration from a ProxyClass that is not yet Ready is required.

If a tailscale ingress/egress Service is annotated with a tailscale.com/proxy-class annotation, look up the corresponding ProxyClass and, if it is Ready, apply the configuration from the ProxyClass to the proxy's StatefulSet.

If a tailscale Ingress has a tailscale.com/proxy-class annotation
and the referenced ProxyClass custom resource is available and Ready,
apply configuration from the ProxyClass to the proxy resources
that will be created for the Ingress.

Add a new .proxyClass field to the Connector spec.
If connector.spec.proxyClass is set to a ProxyClass that is available and Ready,
apply configuration from the ProxyClass to the proxy resources created for the Connector.

Ensure that when Helm chart is packaged, the ProxyClass yaml is added to chart templates. Ensure that static manifest generator adds ProxyClass yaml to operator.yaml. Regenerate operator.yaml


Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 months ago
Brad Fitzpatrick f7f496025a types/views: add test that LenIter doesn't allocate
For a second we thought this was allocating but we were looking
at a CPU profile (which showed calls to mallocgc view makeslice)
instead of the alloc profile.

Updates golang/go#65685 (which if fixed wouldn't have confused us)

Change-Id: Ic0132310d52d8a65758a516142525339aa23b1ed
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 months ago
Percy Wegmann c42a4e407a tailfs: listen for local clients only on 100.100.100.100
FileSystemForLocal was listening on the node's Tailscale address,
which potentially exposes the user's view of TailFS shares to other
Tailnet users. Remote nodes should connect to exported shares via
the peerapi.

This removes that code so that FileSystemForLocal is only avaialable
on 100.100.100.100:8080.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
Percy Wegmann d0ef3a25df cmd/tailscale: hide share subcommand
Fixes #1115

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
David Anderson 58b8f78e7e flake.nix: build tailscale with go 1.22
Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
4 months ago
Maisem Ali 370ecb4654 tailcfg: remove UserProfile.Groups
Removing as per go/group-all-the-things.

Updates tailscale/corp#17445

Signed-off-by: Maisem Ali <maisem@tailscale.com>
4 months ago
Andrew Dunham c1c50cfcc0 util/cloudenv: add support for DigitalOcean
Updates #4984

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ib229eb40af36a80e6b0fd1dd0cabb07f0d50a7d1
4 months ago
Percy Wegmann 55b372a79f tailscaled: revert to using pointers for subcommands
As part of #10631, we stopped using function pointers for subcommands,
preventing us from registering platform-specific installSystemDaemon
and uninstallSystemDaemon subcommands.

Fixes #11099

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
Percy Wegmann 87154a2f88 tailfs: fix startup issues on windows
Starts TailFS for Windows too, initializes shares on startup.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
Percy Wegmann ddcffaef7a tailfs: disable TailFSForLocal via policy
Adds support for node attribute tailfs:access. If this attribute is
not present, Tailscale will not accept connections to the local TailFS
server at 100.100.100.100:8080.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
Percy Wegmann abab0d4197 tailfs: clean up naming and package structure
- Restyles tailfs -> tailFS
- Defines interfaces for main TailFS types
- Moves implemenatation of TailFS into tailfsimpl package

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
dependabot[bot] 79b547804b build(deps-dev): bump vite from 4.4.9 to 4.5.2 in /client/web
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.4.9 to 4.5.2.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v4.5.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v4.5.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
4 months ago
James Tucker 24bac27632 util/rands: add Shuffle and Perm functions with on-stack RNG state
The new math/rand/v2 package includes an m-local global random number
generator that can not be reseeded by the user, which is suitable for
most uses without the RNG pools we have in a number of areas of the code
base.

The new API still does not have an allocation-free way of performing a
seeded operations, due to the long term compiler bug around interface
parameter escapes, and the Source interface.

This change introduces the two APIs that math/rand/v2 can not yet
replace efficiently: seeded Perm() and Shuffle() operations. This
implementation chooses to use the PCG random source from math/rand/v2,
as with sufficient compiler optimization, this source should boil down
to only two on-stack registers for random state under ideal conditions.

Updates #17243

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Sonia Appasamy 2bb837a9cf client/web: only check policy caps for tagged nodes
For user-owned nodes, only the owner is ever allowed to manage the
node.

Updates tailscale/corp#16695

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
4 months ago
Andrew Dunham 6f6383f69e .github: fuzzing is now unbroken
Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I10dca601c79411b412180a46b3f82136e40544b0
4 months ago
Keisuke Umegaki 7039c06d9b
fix toolchain not available error (#11083)
Relates to golang/go#62278
Updates #11058

Signed-off-by: keisku <keisuke.umegaki.630@gmail.com>
4 months ago
Patrick O'Doherty 7c52b27daf
Revert "tsweb: update ServeMux matching to 1.22.0 syntax (#11087)" (#11089)
This reverts commit 291f91d164.

Updates #cleanup

This PR needs additional changes to the registration of child handlers under /debug

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
4 months ago
Patrick O'Doherty 291f91d164
tsweb: update ServeMux matching to 1.22.0 syntax (#11087)
Updates #cleanup

Go 1.22.0 introduced the ability to use more expressive routing patterns
that include HTTP method when constructing ServeMux entries.
Applications that attempted to use these patterns in combination with
the old `tsweb.Debugger` would experience a panic as Go would not permit
the use of matching rules with mixed level of specificity.

Signed-off-by: Patrick O'Doherty <patrick@tailscale.com>
4 months ago
Jenny Zhang c446451bfa cmd/gitops-pusher: only use OAuth creds if non-empty string
`os.LookupEnv` may return true if the variable is present in
the environment but an empty string. We should only attempt
to set OAuth Config if thsoe values are non-empty.

Updates gitops-acl-action#33

Signed-off-by: Jenny Zhang <jz@tailscale.com>
4 months ago
Percy Wegmann 993acf4475 tailfs: initial implementation
Add a WebDAV-based folder sharing mechanism that is exposed to local clients at
100.100.100.100:8080 and to remote peers via a new peerapi endpoint at
/v0/tailfs.

Add the ability to manage folder sharing via the new 'share' CLI sub-command.

Updates tailscale/corp#16827

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
Joe Tsai 2e404b769d
all: use new AppendEncode methods available in Go 1.22 (#11079)
Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
4 months ago
Joe Tsai 94a4f701c2
all: use reflect.TypeFor now available in Go 1.22 (#11078)
Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
4 months ago
Joe Tsai efddad7d7d
util/deephash: cleanup TODO in TestHash (#11080)
Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
4 months ago
Charlotte Brandhorst-Satzkorn 0f042b9814
cmd/tailscale/cli: fix exit node status output (#11076)
This change fixes the format of tailscale status output when location
based exit nodes are present.

Fixes #11065

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
4 months ago
Andrea Gottardo 6c79f55d48
ipnlocal: force-regen new authURL when it is too old (#10971)
Fixes tailscale/support-escalations#23.

authURLs returned by control expire after 1 hour from creation. Customer reported that the Tailscale client on macOS would sending users to a stale authentication page when clicking on the `Login...` menu item. This can happen when clicking on Login after leaving the device unattended for several days. The device key expires, leading to the creation of a new authURL, however the client doesn't keep track of when the authURL was created. Meaning that `login-interactive` would send the user to an authURL that had expired server-side a long time before.

This PR ensures that whenever `login-interactive` is called via LocalAPI, an authURL that is too old won't be used. We force control to give us a new authURL whenever it's been more than 30 minutes since the last authURL was sent down from control.



Apply suggestions from code review




Set interval to 6 days and 23 hours

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
Signed-off-by: Andrea Gottardo <andrea@gottardo.me>
4 months ago
Sonia Appasamy 1217f655c0 cmd/dist: update logs for synology builds
Update logs for synology builds to more clearly callout which variant
is being built. The two existing variants are:

1. Sideloaded (can be manual installed on a device by anyone)
2. Package center distribution (by the tailscale team)

Updates #cleanup

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
4 months ago
OSS Updater 664b861cd4 go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
4 months ago
Will Norris 6f0c5e0c05 client/web: use smart quotes in web UI frontend
add the curly-quotes eslint plugin (same that we use for the admin
panel), and fix existing straight quotes in the current web UI.

Updates #cleanup

Signed-off-by: Will Norris <will@tailscale.com>
4 months ago
Will Norris 128c99d4ae client/web: add new readonly mode
The new read-only mode is only accessible when running `tailscale web`
by passing a new `-readonly` flag. This new mode is identical to the
existing login mode with two exceptions:

 - the management client in tailscaled is not started (though if it is
   already running, it is left alone)

 - the client does not prompt the user to login or switch to the
   management client. Instead, a message is shown instructing the user
   to use other means to manage the device.

Updates #10979

Signed-off-by: Will Norris <will@tailscale.com>
4 months ago
License Updater 9f0eaa4464 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
4 months ago
License Updater 78f257d9f8 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
4 months ago
License Updater 5486d8aaf9 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
4 months ago
Irbe Krumina a6cc2fdc3e
cmd/{containerboot,k8s-operator/deploy/manifests}: optionally allow proxying cluster traffic to a cluster target via ingress proxy (#11036)
* cmd/containerboot,cmd/k8s-operator/deploy/manifests: optionally forward cluster traffic via ingress proxy.

If a tailscale Ingress has tailscale.com/experimental-forward-cluster-traffic-via-ingress annotation, configure the associated ingress proxy to have its tailscale serve proxy to listen on Pod's IP address. This ensures that cluster traffic too can be forwarded via this proxy to the ingress backend(s).

In containerboot, if EXPERIMENTAL_PROXY_CLUSTER_TRAFFIC_VIA_INGRESS is set to true
and the node is Kubernetes operator ingress proxy configured via Ingress,
make sure that traffic from within the cluster can be proxied to the ingress target.

Updates tailscale/tailscale#10499

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 months ago
Flakes Updater 2404b1444e go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
4 months ago
Brad Fitzpatrick c424e192c0 .github/workflows: temporarily disable broken oss-fuzz action
Updates #11064
Updates #11058

Change-Id: I63acc13dece3379a0b2df573afecfd245b7cd6c2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 months ago
Brad Fitzpatrick 2bd3c1474b util/cmpx: delete now that we're using Go 1.22
Updates #11058

Change-Id: I09dea8e86f03ec148b715efca339eab8b1f0f644
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 months ago
Brad Fitzpatrick 5ea071186e Dockerfile: use Go 1.22
Updates #11058

Change-Id: I0f63be498be33d71bd90b7956f9fe9666fd7a696
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 months ago
Brad Fitzpatrick 9612001cf4 .github/workflows: update golangci-lint for Go 1.22
Updates #11058

Change-Id: I3785c1f1bea4a4663e7e5fb6d209d3caedae436d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 months ago
Brad Fitzpatrick b6153efb7d go.mod, README.md: use Go 1.22
Updates #11058

Change-Id: I95eecdc7afe2b5f8189016fdb8a773f78e9f5c42
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
4 months ago
Tom DNetto 653721541c tsweb: normalize passkey identities in bucketed stats
Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: corp#17075
4 months ago
Tom DNetto 8d6d9d28ba tsweb: normalize common StableID's in bucketed stats, export as LabelMap
Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: corp#17075
4 months ago
James Tucker e0762fe331 words: add a list of things you should yahoo!
Updates #self

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
James Tucker 0b16620b80 .github/workflows: add privileged tests workflow
We had missed regressions from privileged tests not running, now they
can run.

Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
James Tucker 0f5e031133 appc: optimize dns response observation for large route tables
Advertise DNS discovered addresses as a single preference update rather
than one at a time.

Sort the list of observed addresses and use binary search to consult the
list.

Updates tailscale/corp#16636

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Andrew Lytvynov db3776d5bf
go.toolchain.rev: bump to Go 1.22.0 (#11055)
Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
4 months ago
Tom DNetto af931dcccd tsweb: replace domains/emails in paths when bucketing stats
Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: corp#17075
4 months ago
Tom DNetto 36efc50817 tsweb: implementing bucketed statistics for started/finished counts
Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: corp#17075
4 months ago
Maisem Ali b752bde280 types/views: add SliceMapKey[T]
views.Slice are meant to be immutable, and if used as such it
is at times desirable to use them as a key in a map. For non-viewed
slices it was kinda doable by creating a custom key struct but views.Slice
didn't allow for the same so add a method to create that struct here.

Updates tailscale/corp#17122

Signed-off-by: Maisem Ali <maisem@tailscale.com>
4 months ago
kari-ts 5595b61b96
ipn/localapi: more http status cleanup (#10995)
Use Http.StatusOk instead of 200

Updates #cleanup
4 months ago
Chris Palmer a633a30711
cmd/hello: link to the Hello KB article (#11022)
Fixes https://github.com/tailscale/corp/issues/17104

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
4 months ago
Joe Tsai 60657ac83f
util/deephash: tighten up SelfHasher API (#11012)
Providing a hash.Block512 is an implementation detail of how deephash
works today, but providing an opaque type with mostly equivalent API
(i.e., HashUint8, HashBytes, etc. methods) is still sensible.
Thus, define a public Hasher type that exposes exactly the API
that an implementation of SelfHasher would want to call.
This gives us freedom to change the hashing algorithm of deephash
at some point in the future.

Also, this type is likely going to be called by types that are
going to memoize their own hash results, we additionally add
a HashSum method to simplify this use case.

Add documentation to SelfHasher on how a type might implement it.

Updates: corp#16409

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
4 months ago
Joe Tsai 84f8311bcd
util/deephash: document pathological deephash behavior (#11010)
Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
4 months ago
James Tucker ba70cbb930 ipn/ipnlocal: fix app connector route advertisements on exit nodes
If an app connector is also configured as an exit node, it should still
advertise discovered routes that are not covered by advertised routes,
excluding the exit node routes.

Updates tailscale/corp#16928

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
James Tucker e1a4b89dbe appc,ipn/ipnlocal: add app connector routes if any part of a CNAME chain is routed
If any domain along a CNAME chain matches any of the routed domains, add
routes for the discovered domains.

Fixes tailscale/corp#16928

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Tom DNetto 2aeef4e610 util/deephash: implement SelfHasher to allow types to hash themselves
Updates: corp#16409
Signed-off-by: Tom DNetto <tom@tailscale.com>
4 months ago
James Tucker b4b2ec7801 ipn/ipnlocal: fix pretty printing of multi-record peer DNS results
The API on the DNS record parser is slightly subtle and requires
explicit handling of unhandled records. Failure to advance previously
resulted in an infinite loop in the pretty responder for any reply that
contains a record other than A/AAAA/TXT.

Updates tailscale/corp#16928

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Percy Wegmann fad6bae764 ipnlocal: log failure to get ssh host keys
When reporting ssh host keys to control, log a warning
if we're unable to get the SSH host keys.

Updates tailscale/escalations#21

Signed-off-by: Percy Wegmann <percy@tailscale.com>
4 months ago
Chris Palmer 9744ad47e3
cmd/hello: avoid deprecated apis (#10957)
Updates #cleanup

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
4 months ago
Will Norris 13f8a669d5 cmd/gitops-pusher: fix logic for checking credentials
gitops-pusher supports authenticating with an API key or OAuth
credentials (added in #7393). You shouldn't ever use both of those
together, so we error if both are set.

In tailscale/gitops-acl-action#24, OAuth support is being added to the
GitHub action. In that environment, both the TS_API_KEY and OAuth
variables will be set, even if they are empty values.  This causes an
error in gitops-pusher which expects only one to be set.

Update gitops-pusher to check that only one set of environment variables
are non-empty, rather than just checking if they are set.

Updates #7393

Signed-off-by: Will Norris <will@tailscale.com>
4 months ago
Charlotte Brandhorst-Satzkorn cce189bde1 words: i like the direction this list is taking
Updates tailscale/corp#14698

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
4 months ago
Andrew Lytvynov fbfc3b7e51
cmd/tailscale/cli: run Watch with NotifyNoPrivateKeys (#10950)
When running as non-root non-operator user, you get this error:
```
$ tailscale serve 8080
Access denied: watch IPN bus access denied, must set ipn.NotifyNoPrivateKeys when not running as admin/root or operator

Use 'sudo tailscale serve 8080' or 'tailscale up --operator=$USER' to not require root.
```

It should fail, but the error message is confusing.

With this fix:
```
$ tailscale serve 8080
sending serve config: Access denied: serve config denied

Use 'sudo tailscale serve 8080' or 'tailscale up --operator=$USER' to not require root.
```

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
4 months ago
James Tucker 0f3b2e7b86 util/expvarx: add a time and concurrency limiting expvar.Func wrapper
expvarx.SafeFunc wraps an expvar.Func with a time limit. On reaching the
time limit, calls to Value return nil, and no new concurrent calls to
the underlying expvar.Func will be started until the call completes.

Updates tailscale/corp#16999
Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Andrew Dunham fd94d96e2b net/portmapper: support legacy "urn:dslforum-org" portmapping services
These are functionally the same as the "urn:schemas-upnp-org" services
with a few minor changes, and are still used by older devices. Support
them to improve our ability to obtain an external IP on such networks.

Updates #10911

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I05501fad9d6f0a3b8cf19fc95eee80e7d16cc2cf
4 months ago
Irbe Krumina 75f1d3e7d7
ipn/ipnlocal: fix failing test (#10937)
Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 months ago
Irbe Krumina 6ee956333f
ipn/ipnlocal: fix proxy path that matches mount point (#10864)
Don't append a trailing slash to a request path
to the reverse proxy that matches the mount point exactly.

Updates tailscale/tailscale#10730

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 months ago
Jordan Whited 8b47322acc
wgengine/magicsock: implement probing of UDP path lifetime (#10844)
This commit implements probing of UDP path lifetime on the tail end of
an active direct connection. Probing configuration has two parts -
Cliffs, which are various timeout cliffs of interest, and
CycleCanStartEvery, which limits how often a probing cycle can start,
per-endpoint. Initially a statically defined default configuration will
be used. The default configuration has cliffs of 10s, 30s, and 60s,
with a CycleCanStartEvery of 24h. Probing results are communicated via
clientmetric counters. Probing is off by default, and can be enabled
via control knob. Probing is purely informational and does not yet
drive any magicsock behaviors.

Updates #540

Signed-off-by: Jordan Whited <jordan@tailscale.com>
4 months ago
James Tucker 0e2cb76abe appc: add test to ensure that individual IPs are not removed during route updates
If control advised the connector to advertise a route that had already
been discovered by DNS it would be incorrectly removed. Now those routes
are preserved.

Updates tailscale/corp#16833

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Charlotte Brandhorst-Satzkorn ce4553b988 appc,ipn/ipnlocal: optimize preference adjustments when routes update
This change allows us to perform batch modification for new route
advertisements and route removals. Additionally, we now handle the case
where newly added routes are covered by existing ranges.

This change also introduces a new appctest package that contains some
shared functions used for testing.

Updates tailscale/corp#16833

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
4 months ago
Irbe Krumina 370ec6b46b
cmd/k8s-operator: don't proceed with Ingress that has no valid backends (#10919)
Do not provision resources for a tailscale Ingress that has no valid backends.

Updates tailscale/tailscale#10910

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 months ago
Andrew Dunham b45089ad85 net/portmapper: handle cases where we have no supported clients
This no longer results in a nil pointer exception when we get a valid
UPnP response with no supported clients.

Updates #10911

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I6e3715a49a193ff5261013871ad7fff197a4d77e
4 months ago
James Tucker 4e822c031f go.toolchain.rev: bump Tailscale Go version to 1.21.6
Updates tailscale/go#83

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Flakes Updater b787c27c00 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
4 months ago
James Tucker 7e3bcd297e go.mod,wgengine/netstack: bump gvisor
Updates #8043

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
David Anderson 17eae5b0d3 tool/gocross: force use of our custom toolchain
The new 'toolchain' directive in go.mod can sometimes force
the use of an upstream toolchain against our wishes. Concurrently,
some of our dependencies have added the 'toolchain' directive, which
transitively adds it to our own go.mod. Force all uses of gocross to
ignore that directive and stick to our customized toolchain.

Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
4 months ago
David Anderson ae79b2e784 tsweb: add a helper to validate redirect URLs
We issue redirects in a few different places, it's time to have
a common helper to do target validation.

Updates tailscale/corp#16875

Signed-off-by: David Anderson <danderson@tailscale.com>
4 months ago
Claire Wang 213d696db0
magicsock: mute noisy expected peer mtu related error (#10870) 4 months ago
kari-ts 62b056d677
VERSION.txt: this is v1.59.0 (#10884)
* VERSION.txt: this is v1.58.0

Signed-off-by: kari-ts <kari@tailscale.com>

* VERSION.txt: this is v1.59.0

---------

Signed-off-by: kari-ts <kari@tailscale.com>
4 months ago
Flakes Updater 5b4eb47300 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
4 months ago
James Tucker 457102d070 go.mod: bump most deps for start of cycle
Plan9 CI is disabled. 3p dependencies do not build for the target.
Contributor enthusiasm appears to have ceased again, and no usage has
been made.

Skipped gvisor, nfpm, and k8s.

Updates #5794
Updates #8043

Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Andrew Dunham 7a0392a8a3 wgengine/netstack: expose gVisor metrics through expvar
When tailscaled is run with "-debug 127.0.0.1:12345", these metrics are
available at:
    http://localhost:12345/debug/metrics

Updates #8210

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I19db6c445ac1f8344df2bc1066a3d9c9030606f8
4 months ago
as2643 832e5c781d
util/nocasemaps: add AppendSliceElem method to nocasemaps (#10871)
Updates #7667

Signed-off-by: Anishka Singh <anishkasingh66@gmail.com>
4 months ago
ChandonPierre 2ce596ea7a
cmd/k8s-operator/deploy: allow modifying operator tags via Helm values
Updates tailscale/tailscale#10659

Signed-off-by: Chandon Pierre <cpierre@coreweave.com>
4 months ago
Andrew Dunham 2ac7c0161b util/slicesx: add Filter function
For use in corp, where we appear to have re-implemented this in a few
places with varying signatures.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Id863a87e674f3caa87945519be8e09650e9c1d76
4 months ago
Irbe Krumina 2aec4f2c43
./github/workflows/kubemanifests.yaml: fix the paths whose changes should trigger test runs (#10885)
Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
4 months ago
James Tucker 8250582fe6 ipn/ipnlocal: make app connector configuration concurrent
If there are routes changes as a side effect of an app connector
configuration update, the connector configuration may want to reenter a
lock, so must be started asynchronously.

Updates tailscale/corp#16833
Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
James Tucker 38a1cf748a control/controlclient,util/execqueue: extract execqueue into a package
This is a useful primitive for asynchronous execution of ordered work I
want to use in another change.

Updates tailscale/corp#16833
Signed-off-by: James Tucker <james@tailscale.com>
4 months ago
Flakes Updater 32f01acc79 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
5 months ago
James Tucker 24df1ef1ee appc,ipn/ipnlocal,types/appctype: implement control provided routes
Control can now send down a set of routes along with the domains, and
the routes will be advertised, with any newly overlapped routes being
removed to reduce the size of the routing table.

Fixes tailscale/corp#16833
Signed-off-by: James Tucker <james@tailscale.com>
5 months ago
Andrea Gottardo 543e7ed596
licenses: mention tvOS in apple.md (#10872)
Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
5 months ago
License Updater 3eba895293 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
5 months ago
License Updater 9fa2c4605f licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
5 months ago
Joe Tsai c25968e1c5
all: make use of ctxkey everywhere (#10846)
Also perform minor cleanups on the ctxkey package itself.
Provide guidance on when to use ctxkey.Key[T] over ctxkey.New.
Also, allow for interface kinds because the value wrapping trick
also happens to fix edge cases with interfaces in Go.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
5 months ago
Joe Tsai 7732377cd7
tstime/rate: implement Value.{Marshal,Unmarshal}JSON (#8481)
Implement support for marshaling and unmarshaling a Value.

Updates tailscale/corp#8427

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
5 months ago
Irbe Krumina 1c3c3d6752
cmd/k8s-operator: warn if unsupported Ingress Exact path type is used. (#10865)
To reduce the likelihood of breaking users,
if we implement stricter Exact path type matching in the future.

Updates tailscale/tailscale#10730

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Irbe Krumina 50b52dbd7d
cmd/k8s-operator: sync StatefulSet labels to their Pods (#10861)
So that users have predictable label values to use when configuring network policies.

Updates tailscale/tailscale#10854

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Irbe Krumina d0492fdee5
cmd/k8s-operator: adds a tailscale IngressClass resource, prints warning if class not found. (#10823)
* cmd/k8s-operator/deploy: deploy a Tailscale IngressClass resource.

Some Ingress validating webhooks reject Ingresses with
.spec.ingressClassName for which there is no matching IngressClass.

Additionally, validate that the expected IngressClass is present,
when parsing a tailscale `Ingress`. 
We currently do not utilize the IngressClass,
however we might in the future at which point
we might start requiring that the right class
for this controller instance actually exists.

Updates tailscale/tailscale#10820

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
Co-authored-by: Anton Tolchanov <anton@tailscale.com>
5 months ago
License Updater 381430eeca licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
5 months ago
Joe Tsai 241a541864
util/ctxkey: add package for type-safe context keys (#10841)
The lack of type-safety in context.WithValue leads to the common pattern
of defining of package-scoped type to ensure global uniqueness:

	type fooKey struct{}

	func withFoo(ctx context, v Foo) context.Context {
		return context.WithValue(ctx, fooKey{}, v)
	}

	func fooValue(ctx context) Foo {
		v, _ := ctx.Value(fooKey{}).(Foo)
		return v
	}

where usage becomes:

	ctx = withFoo(ctx, foo)
	foo := fooValue(ctx)

With many different context keys, this can be quite tedious.

Using generics, we can simplify this as:

	var fooKey = ctxkey.New("mypkg.fooKey", Foo{})

where usage becomes:

	ctx = fooKey.WithValue(ctx, foo)
	foo := fooKey.Value(ctx)

See https://go.dev/issue/49189

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
5 months ago
kari-ts c9fd166cc6
net/netmon: when a new network is added, trigger netmon update (#10840)
Fixes #10107
5 months ago
Will Norris 236531c5fc ipn/ipnserver: always allow Windows SYSTEM user to connect
When establishing connections to the ipnserver, we validate that the
local user is allowed to connect.  If Tailscale is currently being
managed by a different user (primarily for multi-user Windows installs),
we don't allow the connection.

With the new device web UI, the inbound connection is coming from
tailscaled itself, which is often running as "NT AUTHORITY\SYSTEM".
In this case, we still want to allow the connection, even though it
doesn't match the user running the Tailscale GUI. The SYSTEM user has
full access to everything on the system anyway, so this doesn't escalate
privileges.

Eventually, we want the device web UI to run outside of the tailscaled
process, at which point this exception would probably not be needed.

Updates tailscale/corp#16393

Signed-off-by: Will Norris <will@tailscale.com>
5 months ago
James Tucker 7100b6e721 derp: optimize another per client field alignment
Updates #self

Signed-off-by: James Tucker <james@tailscale.com>
5 months ago
James Tucker ee20327496 derp: remove unused per-client struct field
Updates #self

Signed-off-by: James Tucker <james@tailscale.com>
5 months ago
OSS Updater d841ddcb13 go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
5 months ago
James Tucker a7f65b40c5 derp: optimize field order to reduce GC cost
See the field alignment lints for more information.
Reductions are 64->24 and 64->32 respectively.

Updates #self

Signed-off-by: James Tucker <james@tailscale.com>
5 months ago
Charlotte Brandhorst-Satzkorn e6910974ca cmd/tailscale/cli: add description to exit-node CLI command
This change adds a description to the exit-node CLI command. This
description will be displayed when using `tailscale -h` and `tailscale
exit-node -h`.

Fixes #10787

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
5 months ago
Irbe Krumina 169778e23b
cmd/k8s-operator: minor fix in name gen (#10830)
Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Will Norris b89c113365 client/web: skip connectivity check on https
The manage client always listens on http (non-secure) port 5252.  If the
login client is loaded over https, then the connectivity check to `/ok`
will fail with a mixed-content error. Mixed-content enforcement is a
browser setting that we have no control over, so there's no way around
this.

In this case of the login client being loaded over https, we skip the
connectivity check entirely.  We will always render the sign-in button,
though we don't know for sure if the user has connectivity, so we
provide some additional help text in case they have trouble signing in.

Updates hassio-addons/addon-tailscale#314

Signed-off-by: Will Norris <will@tailscale.com>
5 months ago
James Tucker ff9c1ebb4a derp: reduce excess goroutines blocking on broadcasts
Observed on one busy derp node, there were 600 goroutines blocked
writing to this channel, which represents not only more blocked routines
than we need, but also excess wake-ups downstream as the latent
goroutines writes represent no new work.

Updates #self

Signed-off-by: James Tucker <james@tailscale.com>
5 months ago
Irbe Krumina 5cc1bfe82d
cmd/k8s-operator: remove configuration knob for Connector (#10791)
The configuration knob (that defaulted to Connector being disabled)
was added largely because the Connector CRD had to be installed in a separate step.
Now when the CRD has been added to both chart and static manifest, we can have it on by default.

Updates tailscale/tailscale#10878

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Irbe Krumina 469af614b0
cmd/k8s-operator: fix base truncating for extra long Service names (#10825)
cmd/k8s-operator: fix base truncating for extra long Service names

StatefulSet names for ingress/egress proxies are calculated
using Kubernetes name generator and the parent resource name
as a base.
The name generator also cuts the base, but has a higher max cap.
This commit fixes a bug where, if we get a shortened base back
from the generator, we cut off too little as the base that we
have cut will be passed into the generator again, which will
then itself cut less because the base is shorter- so we end up
with a too long name again.

Updates tailscale/tailscale#10807

Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Irbe Krumina <irbekrm@gmail.com>
5 months ago
Sonia Appasamy 331a6d105f client/web: add initial types for using peer capabilities
Sets up peer capability types for future use within the web client
views and APIs.

Updates tailscale/corp#16695

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
5 months ago
Andrew Dunham 6540d1f018 wgengine/router: look up absolute path to netsh.exe on Windows
This is in response to logs from a customer that show that we're unable
to run netsh due to the following error:

    router: firewall: adding Tailscale-Process rule to allow UDP for "C:\\Program Files\\Tailscale\\tailscaled.exe" ...
    router: firewall: error adding Tailscale-Process rule: exec: "netsh": cannot run executable found relative to current directory:

There's approximately no reason to ever dynamically look up the path of
a system utility like netsh.exe, so instead let's first look for it
in the System32 directory and only if that fails fall back to the
previous behaviour.

Updates #10804

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I68cfeb4cab091c79ccff3187d35f50359a690573
5 months ago
Irbe Krumina ca48db0d60
Makefile,build_docker.sh: allow to configure target platform. (#10806)
Build dev tailscale and k8s-operator images for linux/amd64 only by default,
make it possible to configure target build platform via PLATFORM var.

Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Flakes Updater 91c7dfe85c go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
5 months ago
Andrew Lytvynov 86e476c8d1
version/mkversion: allow version override with $TS_VERSION_OVERRIDE (#10799)
This is useful to build local binaries with custom versions to test
version-specific logic (like updates).

Updates https://github.com/tailscale/corp/issues/16703

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
Andrew Lytvynov 4ec6a78551
go.mod: update golang-x-crypto fork (#10786)
Pick up a bunch of recent upstream commits.

Updates #8593

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
Will Norris 84ab040f02 safesocket: detect macsys from within tailscaled
Use the helper method from the version package to detect that we are
running the macsys network extension. This method does the same check
for the HOME environment variable (which works fine in most cases) as
well as the name of the executable (which is needed for the web client).

Updates tailscale/corp#16393

Signed-off-by: Will Norris <will@tailscale.com>
5 months ago
OSS Updater e7d52eb2f8 go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
5 months ago
Irbe Krumina 35f49ac99e
cmd/k8s-operator: add Connector CRD to Helm chart and static manifests (#10775)
cmd/k8s-operator: add CRD to chart and static manifest

Add functionality to insert CRD to chart at package time.
Insert CRD to static manifests as this is where they are currently consumed from.

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Sonia Appasamy ea9c7f991a cli/set: add printout when web client started
Prints a helpful message with the web UI's address when running
tailscale set --webclient.

Updates tailscale/corp#16345

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
5 months ago
Rhea Ghosh 4ce33c9758
taildrop: remove breaking abstraction layers for apple (#10728)
Removes the avoidFinalRename logic and all associated code as it is no longer required by the Apple clients.
Enables resume logic to be usable for Apple clients.

Fixes tailscale/corp#14772

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
5 months ago
Andrew Lytvynov 7df9af2f5c
.github/workflows/govulncheck: migrate to a Github App (#10793)
Send failures to a new channel using a github app token instead of
webhook URL.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
Andrew Dunham 20f3f706a4 net/netutil: allow 16-bit 4via6 site IDs
The prefix has space for 32-bit site IDs, but the validateViaPrefix
function would previously have disallowed site IDs greater than 255.

Fixes tailscale/corp#16470

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I4cdb0711dafb577fae72d86c4014cf623fa538ef
5 months ago
Irbe Krumina 05093ea7d9
cmd/k8s-operator,k8s-operator: allow the operator to deploy exit nodes via Connector custom resource (#10724)
cmd/k8s-operator/deploy/crds,k8s-operator/apis/v1alpha1: allow to define an exit node via Connector CR.

Make it possible to define an exit node to be deployed to a Kubernetes cluster
via Connector Custom resource.

Also changes to Connector API so that one Connector corresponds
to one Tailnet node that can be either a subnet router or an exit
node or both.

The Kubernetes operator parses Connector custom resource and,
if .spec.isExitNode is set, configures that Tailscale node deployed
for that connector as an exit node.

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
Co-authored-by: Anton Tolchanov <anton@tailscale.com>
5 months ago
James Tucker 953fa80c6f cmd/{derper,stund},net/stunserver: add standalone stun server
Add a standalone server for STUN that can be hosted independently of the
derper, and factor that back into the derper.

Fixes #8434
Closes #8435
Closes #10745

Signed-off-by: James Tucker <james@tailscale.com>
5 months ago
Will Norris 569b91417f client/web: ensure path prefix has a leading slash
This is simply an extra check to prevent hypothetical issues if a prefix
such as `--prefix="javascript:alert(1)"` was provided.  This isn't
really necessary since the prefix is a configuration flag provided by
the device owner, not user input.  But it does enforce that we are
always interpreting the provided value as a path relative to the root.

Fixes: tailscale/corp#16268

Signed-off-by: Will Norris <will@tailscale.com>
5 months ago
License Updater e26ee6952f licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
5 months ago
License Updater 7b113a2d06 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
5 months ago
Andrew Lytvynov d96e0a553f
tstest/integration: add tests for auto-update defaulting behavior (#10763)
Updates #16244

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
Sonia Appasamy 55d302b48e client/web: rename Disconnect to Log out
For consistency w/ the CLI command. And to be more accurate to what
is actually happening on this action - node key is expired.

Also updates the disconnected view shown after logout.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
5 months ago
Irbe Krumina 133699284e
cmd/containerboot: add EXPERIMENTAL_TS_CONFIGFILE_PATH env var to allow passing tailscaled config in a file (#10759)
* cmd/containerboot: optionally configure tailscaled with a configfile.

If EXPERIMENTAL_TS_CONFIGFILE_PATH env var is set,
only run tailscaled with the provided config file.
Do not run 'tailscale up' or 'tailscale set'.

* cmd/containerboot: store containerboot accept_dns val in bool pointer

So that we can distinguish between the value being set to
false explicitly bs being unset.

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Adrian Dewhurst c05c4bdce4 ipn: apply ControlURL policy before login
Unlike most prefs, the ControlURL policy needs to take effect before
login. This resolves an issue where on first start, even when the
ControlURL policy is set, it will generate a login URL to the Tailscale
SaaS server.

Updates tailscale/coral#118
Fixes #10736

Change-Id: I6da2a521f64028c15dbb6ac8175839fc3cc4e858
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
5 months ago
Adrian Dewhurst d50303bef7 docs: add Windows administrative template
To make setting Windows policies easier, this adds ADMX policy
descriptions.

Fixes #6495
Updates ENG-2515

Change-Id: If4613c9d8ec734afec8bd781575e24b4aef9bb73
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
5 months ago
Andrew Dunham 35c303227a net/dns/resolver: add ID to verbose logs in forwarder
To make it easier to correlate the starting/ending log messages.

Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I2802d53ad98e19bc8914bc58f8c04d4443227b26
5 months ago
Rhea Ghosh dbe70962b1
taildrop: Allow category Z unicode characters (#10750)
This will expand the unicode character categories that we allow for valid filenames to go from "L, M, N, P, S, and the ASCII space character" to "L, M, N, P, S, Zs"

Fixes #10105

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
5 months ago
Andrew Dunham d3574a350f cmd/tailscale, ipn/ipnlocal: add 'debug dial-types' command
This command allows observing whether a given dialer ("SystemDial",
"UserDial", etc.) will successfully obtain a connection to a provided
host, from inside tailscaled itself. This is intended to help debug a
variety of issues from subnet routers to split DNS setups.

Updates #9619

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ie01ebb5469d3e287eac633ff656783960f697b84
5 months ago
Aaron Klotz aed2cfec4e util/winutil: add some missing docs to restartmgr errors
Just a quick #cleanup.

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
5 months ago
Andrew Dunham 46bdbb3878 cmd/tailscaled, tsnet: don't return an interface containing a nil pointer
This tripped me up when I was testing something and wrote:

    if conn != nil {
        conn.Close()
    }

In netstack mode, when an error occurred we were getting a non-nil error
and a non-nil interface that contained a nil pointer. Instead, just
return a nil interface value.

Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Id9ef3dd24529e0e8c53adc60ed914c31fbb10cc4
5 months ago
Andrew Lytvynov 29e98e18f8
ssh/tailssh: use a local error instead of gossh.ErrDenied (#10743)
ErrDenied was added in [our fork of
x/crypto/ssh](acc6f8fe8d)
to short-circuit auth attempts once one fails.

In the case of our callbacks, this error is returned when SSH policy
check determines that a connection should not be allowed. Both
`NoClientAuthCallback` and `PublicKeyHandler` check the policy and will
fail anyway. The `fakePasswordHandler` returns true only if
`NoClientAuthCallback` succeeds the policy check, so it checks it
indirectly too.

The difference here is that a client might attempt all 2-3 auth methods
instead of just `none` but will fail to authenticate regardless.

Updates #8593

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
James 'zofrex' Sanderson 124dc10261
controlclient,tailcfg,types: expose MaxKeyDuration via localapi (#10401)
Updates tailscale/corp#16016

Signed-off-by: James Sanderson <jsanderson@tailscale.com>
5 months ago
Andrea Gottardo d9aeb30281
net/interfaces: handle iOS network transitions (#10680)
Updates #8022
Updates #6075

On iOS, we currently rely on delegated interface information to figure out the default route interface.  The NetworkExtension framework in iOS seems to set the delegate interface only once, upon the *creation* of the VPN tunnel. If a network transition (e.g. from Wi-Fi to Cellular) happens while the tunnel is connected, it will be ignored and we will still try to set Wi-Fi as the default route because the delegated interface is not getting updated as connectivity transitions.

Here we work around this on the Swift side with a NWPathMonitor instance that observes the interface name of the first currently satisfied network path. Our Swift code will call into `UpdateLastKnownDefaultRouteInterface`, so we can rely on that when it is set.

If for any reason the Swift machinery didn't work and we don't get any updates, here we also have some fallback logic: we try finding a hardcoded Wi-Fi interface called en0. If en0 is down, we fall back to cellular (pdp_ip0) as a last resort. This doesn't handle all edge cases like USB-Ethernet adapters or multiple Ethernet interfaces, but it is good enough to ensure connectivity isn't broken.

I tested this on iPhones and iPads running iOS 17.1 and it appears to work. Switching between different cellular plans on a dual SIM configuration also works (the interface name remains pdp_ip0).

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
5 months ago
James 'zofrex' Sanderson 10c595d962
ipn/ipnlocal: refresh node key without blocking if cap enabled (#10529)
Updates tailscale/corp#16016

Signed-off-by: James Sanderson <jsanderson@tailscale.com>
Co-authored-by: Maisem Ali <maisem@tailscale.com>
5 months ago
Irbe Krumina 3a9450bc06
cmd/containerboot: don't parse empty subnet routes (#10738)
Updates#cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Irbe Krumina 5a2eb26db3
cmd/containerboot: ensure that subnet routes can be unset. (#10734)
A Tailnet node can be told to stop advertise subnets by passing
an empty string to --advertise-routes flag.
Respect an explicitly passed empty value to TS_ROUTES env var
so that users have a way to stop containerboot acting as a subnet
router without recreating it.
Distinguish between TS_ROUTES being unset and empty.

Updates tailscale/tailscale#10708

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Aaron Klotz e32a064659 cmd/tailscaled: don't create a network monitor in the parent tailscaled on Windows
The service is only used as a watchdog and for piping logs from the child
process. We shouldn't be creating a network monitor in that case.

Fixes #10732

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
5 months ago
Andrew Dunham fa3639783c net/portmapper: check returned epoch from PMP and PCP protocols
If the epoch that we see during a Probe is less than the existing epoch,
it means that the gateway has either restarted or reset its
configuration, and an existing mapping is no longer valid. Reset any
saved mapping(s) if we detect this case so that a future
createOrGetMapping will not attempt to re-use it.

Updates #10597

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ie3cddaf625cb94a29885f7a1eeea25dbf6b97b47
5 months ago
Jordan Whited b084888e4d
wgengine/magicsock: fix typos in docs (#10729)
Updates #cleanup

Signed-off-by: Jordan Whited <jordan@tailscale.com>
5 months ago
Chris Palmer 1f1ab74250
tsweb: use object-src instead of plugin-types (#10719)
plugin-types is deprecated, and setting object-src: 'none' is best
practice. This should result in no functional change.

Fixes #10718

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
5 months ago
Adrian Dewhurst 3d57c885bf logpolicy: use syspolicy to override LogTarget
Previously, for Windows clients only, a registry value named LogTarget
could override the log server, but only if the environment variable was
unset.

To allow administrators to enforce using a particular log server, switch
this to make the registry value take precedence over the environment
variable, and switch to the newer syspolicy.GetString so that the log
target can be specified by a GPO more easily.

Updates ENG-2515

Change-Id: Ia618986b0e07715d7db4c6df170a24d511c904c9
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
5 months ago
Flakes Updater 1406a9d494 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
5 months ago
Irbe Krumina e72f2b7791
go.{mod,sum}: bump mkctr (#10722)
go get github.com/tailscale/mkctr@bf50773ba7349ced8de812c3d5437e8618bd4fa7

Updates tailscale/tailscale#9902

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
5 months ago
Anton Tolchanov 1d22265f69 release: add shebang to the debian postinst script
Seems like an omission, since we have it in postrm and prerm.

Fixes #10705

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
5 months ago
Chris Palmer 5deeb56b95
cmd/tailscale/cli: document usage more clearly (#10681)
The IP argument is required; only the port is optional.

Updates #10605

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
5 months ago
Aaron Klotz 5812093d31 util/winutil: publicize existing functions for opening read-only connections to the Windows Service Control Manager
We're going to need to access these from code outside winutil.

Updates #10215

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
5 months ago
Andrew Dunham cae6edf485 ipn/ipnlocal: fix data race with capForcedNetfilter field
Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I1fdad454198d7ea4a898dbff3062818b0db35167
5 months ago
Andrew Lytvynov 2716250ee8
all: cleanup unused code, part 2 (#10670)
And enable U1000 check in staticcheck.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
Nick Khyl c9836b454d net/netmon: fix goroutine leak in winMon if the monitor is never started
When the portable Monitor creates a winMon via newOSMon, we register
address and route change callbacks with Windows. Once a callback is hit,
it starts a goroutine that attempts to send the event into messagec and returns.
The newly started goroutine then blocks until it can send to the channel.
However, if the monitor is never started and winMon.Receive is never called,
the goroutines remain indefinitely blocked, leading to goroutine leaks and
significant memory consumption in the tailscaled service process on Windows.
Unlike the tailscaled subprocess, the service process creates but never starts
a Monitor.

This PR adds a check within the callbacks to confirm the monitor's active status,
and exits immediately if the monitor hasn't started.

Updates #9864

Signed-off-by: Nick Khyl <nickk@tailscale.com>
5 months ago
Andrew Lytvynov 2e956713de
safesocket: remove ConnectionStrategy (#10662)
This type seems to be a migration shim for TCP tailscaled sockets
(instead of unix/windows pipes). The `port` field was never set, so it
was effectively used as a string (`path` field).
Remove the whole type and simplify call sites to pass the socket path
directly to `safesocket.Connect`.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
Andrew Lytvynov 1302bd1181
all: cleanup unused code, part 1 (#10661)
Run `staticcheck` with `U1000` to find unused code. This cleans up about
a half of it. I'll do the other half separately to keep PRs manageable.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
Andrew Dunham 3c333f6341 net/portmapper: add logs about obtained mapping(s)
This logs additional information about what mapping(s) are obtained
during the creation process, including whether we return an existing
cached mapping.

Updates #10597

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I9ff25071f064c91691db9ab0b9365ccc5f948d6e
5 months ago
David Crawshaw f815d66a88 api.md: add docs for setting an IP address
Updates tailscale/corp#16453

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
5 months ago
Andrew Dunham 01286af82b net/interfaces: better handle multiple interfaces in LikelyHomeRouterIP
Currently, we get the "likely home router" gateway IP and then iterate
through all IPs for all interfaces trying to match IPs to determine the
source IP. However, on many platforms we know what interface the gateway
is through, and thus we don't need to iterate through all interfaces
checking IPs. Instead, use the IP address of the associated interface.

This better handles the case where we have multiple interfaces on a
system all connected to the same gateway, and where the first interface
that we visit (as iterated by ForeachInterfaceAddress) isn't also the
default internet route.

Updates #8992

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8632f577f1136930f4ec60c76376527a19a47d1f
5 months ago
Andrew Lytvynov 7a2eb22e94
ipn: remove use of reflect.MethodByName (#10652)
Using reflect.MethodByName disables some linked deadcode optimizations
and makes our binaries much bigger.
Difference before/after this commit:
```
-rwxr-xr-x  1 awly awly  30M Dec 19 15:28 tailscaled.after*
-rwxr-xr-x  1 awly awly  43M Dec 19 15:27 tailscaled.before*
```

Fixes #10627

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
5 months ago
Andrew Dunham 09136e5995
net/netutil: add function to check rp_filter value (#5703)
Updates #4432


Change-Id: Ifc332a5747fc1feffdbb87437308cf8ecb21b0b0

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
5 months ago
Paul Scott 65f2d32300 api.md: add device.postureIdentity field
Updates tailscale/corp#15445

Signed-off-by: Paul Scott <paul@tailscale.com>
5 months ago
Paul Scott 03f22cd9fa client/tailscale: add Device.PostureIdentity field
New API fields being added in tailscale/corp#15445.

Updates tailscale/corp#15203

Signed-off-by: Paul Scott <paul@tailscale.com>
5 months ago
Nick Khyl 5e3126f510 tool/gocross: make all Windows DLLs build with static libgcc
In this commit, we have updated the build process for our Windows DLLs
to link statically with libgcc, ensuring our Windows DLLs are self-contained.

Updates #10617

Signed-off-by: Nick Khyl <nickk@tailscale.com>
5 months ago
James Tucker 0957258f84 appc,ipn: prevent undesirable route advertisements
Individual route advertisements that are covered by existing routes are
no longer advertised. If an upstream returns 0.0.0.0, 127.x, and other
common unwanted addresses those are also rejected.

Updates #16425
Signed-off-by: James Tucker <james@tailscale.com>
5 months ago
Gavin Greenwalt 865ee25a57
cmd/tailscale/cli: update debug.go (#10644)
redundant run "portmap debugging" word 'debugging'

Signed-off-by: Gavin Greenwalt <gavin@sfstudios.com>
5 months ago
Andrew Dunham a661287c4b util/cmpx: remove code that's in the stdlib now
The cmpx.Compare function (and associated interface) are now available
in the standard library as cmp.Compare. Remove our version of it and use
the version from the standard library.

Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I4be3ac63d466c05eb7a0babb25cb0d41816fbd53
5 months ago
Andrew Lytvynov 945cf836ee
ipn: apply tailnet-wide default for auto-updates (#10508)
When auto-update setting in local Prefs is unset, apply the tailnet
default value from control. This only happens once, when we apply the
default (or when the user manually overrides it), tailnet default no
longer affects the node.

Updates #16244

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Andrew Dunham d05a572db4 net/portmapper: handle multiple UPnP discovery responses
Instead of taking the first UPnP response we receive and using that to
create port mappings, store all received UPnP responses, sort and
deduplicate them, and then try all of them to obtain an external
address.

Updates #10602

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I783ccb1834834ee2a9ecbae2b16d801f2354302f
6 months ago
Irbe Krumina 38b4eb9419
cmd/k8s-operator/deploy/chart: document passing multiple proxy tags + log level values (#10624)
Updates #cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
Flakes Updater dc2792aaee go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
6 months ago
as2643 3fb6ee7fdb
tailscale/logtail: redact public ipv6 and ipv4 ip addresses within tailscaled. (#10531)
Updates #15664

Signed-off-by: Anishka Singh <anishkasingh66@gmail.com>
6 months ago
James Tucker 3a635db06e cmd/connector-gen: add helper tool for wide app connector configurations
connector-gen can initially generate connector ACL snippets and
advertise-routes flags for Github and AWS based on their public IP /
domain data.

Updates ENG-2425
Signed-off-by: James Tucker <james@tailscale.com>
6 months ago
James Tucker 706e30d49e disco: correct noun for nacl box type in disco docs
Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
6 months ago
Sonia Appasamy c6a274611e client/web: use Tailscale IP known by peer node
Throughout the web UI, we present the tailscale addresses for the
self node. In the case of the node being shared out with a user
from another tailnet, the peer viewer may actually know the node
by a different IP than the node knows itself as (Tailscale IPs
can be configured as desired on a tailnet level). This change
includes two fixes:

1. Present the self node's addresses in the frontend as the addresses
   the viewing node knows it as (i.e. the addresses the viewing node
   uses to access the web client).

2. We currently redirect the viewer to the Tailscale IPv4 address if
   viewing it by MagicDNS name, or any other name that maps to the
   Tailscale node. When doing this redirect, which is primarily added
   for DNS rebinding protection, we now check the address the peer
   knows this node as, and redirect to specifically that IP.

Fixes tailscale/corp#16402

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Jordan Whited 685b853763
wgengine/magicsock: fix handling of derp.PeerGoneMessage (#10589)
The switch in Conn.runDerpReader() on the derp.ReceivedMessage type
contained cases other than derp.ReceivedPacket that fell through to
writing to c.derpRecvCh, which should only be reached for
derp.ReceivedPacket. This can result in the last/previous
derp.ReceivedPacket to be re-handled, effectively creating a duplicate
packet. If the last derp.ReceivedPacket happens to be a
disco.CallMeMaybe it may result in a disco ping scan towards the
originating peer on the endpoints contained.

The change in this commit moves the channel write on c.derpRecvCh and
subsequent select awaiting the result into the derp.ReceivedMessage
case, preventing it from being reached from any other case. Explicit
continue statements are also added to non-derp.ReceivedPacket cases
where they were missing, in order to signal intent to the reader.

Fixes #10586

Signed-off-by: Jordan Whited <jordan@tailscale.com>
6 months ago
Andrew Dunham 3ae562366b ipn/ipnlocal: fix usage of slices.Compact
Fixes #10595

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I4e96e9c43b8dedb5f88b03368c01b0e46723e15b
6 months ago
Irbe Krumina 1a08ea5990
cmd/k8s-operator: operator can create subnetrouter (#9505)
* k8s-operator,cmd/k8s-operator,Makefile,scripts,.github/workflows: add Connector kube CRD.

Connector CRD allows users to configure the Tailscale Kubernetes operator
to deploy a subnet router to expose cluster CIDRs or
other CIDRs available from within the cluster
to their tailnet.

Also adds various CRD related machinery to
generate CRD YAML, deep copy implementations etc.

Engineers will now have to run
'make kube-generate-all` after changing kube files
to ensure that all generated files are up to date.

* cmd/k8s-operator,k8s-operator: reconcile Connector resources

Reconcile Connector resources, create/delete subnetrouter resources in response to changes to Connector(s).

Connector reconciler will not be started unless
ENABLE_CONNECTOR env var is set to true.
This means that users who don't want to use the alpha
Connector custom resource don't have to install the Connector
CRD to their cluster.
For users who do want to use it the flow is:
- install the CRD
- install the operator (via Helm chart or using static manifests).
For Helm users set .values.enableConnector to true, for static
manifest users, set ENABLE_CONNECTOR to true in the static manifest.

Updates tailscale/tailscale#502


Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
Chris Palmer b62a3fc895
client/web: keep redirects on-site (#10525)
Ensure we don't create Location: header URLs that have leading //, which is a
schema-less reference to arbitrary 3rd-party sites. That is, //example.com/foo
redirects off-site, while /example.com/foo is an on-site path URL.

Fixes tailscale/corp#16268

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
6 months ago
Andrew Dunham 727acf96a6 net/netcheck: use DERP frames as a signal for home region liveness
This uses the fact that we've received a frame from a given DERP region
within a certain time as a signal that the region is stil present (and
thus can still be a node's PreferredDERP / home region) even if we don't
get a STUN response from that region during a netcheck.

This should help avoid DERP flaps that occur due to losing STUN probes
while still having a valid and active TCP connection to the DERP server.

RELNOTE=Reduce home DERP flapping when there's still an active connection

Updates #8603

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: If7da6312581e1d434d5c0811697319c621e187a0
6 months ago
Andrew Dunham bac4890467 net/portmapper: be smarter about selecting a UPnP device
Previously, we would select the first WANIPConnection2 (and related)
client from the root device, without any additional checks. However,
some routers expose multiple UPnP devices in various states, and simply
picking the first available one can result in attempting to perform a
portmap with a device that isn't functional.

Instead, mimic what the miniupnpc code does, and prefer devices that are
(a) reporting as Connected, and (b) have a valid external IP address.
For our use-case, we additionally prefer devices that have an external
IP address that's a public address, to increase the likelihood that we
can obtain a direct connection from peers.

Finally, we split out fetching the root device (getUPnPRootDevice) from
selecting the best service within that root device (selectBestService),
and add some extensive tests for various UPnP server behaviours.

RELNOTE=Improve UPnP portmapping when multiple UPnP services exist

Updates #8364

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I71795cd80be6214dfcef0fe83115a5e3fe4b8753
6 months ago
Sonia Appasamy 971fa8dc56 VERSION.txt: this is v1.57.0
Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Flakes Updater e00141ccbe go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
6 months ago
OSS Updater e78cb9aeb3 go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
6 months ago
Sonia Appasamy 4fb679d9cd client/web: fix redirect logic when accessing login client over TS IP
Was previously failing to redirect to the manage client when accessing
the login client with the Tailscale IP.

Updates #10261
Fixes tailscale/corp#16348

Co-authored-by: Will Norris <will@tailscale.com>
Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Anton Tolchanov 869b34ddeb prober: log HTTP response body on failure
Signed-off-by: Anton Tolchanov <anton@tailscale.com>
6 months ago
Andrea Barisani affe11c503 net/netcheck: only run HTTP netcheck for tamago clients
Signed-off-by: Andrea Barisani <andrea@inversepath.com>
6 months ago
Flakes Updater 3ba5fd4baa go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
6 months ago
OSS Updater be19262cc5 go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
6 months ago
Charlotte Brandhorst-Satzkorn 7370f3e3a7 words: some stellar additions
Don't get too starry-eyed reviewing these.

Updates tailscale/corp#14698

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
6 months ago
Sonia Appasamy 77f5d669fa client/web: fix key expiry text when expiry disabled
Displays "No expiry" when disabled.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy 06af3e3014 client/web: only add cache header for assets
Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Flakes Updater 808f19bf01 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
6 months ago
OSS Updater afe138f18d go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
6 months ago
Sonia Appasamy dd0279a6c9 client/web: fix ts connection check
Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Flakes Updater 8c2fcef453 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
6 months ago
Sonia Appasamy 343f4e4f26 client/web: refresh auth after syno login
Makes sure we refresh auth state after synology auth has run.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Will Norris 1b7d289fad client/web: add debug card to details page
Add a new "Debug" card at the bottom of the details page. It's maybe
premature to add a separate card for this, since all it currently lists
is whether the device is using TUN mode and (for Synology) the DSM
version. But I think it may be helpful to add client connectivity data
(like shown on admin console machine page) as well as a bug report
button.  Those can come soon after the 1.56 launch.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
OSS Updater 552b1ad094 go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
6 months ago
Sonia Appasamy 1aee6e901d client/web: use prefs.ControlURLOrDefault from controlSupportsCheckMode
To be safe, use `prefs.ControlURLOrDefault()` rather than the current
`prefs.ControlURL` directly.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Irbe Krumina 0cdc8e20d6
util/linuxfw: return created chain (#10563)
Ensure that if getOrCreateChain creates a new chain, it actually returns the created chain

Updates tailscale/tailscale#10399

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
Will Norris d2fbdb005d client/web: use CSP hash for inline javascript
Calculate and set the hash of the one inline script we have in
index.html. That script is unlikely to change, so hardcoding the hash
seems fine for now.

Updates #10261
Updates tailscale/corp#16266

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy bc9b9e8f69 client/web: restrict using an exit node on a couple more platforms
Completed testing of the new UI on the existing platforms that use
it. From testing, QNAP, Unraid, and Home Assistant (in addition to
Synology) all do not play well with using an exit node. For now,
we're disabling this setting from the UI. CLI should be updated to
also disallow selection of an exit node from these platforms.
All platforms still allow for advertising as an exit node.

Co-authored-by: Will Norris <will@tailscale.com>

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Will Norris fc69301fd1 client/web: don't show login button if /ok errors
When displaying the login client, we check for connectivity to the
management client by calling it's /ok handler. If that response is
non-200, then there is something wrong with the management client, so
don't render the login button.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Maisem Ali 3aa6468c63 cmd/tailscale/cli: add whois subcommand
Initial implementation of a `tailscale whois` subcommand
which allows users to observe metadata associated with a
Tailscale IP. It also has a `--json` flag to allow consumption
programmatically.

Updates #4217

Signed-off-by: Maisem Ali <maisem@tailscale.com>
6 months ago
Maisem Ali fb632036e3 cmd/k8s-operator: drop https:// in capName
Add the new format but keep respecting the old one.

Updates #4217

Signed-off-by: Maisem Ali <maisem@tailscale.com>
6 months ago
Mario Minardi 4e012794fc
client/web: add metric logging when viewing local / remote node (#10555)
Add metric logging for the case where a user is viewing a local or remote
node.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
6 months ago
Mario Minardi 763b9daa84
client/web: add visual indication for exit node pending approval (#10532)
Add visual indication when running as an exit node prior to receiving
admin approval.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
Co-authored-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Will Norris e9f203d747 client/web: open new window if iframed
Previously, we were only breaking out of iframes when accessing the
login client over a local IP address (where viewerIdentity is not set).
We need to also handle the case where the user is accessing the login
client over the Tailscale IP, and similarly break out of the iframe when
logging into the management client.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
OSS Updater 501478dcdc go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
6 months ago
Will Norris 970dc2a976 client/web: remove 'unsafe-inline' from CSP
I seem to recall I needed this for things to work properly with the vite
dev server, but that doesn't seem to be the case anymore?  Everything
seems to work fine without it.  If we still have issues, we'll need to
look into using a nonce or integrity attribute.

Updates #10261
Fixes tailscale/corp#16266

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy c2fe123232 cmd/tailscaled: update ConfigureWebClient's UseSocketOnly value
Previously were always setting `UseSocketOnly` because we were
comparing `args.socketpath != ""`, but `args.socketpath` flag
always gets filled with `paths.DefaultTailscaledSocket()` when
not provided. Rather than comparing to the empty string, compare
to the default value to determine if `UseSocketOnly` should be
set.

Should fix issue with web client being unreachable for Mac App
Store variant of the mac build.

Updates #16054

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Mario Minardi 109929d110
client/web: add endpoint for logging device detail click metric (#10505)
Add an endpoint for logging the device detail click metric to allow for
this metric to be logged without having a valid session which is the
case when in readonly mode.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
6 months ago
Andrew Lytvynov d8493d4bd5
clientupdate: add explicit Track to Arguments (#10548)
Instead of overloading the Version field, add an explicit Track field.

This fixes a bug where passing a track name in `args.Version` would keep
the track name in `updater.Version` and pass it down the code path to
commands like `apt-get install`. Now, `updater.Version` should always be
a version (or empty string).

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Irbe Krumina 1b1b6bb634
ALPINE.txt,Dockerfile{.base},build_docker.sh: bump alpine (#10543)
Bump alpine base image version used to build tailscale/tailscale
and tailscale/k8s-operator images 3.16 -> 3.18

Updates #cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
License Updater bac0df6949 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
6 months ago
Will Norris 5a2e6a6f7d client/web: use Home Assistant's X-Ingress-Path header
When running on Home Assistant, use the X-Ingress-Path header to set the
URLPrefix that is passed to the frontend.

Also fix handling of errNotUsingTailscale in the auth handler
(previously it falling through to a later case and returning a 500).
Instead, it's just a terminal state with no auth needed.

Also disable SSH on Home Assistant, since it causes problems on startup
and doesn't make much sense anyway for that platform.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy a4c7b0574a client/web: add confirmation dialogs
Add confirmation dialogs for disconnecting and stopping advertisement
of a subnet route.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Will Norris 69b56462fc client/web: check content-type on PATCH requests
Updates #10261
Fixes tailscale/corp#16267

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Will Norris c615fe2296 client/web: add security attributes on session cookie
Limit cookies to HTTP requests (not accessible from javascript).
Set SameSite to "Lax", which is similar to "Strict" but allows for
cookies to be included in requests that come from offsite links.  This
will be necessary when we link to the web client from the admin console.

Updates #10261
Fixes tailscale/corp#16265

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy 261b6f1e9f client/web: limit updates ui to unstable builds
The updates view still needs a final design pass, limit to unstable
track for now.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Will Norris 33de922d57 client/web: only enforce path prefix in CGI mode
The client has changed a bit since we introduced the path prefix.  It is
now used for two things:

- its original purpose, of ensuring that when the client is run in CGI
  mode at arbitrary paths, then relative paths for assets continue to
  work

- we also now pass the path to the frontend and use wouter to manage
  routes for the various subpages of the client.

When the client is run behind a reverse proxy (as it is in Home
Assistant), it is common for the proxy to rewrite the request so that
the backend application doesn't see the path it's being served at. In
this case, we don't need to call enforcePrefix, since it's already
stripped before it reaches us.  However, wouter (or react router
library) still sees the original path in the browser, and needs to know
what part of it is the prefix that needs to be stripped off.

We're handling this by now only calling enforcePrefix when run in CGI
mode. For Home Assistant, or any other platform that runs the client
behind a reverse proxy with a custom path, they will still need to pass
the `-prefix` flag to `tailscale web`, but we will only use it for route
handling in the frontend.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy c2319f0dfa client/web: fix serveAPIAuth in Login mode
In Login mode, must first run system auth. But once authorized,
should be able to reach rest of auth logic to check whether the
user can manage the node. This results in showing/hiding the
sign in button in the frontend login toggle.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy 7c172df791 client/web: fix 500 error after logout
Calling DebugPacketFilterRules fails when the node is not logged
in, which was causing 500 errors on the node data endpoint after
logging the node out.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Adrian Dewhurst 86aa0485a6 ipn/ipnlocal, util/syspolicy: make run exit node a preference option
Previously, the "RunExitNode" policy merely controlled the visibility of
the "run as exit node" menu item, not the setting itself. This migrates
that setting to a preference option named "AdvertiseExitNode".

Updates ENG-2138

Change-Id: Ia6a125beb6b4563d380c6162637ce4088f1117a0
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
6 months ago
Mario Minardi 21958d2934
client/web: add logging of device management type for web client (#10492)
Add logging of device management type for the web client auth flow. Namely,
this differentiates between viewing a node you do not own, viewing a local
tagged node, viewing a remote tagged node, managing a local node, and
managing a remote node.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
6 months ago
Maisem Ali 7bdea283bd cmd/containerboot: symlink TS_SOCKET to socket expected by CLI
`tailscaled` and `tailscale` expect the socket to be at
`/var/run/tailscale/tailscaled.sock`, however containerboot
would set up the socket at `/tmp/tailscaled.sock`. This leads to a
poor UX when users try to use any `tailscale` command as they
have to prefix everything with `--socket /tmp/tailscaled.sock`.

To improve the UX, this adds a symlink to
`/var/run/tailscale/tailscaled.sock` to point to `/tmp/tailscaled.sock`.

This approach has two benefits, 1 users are able to continue to use
existing scripts without this being a breaking change. 2. users are
able to use the `tailscale` CLI without having to add the `--socket` flag.

Fixes tailscale/corp#15902
Fixes #6849
Fixes #10027

Signed-off-by: Maisem Ali <maisem@tailscale.com>
6 months ago
Sonia Appasamy ddb4b51122 client/web: always run platform auth for login mode
Even if connected to the login client over tailscale, still check
platform auth so the browser can obtain the tokens it needs to make
platform requests complete successfully.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Andrew Lytvynov e25f114916
ipn,cmd/tailscale/cli: support hierarchical MaskedPrefs (#10507)
Some fields if `ipn.Prefs` are structs. `ipn.MaskedPrefs` has a single
level of boolean `*Set` flags, which doesn't map well to nested structs
within `ipn.Prefs`.

Change `MaskedPrefs` and `ApplyEdits` to support `FooSet` struct fields
that map to a nested struct of `ipn.Prefs` like `AutoUpdates`. Each
struct field in `MaskedPrefs` is just a bundle of more `Set` bool fields
or other structs. This allows you to have a `Set` flag for any
arbitrarily-nested field of `ipn.Prefs`.

Also, make `ApplyEdits` match fields between `Prefs` and `MaskedPrefs`
by name instead of order, to make it a bit less finicky. It's probably
slower but `ipn.ApplyEdits` should not be in any hot path.

As a result, `AutoUpdate.Check` and `AutoUpdate.Apply` fields don't
clobber each other when set individually.

Updates #16247

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Flakes Updater 2f01d5e3da go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
6 months ago
OSS Updater 6389322619 go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
6 months ago
Aaron Klotz 0f646937e9 clientupdate: remove TS_NOLAUNCH and GUI restart hacks from autoupdate
We've fixed the underlying issue in github.com/tailscale/corp/issues/13998.

Fixes #10513

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
6 months ago
Andrea Gottardo 646d17ac8d
util/syspolicy: rename client metric keys (#10516)
Updates ENG-2513. Renames client metrics keys used on Windows for consistency with Apple platforms.

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
6 months ago
Sonia Appasamy d5d42d0293 client/web: small UI cleanups
Updates:
* Card component used throughout instead of custom card class
* SSH toggle changed to non-editable text/status icon in readonly
* Red error text on subnet route input when route post failed

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy e5e5ebda44 client/web: precompress assets
Precompress webclient assets with precompress util. This cuts our
css and js build sizes to about 1/3 of non-compressed size. Similar
compression done on tsconnect and adminhttp assets.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy 97f8577ad2 client/web: restructure api mutations into hook
This commit makes some restructural changes to how we handle api
posting from the web client frontend.

Now that we're using SWR, we have less of a need for hooks like
useNodeData that return a useSWR response alongside some mutation
callbacks. SWR makes it easy to mutate throughout the UI without
needing access to the original data state in order to reflect
updates. So, we can fetch data without having to tie it to post
callbacks that have to be passed around through components.

In an effort to consolidate our posting endpoints, and make it
easier to add more api handlers cleanly in the future, this change
introduces a new `useAPI` hook that returns a single `api` callback
that can make any changes from any component in the UI. The hook
itself handles using SWR to mutate the relevant data keys, which
get globally reflected throughout the UI.

As a concurrent cleanup, node types are also moved to their own
types.ts file, to consolidate data types across the app.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Andrew Dunham 9fd29f15c7 util/cache: add package for general-purpose caching
This package allows caching arbitrary key/value pairs in-memory, along
with an interface implemented by the cache types.

Extracted from #7493

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic8ca820927c456721cf324a0c8f3882a57752cc9
6 months ago
Adrian Dewhurst f706a3abd0 ipn/ipnlocal, util/syspolicy: add auto update policy
Due to the Sparkle preference naming convention, macsys already has a
policy key named "ApplyUpdates" that merely shows or hides the menu
item that controls if auto updates are installed, rather than directly
controlling the setting.

For other platforms, we are going to use "InstallUpdates" instead
because it seemed better than the other options that were considered.

Updates ENG-2127
Updates tailscale/corp#16247

Change-Id: Ia6a125beb6b4563d380c6162637ce4088f1117a0
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
6 months ago
Sonia Appasamy ef4f1e3a0b client/web: add loading state to app
Displays animated loading dots while initial auth and data endpoints
are fetching.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Andrew Dunham 3f576fc4ca ci: run 'go vet' in golangci-lint; fix errors in tests
Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ice78fc907bad24c1de749a1595e212ef2db4b8bb
6 months ago
Mario Minardi f5f21c213c
client/web: add additional web client metrics logging (#10462)
Add additional web client metric logging. Namely, add logging events for
auth / deauth, enable / disable using exit node, enable / disable SSH,
enable / disable advertise routes, and click events on the device details
button.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
6 months ago
Naman Sood 97f84200ac
wgengine/router: implement UpdateMagicsockPort for CallbackRouter (#10494)
Updates #9084.

Signed-off-by: Naman Sood <mail@nsood.in>
6 months ago
Sonia Appasamy 95655405b8 client/web: start using swr for some fetching
Adds swr to the web client, and starts by using it from the
useNodeData hook.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy 014ae98297 client/web: style tweaks
Style changes made in live pairing session.

Updates #10261

Co-authored-by: Will Norris <will@tailscale.com>
Co-authored-by: Alessandro Mingione <alessandro@tailscale.com>
Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Adrian Dewhurst 1a4d423328 ipn/ipnlocal: add additional syspolicy enforcement
This adds support for enforcing exit node LAN access, DNS and subnet
routes.

Adding new preference policies was getting repetitive, so this turns
some of the boilerplate into a table.

Updates tailscale/corp#15585
Updates ENG-2240

Change-Id: Iabd3c42b0ae120b3145fac066c5caa7fc4d67824
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
6 months ago
Sonia Appasamy 2731a9da36 client/web: fix exit node selector styling
Remove padding on top of search bar, remove rounded corners of
bottom border of earch bar, and add auto focus.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Adrian Dewhurst af32d1c120 ipn/ipnlocal: better enforce system policies
Previously, policies affected the default prefs for a new profile, but
that does not affect existing profiles. This change ensures that
policies are applied whenever preferences are loaded or changed, so a
CLI or GUI client that does not respect the policies will still be
overridden.

Exit node IP is dropped from this PR as it was implemented elsewhere
in #10172.

Fixes tailscale/corp#15585

Change-Id: Ide4c3a4b00a64e43f506fa1fab70ef591407663f
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
6 months ago
Sonia Appasamy ac6f671c54 ipn/localapi: use clientupdate.CanAutoUpdate from serveUpdateCheck
Fixes #10486

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy a54a4f757b client/web: add licenses and policies links
Adds a footer to the device details page that mirrors license and
policy content on other Tailscale clients.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy cc6729a0bc .github/workflows: add webclient workflow
Add workflow to run yarn lint/test/format-check against the web
client on pull requests.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Mario Minardi 4a24db852a
client/web: use IPv4 instead of IP in login view (#10483)
The IP property in node data was renamed to IPv4 but refactoring the usage
of the property was missed in this file.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
6 months ago
Denton Gentry 137e9f4c46 net/portmap: add test of Mikrotik Root Desc XML.
Unfortunately in the test we can't reproduce the failure seen
in the real system ("SOAP fault: UPnPError")

Updates https://github.com/tailscale/tailscale/issues/8364

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
6 months ago
Naman Sood d46a4eced5
util/linuxfw, wgengine: allow ingress to magicsock UDP port on Linux (#10370)
* util/linuxfw, wgengine: allow ingress to magicsock UDP port on Linux

Updates #9084.

Currently, we have to tell users to manually open UDP ports on Linux when
certain firewalls (like ufw) are enabled. This change automates the process of
adding and updating those firewall rules as magicsock changes what port it
listens on.

Signed-off-by: Naman Sood <mail@nsood.in>
6 months ago
Andrew Lytvynov aad5fb28b1
go.toolchain.rev: bump to 1.21.5 (#10475)
Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Claire Wang 47db67fef5
util/syspolicy: add policy counters (#10471)
Fixes tailscale/corp#16138

Signed-off-by: Claire Wang <claire@tailscale.com>
6 months ago
Sonia Appasamy a95b3cbfa8 client/web: add copyable components throughout UI
Updates the IP address on home view to open a copyable list of node
addresses on click. And makes various values on the details view
copyable text items, mirroring the machine admin panel table.

As part of these changes, pulls the AddressCard, NiceIP and QuickCopy
components from the admin panel, with the AddressCard slightly modified
to avoid needing to also pull in the CommandLine component.

A new toaster interface is also added, allowing us to display success
and failure toasts throughout the UI. The toaster code is slightly
modified from it's admin form to avoid the need for some excess
libraries.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Naman Sood 650c67a0a1 tailcfg: bump CapabilityVersion for Linux netfilter NodeAttrs and c2n endpoint
Updates tailscale/corp#14029.

Signed-off-by: Naman Sood <mail@nsood.in>
6 months ago
Naman Sood 0a59754eda linuxfw,wgengine/route,ipn: add c2n and nodeattrs to control linux netfilter
Updates tailscale/corp#14029.

Signed-off-by: Naman Sood <mail@nsood.in>
6 months ago
James Tucker 215f657a5e wgengine/router: create netfilter runner in setNetfilterMode
This will enable the runner to be replaced as a configuration side
effect in a later change.

Updates tailscale/corp#14029

Signed-off-by: James Tucker <james@tailscale.com>
6 months ago
Adrian Dewhurst 94a64c0017 util/syspolicy: rename incorrectly named policy keys
These keys were intended to match the Apple platforms, but accidentally
used the wrong name.

Updates ENG-2133

Change-Id: I9ed7a17919e34e2d8896a5c64efc4d0c0003166e
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
6 months ago
License Updater 70f201c691 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
6 months ago
License Updater 9095518c2d licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
6 months ago
Matt Layher a217f1fccf all: fix nilness issues
Signed-off-by: Matt Layher <mdlayher@gmail.com>
6 months ago
Will Norris c5208f8138 client/web: small tweaks for small screens
Add left and right padding around entire client so that the cards don't
run into the side of the screen. Also tighten up vertical spacing in
couple of places.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Andrew Dunham c4ccdd1bd1 net/interfaces: ensure we return valid 'self' IP in LikelyHomeRouterIP
Before this fix, LikelyHomeRouterIP could return a 'self' IP that
doesn't correspond to the gateway address, since it picks the first
private address when iterating over the set interfaces as the 'self' IP,
without checking that the address corresponds with the
previously-detected gateway.

This behaviour was introduced by accident in aaf2df7, where we deleted
the following code:

    for _, prefix := range privatev4s {
        if prefix.Contains(gateway) && prefix.Contains(ip) {
            myIP = ip
            ok = true
            return
        }
    }

Other than checking that 'gateway' and 'ip' were private IP addresses
(which were correctly replaced with a call to the netip.Addr.IsPrivate
method), it also implicitly checked that both 'gateway' and 'ip' were a
part of the *same* prefix, and thus likely to be the same interface.

Restore that behaviour by explicitly checking pfx.Contains(gateway),
which, given that the 'ip' variable is derived from our prefix 'pfx',
ensures that the 'self' IP will correspond to the returned 'gateway'.

Fixes #10466

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Iddd2ee70cefb9fb40071986fefeace9ca2441ee6
6 months ago
Mario Minardi 6b083a8ddf
client/web: add metric logging logic to the web client (#10434)
Add metric logging logic for the web client frontend. This is an initial
pass of adding the base logic, plus a single point where it is used for
validation that the logging is working correctly. More metric logging
calls will follow in subsquent PRs.

Updates https://github.com/tailscale/tailscale/issues/10261

Signed-off-by: Mario Minardi <mario@tailscale.com>
6 months ago
Will Norris 9c4b73d77d client/web: handle login client inside an iframe
If the login client is inside an iframe, open the management client in a
new window, since it can't be loaded in the frame.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Will Norris 9441a4e15d client/web: render 404 message in empty card
Switch the "feature disabled" page to use the same treatment.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy 65643f6606 client/web: update device and connected icon
Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Will Norris f5989f317f client/web: handle offline exit nodes
If the currently selected exit node is offline, render the exit node
selector in red with an error message. Update exit nodes in the dropdown
to indicate if they are offline, and don't allow them to be selected.

This also updates some older color values to use the new colors.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy b144391c06 client/web: add cancel button to subnet router input section
Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy 95e9d22a16 client/web: button, link, and other small UI updates
Makes the following changes:
* Use “link” class in various spots
* Remove button appearance on Exit Node dropdown in readonly mode
* Update `-stone-` colors to `-gray-` (couple spots missed by
  original color config commit)
* Pull full ui/button component from admin panel, and update
  buttons throughout UI to use this component
* Remove various buttons in readonly view to match mocks
* Add route (and “pending approval”) highlights to Subnet router
  settings card
* Delete legacy client button styles from index.css
* Fix overflow of IPv6 address on device details view

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Aaron Klotz 64a26b221b net/dns: use an additional registry setting to disable dynamic DNS updates for our interface on Windows
Fixes #9775

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
6 months ago
Irbe Krumina 49fd0a62c9
cmd/k8s-operator: generate static kube manifests from the Helm chart. (#10436)
* cmd/k8s-operator: generate static manifests from Helm charts

This is done to ensure that there is a single source of truth
for the operator kube manifests.
Also adds linux node selector to the static manifests as
this was added as a default to the Helm chart.

Static manifests can now be generated by running
`go generate tailscale.com/cmd/k8s-operator`.

Updates tailscale/tailscale#9222

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
Andrew Lytvynov 263e01c47b
wgengine/filter: add protocol-agnostic packet checker (#10446)
For use in ACL tests, we need a way to check whether a packet is allowed
not just with TCP, but any protocol.

Updates #3561

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Flakes Updater c85532270f go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
6 months ago
Adrian Dewhurst 2003d1139f go.mod: update certstore
Updates tailscale/coral#118

Change-Id: Ie535ab890f95d13d050b2acc7d4ad1e3f8316877
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
6 months ago
Will Norris f9550e0bed client/web: indicate if ACLs prevent access
Use the packet filter rules to determine if any device is allowed to
connect on port 5252.  This does not check whether a specific device can
connect (since we typically don't know the source device when this is
used).  Nor does it specifically check for wide-open ACLs, which is
something we may provide a warning about in the future.

Update the login popover content to display information when the src
device is unable to connect to the dst device over its Tailscale IP. If
we know it's an ACL issue, mention that, otherwise list a couple of
things to check. In both cases, link to a placeholder URL to get more
information about web client connection issues.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy 5e125750bc client/web: center and fix height of header
Centers login pill with Tailscale icon, and fixes height of login
pill.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
OSS Updater f13255d54d go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
6 months ago
Sonia Appasamy 7a4ba609d9 client/web: show features based on platform support
Hiding/disabling UI features when not available on the running
client.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy 7d61b827e8 client/web: adjust colors and some UI margins
Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy b155c7a091 client/web: move postcss config into package.json
A little cleanup.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Aaron Klotz db39a43f06 util/winutil: add support for restarting Windows processes in specific sessions
This PR is all about adding functionality that will enable the installer's
upgrade sequence to terminate processes belonging to the previous version,
and then subsequently restart instances belonging to the new version within
the session(s) corresponding to the processes that were killed.

There are multiple parts to this:

* We add support for the Restart Manager APIs, which allow us to query the
  OS for a list of processes locking specific files;
* We add the RestartableProcess and RestartableProcesses types that query
  additional information about the running processes that will allow us
  to correctly restart them in the future. These types also provide the
  ability to terminate the processes.
* We add the StartProcessInSession family of APIs that permit us to create
  new processes within specific sessions. This is needed in order to
  properly attach a new GUI process to the same RDP session and desktop that
  its previously-terminated counterpart would have been running in.
* I tweaked the winutil token APIs again.
* A lot of this stuff is pretty hard to test without a very elaborate
  harness, but I added a unit test for the most complicated part (though it
  requires LocalSystem to run).

Updates https://github.com/tailscale/corp/issues/13998

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
6 months ago
Andrew Lytvynov 59d1077e28
clientupdate: cleanup tailscale binary copies on Windows (#10433)
When updating on Windows, we make a copy of the tailscale.exe file in a
temp directory to perform the update, because the original tailscale.exe
gets deleted during the update.

This can eat up disk space if a machine is stuck doing repeated failed
update attempts. Clean up old copies explicitly before making a new one,
same as we do with MSIs.

Updates #10082

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Marwan Sulaiman b819f66eb1 tsweb: propagate RequestID via context and entire request
The recent addition of RequestID was only populated if the
HTTP Request had returned an error. This meant that the underlying
handler has no access to this request id and any logs it may have
emitted were impossible to correlate to that request id. Therefore,
this PR adds a middleware to generate request ids and pass them
through the request context. The tsweb.StdHandler automatically
populates this request id if the middleware is being used. Finally,
inner handlers can use the context to retrieve that same request id
and use it so that all logs and events can be correlated.

Updates #2549

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
6 months ago
Juergen Knaack c27aa9e7ff net/dns: fix darwin dns resolver files
putting each nameserver on one line in /etc/resolver/<domain>

fixes: #10134
Signed-off-by: Juergen Knaack <jk@jk-1.de>
6 months ago
Sonia Appasamy cbd0b60743 client/web: remove ControlAdminURL override
Was setting this for testing, snuck into the merged version.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy bcc9b44cb1 client/web: hide admin panel links for non-tailscale control servers
Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Claire Wang 8af503b0c5
syspolicy: add exit node related policies (#10172)
Adds policy keys ExitNodeID and ExitNodeIP.
Uses the policy keys to determine the exit node in preferences.
Fixes tailscale/corp#15683

Signed-off-by: Claire Wang <claire@tailscale.com>
6 months ago
Sonia Appasamy ecd1ccb917 client/web: add subnet routes view
Add UI view for mutating the node's advertised subnet routes.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy 7aa981ba49 client/web: remove duplicate WhoIs call
Fixes a TODO in web.authorizeRequest.

`getSession` calls `WhoIs` already. Call `getSession` earlier in
`authorizeRequest` so we can avoid the duplicate `WhoIs` check on
the same request.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Sonia Appasamy bc4e303846 ipn/ipnstate: add AllowedIPs to PeerStatus
Adds AllowedIPs to PeerStatus, allowing for easier lookup of the
routes allowed to be routed to a node. Will be using the AllowedIPs
of the self node from the web client interface to display approval
status of advertised routes.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Andrew Lytvynov ac4b416c5b
cmd/tailscale,ipn/ipnlocal: pass available update as health message (#10420)
To be consistent with the formatting of other warnings, pass available
update health message instead of handling ClientVersion in he CLI.

Fixes #10312

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Will Norris 26db9775f8
client/web: skip check mode for non-tailscale.com control servers (#10413)
client/web: skip check mode for non-tailscale.com control servers

Only enforce check mode if the control server URL ends in
".tailscale.com".  This allows the web client to be used with headscale
(or other) control servers while we work with the project to add check
mode support (tracked in juanfont/headscale#1623).

Updates #10261

Co-authored-by: Sonia Appasamy <sonia@tailscale.com>
Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
Signed-off-by: Will Norris <will@tailscale.com>
6 months ago
Sonia Appasamy ab0e25beaa client/web: fix Vite dev server build error
6e30c9d1f added eslint to the web client. As a part of that change,
the existing yarn.lock file was removed and yarn install run to build
with a clean yarn dependencies set with latest versions. This caused
a change in the "vite-plugin-rewrite-all" package that fails at build
time with our existing vite config. This is a known bug with some
suggested fixes:
https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only

Rather than editing our package.json type, this commit reverts back
the yarn.lock file to it's contents at the commit just before 6e30c9d1f
and then only runs yarn install to add the new eslint packages, rather
than installing the latest versions of all packages.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Tom DNetto 8a660a6513 ipn/ipnlocal: update hostinfo when app connector state is toggled
Updates: https://github.com/tailscale/corp/issues/16041
Signed-off-by: Tom DNetto <tom@tailscale.com>
6 months ago
Sonia Appasamy 6e30c9d1fe client/web: add eslint
Add eslint to require stricter typescript rules, particularly around
required hook dependencies. This commit also updates any files that
were now throwing errors with eslint.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Andrew Lytvynov 5a9e935597
clientupdate: implement update for Unraid (#10344)
Use the [`plugin`
CLI](https://forums.unraid.net/topic/72240-solved-is-there-a-way-to-installuninstall-plugins-from-script/#comment-676870)
to fetch and apply the update.

Updates https://github.com/tailscale/tailscale/issues/10184

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Jordan Whited 5e861c3871
wgengine/netstack: disable RACK on Windows (#10402)
Updates #9707

Signed-off-by: Jordan Whited <jordan@tailscale.com>
6 months ago
Sonia Appasamy 5f40b8a0bc scripts/check_license_headers: enforce license on ts/tsx files
Enforcing inclusion of our OSS license at the top of .ts and .tsx
files. Also updates any relevant files in the repo that were
previously missing the license comment. An additional `@license`
comment is added to client/web/src/index.tsx to preserve the
license in generated Javascript.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Jenny Zhang 09b4914916 tka: clarify field comment
Updates #cleanup
Signed-off-by: Jenny Zhang <jz@tailscale.com>
6 months ago
Denton Gentry 67f3b2a525 tsnet: add CapturePcap method for debugging
Application code can call the tsnet s.CapturePcap(filename) method
to write all packets, sent and received, to a pcap file. The cleartext
packets are written, outside the Wireguard tunnel. This is expected
to be useful for debugging.

Updates https://github.com/tailscale/tailscale/issues/9707

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
6 months ago
Sonia Appasamy b247435d66 client/web: scroll exit node dropdown to top on search
When search input changes, reset the scroll to the top of the
dropdown list.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
6 months ago
Jenny Zhang d5d84f1a68 cmd/tailscale: also warn about IP forwarding if using CLI set
We warn users about IP forwarding being disabled when using
`--avertise-routes` in `tailscale up`, this adds the same warnings
to `tailscale set`.

Updates tailscale/corp#9968
Signed-off-by: Jenny Zhang <jz@tailscale.com>
6 months ago
Irbe Krumina 18ceb4e1f6
cmd/{containerboot,k8s-operator}: allow users to define tailnet egress target by FQDN (#10360)
* cmd/containerboot: proxy traffic to tailnet target defined by FQDN

Add a new Service annotation tailscale.com/tailnet-fqdn that
users can use to specify a tailnet target for which
an egress proxy should be deployed in the cluster.

Updates tailscale/tailscale#10280

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
David Anderson 2a01df97b8 flake.nix: use vendorHash instead of vendorSha256
vendorSha256 is getting retired, and throws warning in builds.

Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
6 months ago
Flakes Updater 6b395f6385 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
6 months ago
Charlotte Brandhorst-Satzkorn 9e63bf5fd6 words: crikey! what a beauty of a list
If I have to add a tail, or a scale, mate, I will add it.

Updates tailscale/corp#14698

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
6 months ago
Tom DNetto 611e0a5bcc appc,ipn/local: support wildcard when matching app-connectors
Updates: ENG-2453
Signed-off-by: Tom DNetto <tom@tailscale.com>
6 months ago
Jordan Whited 1af7f5b549
wgengine/magicsock: fix typo in Conn.handlePingLocked() (#10365)
Updates #cleanup

Signed-off-by: Jordan Whited <jordan@tailscale.com>
6 months ago
Andrew Dunham 5aa7687b21 util/httpm: don't run test if .git doesn't exist
Updates #9635

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I9089200f9327605036c88fc12834acece0c11694
6 months ago
Claire Wang afacf2e368
containerboot: Add TS_ACCEPT_ROUTES (#10176)
Fixes tailscale/corp#15596

Signed-off-by: Claire Wang <claire@tailscale.com>
6 months ago
Gabriel Martinez 128d3ad1a9
cmd/k8s-operator: helm chart add missing keys (#10296)
* cmd/k8s-operator: add missing keys to Helm values file

Updates  #10182

Signed-off-by: Gabriel Martinez <gabrielmartinez@sisti.pt>
6 months ago
Jordan Whited e1d0d26686
go.mod: bump wireguard-go (#10352)
This pulls in tailscale/wireguard-go@8cc8b8b and
tailscale/wireguard-go@cc193a0, which improve throughput and latency
under load.

Updates tailscale/corp#11061

Signed-off-by: Jordan Whited <jordan@tailscale.com>
6 months ago
Cole Helbling a8647b3c37
flake: fixup version embedding (#9997)
It looks like `gitCommitStamp` is the new "entrypoint" for setting this
information.

Fixes #9996.

Signed-off-by: Cole Helbling <cole.helbling@determinate.systems>
6 months ago
Percy Wegmann 17501ea31a ci: report test coverage to coveralls.io
This records test coverage for the amd64 no race tests and uploads the
results to coveralls.io.

Updates #cleanup

Signed-off-by: Ox Cart <ox.to.a.cart@gmail.com>
6 months ago
Irbe Krumina 66471710f8
cmd/k8s-operator: truncate long StatefulSet name prefixes (#10343)
Kubernetes can generate StatefulSet names that are too long and result in invalid Pod revision hash label values.
Calculate whether a StatefulSet name generated for a Service or Ingress
will be too long and if so, truncate it.

Updates tailscale/tailscale#10284

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
Andrew Lytvynov 2c1f14d9e6
util/set: implement json.Marshaler/Unmarshaler (#10308)
Marshal as a JSON list instead of a map. Because set elements are
`comparable` and not `cmp.Ordered`, we cannot easily sort the items
before marshaling.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
6 months ago
Irbe Krumina dd8bc9ba03
cmd/k8s-operator: log user/group impersonated by apiserver proxy (#10334)
Updates tailscale/tailscale#10127

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
Irbe Krumina 4f80f403be
cmd/k8s-operator: fix chart syntax error (#10333)
Updates #9222

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
6 months ago
License Updater 2fa219440b licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
7 months ago
David Anderson f867392970 cmd/tailscale/cli: add debug function to print the netmap
It's possible to do this with a combination of watch-ipn and jq, but looking
at the netmap while debugging is quite common, so it's nice to have a one-shot
command to get it.

Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
7 months ago
David Anderson fd22145b52 cmd/tailscale/cli: make 'debug watch-ipn' play nice with jq
jq doens't like non-json output in the json stream, and works more happily
when the input stream EOFs at some point. Move non-json words to stderr, and
add a parameter to stop watching and exit after some number of objects.

Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
7 months ago
Ryan Petris c4855fe0ea Fix Empty Resolver Set
Config.singleResolverSet returns true if all routes have the same resolvers,
even if the routes have no resolvers. If none of the routes have a specific
resolver, the default should be used instead. Therefore, check for more than
0 instead of nil.

Signed-off-by: Ryan Petris <ryan@petris.net>
7 months ago
Uri Gorelik b88929edf8 Fix potential goroutine leak in syncs/watchdog.go
Depending on how the preemption will occur, in some scenarios sendc
would have blocked indefinitely even after cancelling the context.

Fixes #10315

Signed-off-by: Uri Gorelik <uri.gore@gmail.com>
7 months ago
Flakes Updater e7cad78b00 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
7 months ago
OSS Updater fc8488fac0 go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
7 months ago
Will Norris 42dc843a87 client/web: add advanced login options
This adds an expandable section of the login view to allow users to
specify an auth key and an alternate control URL.

Input and Collapsible components and accompanying styles were brought
over from the adminpanel.

Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Flakes Updater f0613ab606 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
7 months ago
OSS Updater 3402998c1c go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
7 months ago
Sonia Appasamy 38ea8f8c9c client/web: add Inter font
Adds Inter font and uses it as the default for the web UI.
Creates a new /assets folder to house the /fonts, and moves /icons
to live here too.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Marwan Sulaiman 2dc0645368 ipn/ipnlocal,cmd/tailscale: persist tailnet name in user profile
This PR starts to persist the NetMap tailnet name in SetPrefs so that tailscaled
clients can use this value to disambiguate fast user switching from one tailnet
to another that are under the same exact login. We will also try to backfill
this information during backend starts and profile switches so that users don't
have to re-authenticate their profile. The first client to use this new
information is the CLI in 'tailscale switch -list' which now uses text/tabwriter
to display the ID, Tailnet, and Account. Since account names are ambiguous, we
allow the user to pass 'tailscale switch ID' to specify the exact tailnet they
want to switch to.

Updates #9286

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
7 months ago
Sonia Appasamy e75be017e4 client/web: add exit node selector
Add exit node selector (in full management client only) that allows
for advertising as an exit node, or selecting another exit node on
the Tailnet for use.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
License Updater 0e27ec2cd9 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
7 months ago
License Updater 4f05cf685e licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
7 months ago
License Updater 05298f4336 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
7 months ago
Will Norris f880c77df0 client/web: split login from nodeUpdate
This creates a new /api/up endpoint which is exposed in the login
client, and is solely focused on logging in. Login has been removed from
the nodeUpdate endpoint.

This also adds support in the LoginClientView for a stopped node that
just needs to reconnect, but not necessarily reauthenticate.  This
follows the same pattern in `tailscale up` of just setting the
WantRunning user pref.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
James Tucker 28684b0538 cmd/tailscale/cli: correct app connector help text in set
Updates tailscale/corp#15437
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Sonia Appasamy 980f1f28ce client/web: hide unimplemented links
Hiding links to unimplemented settings pages.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Brad Fitzpatrick fb829ea7f1 control/controlclient: support incremental packet filter updates [capver 81]
Updates #10299

Change-Id: I87e4235c668a1db7de7ef1abc743f0beecb86d3d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Claire Wang b8a2aedccd
util/syspolicy: add caching handler (#10288)
Fixes tailscale/corp#15850
Co-authored-by: Adrian Dewhurst <adrian@tailscale.com>
Signed-off-by: Claire Wang <claire@tailscale.com>
7 months ago
Ox Cart 719ee4415e ssh/tailssh: use control server time instead of local time
This takes advantage of existing functionality in ipn/ipnlocal to adjust
the local clock based on periodic time signals from the control server.
This way, when checking things like SSHRule expirations, calculations are
protected incorrectly set local clocks.

Fixes tailscale/corp#15796

Signed-off-by: Percy Wegmann <percy@tailscale.com>
7 months ago
Sonia Appasamy bd534b971a {client/web},{ipn/ipnlocal}: replace localapi debug-web-client endpoint
This change removes the existing debug-web-client localapi endpoint
and replaces it with functions passed directly to the web.ServerOpts
when constructing a web.ManageServerMode client.

The debug-web-client endpoint previously handled making noise
requests to the control server via the /machine/webclient/ endpoints.
The noise requests must be made from tailscaled, which has the noise
connection open. But, now that the full client is served from
tailscaled, we no longer need to proxy this request over the localapi.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Brad Fitzpatrick 4d196c12d9 health: don't report a warning in DERP homeless mode
Updates #3363
Updates tailscale/corp#396

Change-Id: Ibfb0496821cb58a78399feb88d4206d81e95ca0f
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Brad Fitzpatrick cca27ef96a ipn/ipnlocal: add c2n method to check on TLS cert fetch status
So the control plane can delete TXT records more aggressively
after client's done with ACME fetch.

Updates tailscale/corp#15848

Change-Id: I4f1140305bee11ee3eee93d4fec3aef2bd6c5a7e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Irbe Krumina 664ebb14d9
cmd/containerboot: fix unclean shutdown (#10035)
* cmd/containerboot: shut down cleanly on SIGTERM

Make sure that tailscaled watcher returns when
SIGTERM is received and also that it shuts down
before tailscaled exits.

Updates tailscale/tailscale#10090

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
7 months ago
Sonia Appasamy 7238586652 client/web: fix margins on login popover
Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Will Norris 5aa22ff3eb tsnet: add option to run integrated web client
Updates #10261

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Tyler Smalley 90eb5379f4
ipn/ipnlocal: log and don't return full file serve error (#10174)
Previously we would return the full error from Stat or Open, possibily exposing the full file path. This change will log the error and return the generic error message "an error occurred reading the file or directory".

Updates tailscale/corp#15485

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
7 months ago
Sonia Appasamy 4f409012c5 client/web: when readonly, add check for TS connection
When the viewing user is accessing a webclient not over Tailscale,
they must connect over Tailscale before being able to log into the
full management client, which is served over TS. This change adds
a check that the user is able to access the node's tailscale IP.
If not able to, the signin button is disabled. We'll also be adding
Copy here to help explain to the user that they must connect to
Tailscale before proceeding.

Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Will Norris 33147c4591 .github: build gocross using regular GOPROXY settings
This `go get` action has been running very slowly, and I'm pretty sure
it's because we're building gocross on the first `./tool/go` run, and
because we've set `GOPROXY=direct`, it's going directly to GitHub to
fetch all of the gocross dependencies.

Updates #cleanup

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Flakes Updater a3c11b87c6 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
7 months ago
OSS Updater 146c4bacde go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
7 months ago
Will Norris d01fa857b1 client/web: allow login client to still run tailscale up
I don't believe this has ever worked, since we didn't allow POST
requests in the login client. But previously, we were primarily using
the legacy client, so it didn't really matter. Now that we've removed
the legacy client, we have no way to login.

This fixes the login client, allowing it to login, but it still needs to
be refactored to expose a dedicated login method, without exposing all
the node update functionality.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Brad Fitzpatrick 3bd382f369 wgengine/magicsock: add DERP homeless debug mode for testing
In DERP homeless mode, a DERP home connection is not sought or
maintained and the local node is not reachable.

Updates #3363
Updates tailscale/corp#396

Change-Id: Ibc30488ac2e3cfe4810733b96c2c9f10a51b8331
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Jordan Whited 2ff54f9d12
wgengine/magicsock: move trustBestAddrUntil forward on non-disco rx (#10274)
This is gated behind the silent disco control knob, which is still in
its infancy. Prior to this change disco pong reception was the only
event that could move trustBestAddrUntil forward, so even though we
weren't heartbeating, we would kick off discovery pings every
trustUDPAddrDuration and mirror to DERP.

Updates #540

Signed-off-by: Jordan Whited <jordan@tailscale.com>
7 months ago
Maisem Ali 57129205e6 cmd/tailscaled: make tun mode default on gokrazy
Now that we have nftable support this works fine and force
it on gokrazy since 25a8daf405.

Updates gokrazy/gokrazy#209

Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Sonia Appasamy 96ad9b6138 client/web: remove legacy-client-view.tsx
Updates #10261

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy 055394f3be ipn/ipnlocal: add mutex to webClient struct
Adds a new sync.Mutex field to the webClient struct, rather than
using the general LocalBackend mutex. Since webClientGetOrInit
(previously WebClientInit) gets called on every connection, we
want to avoid holding the lock on LocalBackend just to check if
the server is initialized.

Moves all web_client.go funcs over to using the webClient.mu field.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Maisem Ali 7d4221c295 cmd/tsidp: add start of OIDC Tailscale IdP
Updates #10263

Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Change-Id: I240bc9b5ecf2df6f92c45929d105fde66c06a860
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Sonia Appasamy 2dbd546766 client/web: remove DebugMode from GET /api/data
No longer using this! Readonly state fully managed via auth endpoint.
Also getting rid of old Legacy server mode.

A #cleanup

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy 6f7a1b51a8 ipn/ipnlocal: rename SetWebLocalClient to ConfigureWebClient
For consistency with the "WebClient" naming of the other functions
here. Also fixed a doc typo.

A #cleanup

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Naman Sood d5c460e83c
client/{tailscale,web}: add initial webUI frontend for self-updates (#10191)
Updates #10187.

Signed-off-by: Naman Sood <mail@nsood.in>
7 months ago
James Tucker 245ddb157b appc: fix DomainRoutes copy
The non-referential copy destination doesn't extend the map contents,
but also the read of a non-key is returning a zero value not bound to
the map contents in any way.

Updates tailscale/corp#15657

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Adrian Dewhurst b8ac3c5191 util/syspolicy: add some additional policy keys
These policy keys are supported on Apple platforms in Swift code; in
order to support them on platforms using Go (e.g. Windows), they also
need to be recorded here.

This does not affect any code, it simply adds the constants for now.

Updates ENG-2240
Updates ENG-2127
Updates ENG-2133

Change-Id: I0aa9863a3641e5844479da3b162761452db1ef42
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
7 months ago
Adrian Dewhurst 1ef5bd5381 util/osdiag, util/winutil: expose Windows policy key
The Windows base registry key is already exported but the policy key was
not. util/osdiag currently replicates the string rather than the
preferred approach of reusing the constant.

Updates #cleanup

Change-Id: I6c1c45337896c744059b85643da2364fb3f232f2
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
7 months ago
Aaron Klotz 855f79fad7 cmd/tailscaled, util/winutil: changes to process and token APIs in winutil
This PR changes the internal getTokenInfo function to use generics.
I also removed our own implementations for obtaining a token's user
and primary group in favour of calling the ones now available in
x/sys/windows.

Furthermore, I added two new functions for working with tokens, logon
session IDs, and Terminal Services / RDP session IDs.

I modified our privilege enabling code to allow enabling of multiple
privileges via one single function call.

Finally, I added the ProcessImageName function and updated the code in
tailscaled_windows.go to use that instead of directly calling the
underlying API.

All of these changes will be utilized by subsequent PRs pertaining to
this issue.

Updates https://github.com/tailscale/corp/issues/13998

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
7 months ago
Will Norris 03e780e9af client/web: disable the "disable" button when disabled
We currently disable the exit-node drop down selector when the user is
in read-only mode, but we missed disabling the "Disable" button also.
Previously, it would display an error when clicked.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris 9b537f7c97 ipn: remove the preview-webclient node capability
Now that 1.54 has released, and the new web client will be included in
1.56, we can remove the need for the node capability. This means that
all 1.55 unstable builds, and then eventually the 1.56 build, will work
without setting the node capability.

The web client still requires the "webclient" user pref, so this does
NOT mean that the web client will be on by default for all devices.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris 303a1e86f5 cmd/tailscale: expose --webclient for all builds
This removes the dev/unstable build check for the --webclient flag on
`tailscale set`, so that it will be included in the next major stable
release (1.56)

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Andrew Dunham e33bc64cff net/dnsfallback: add singleflight to recursive resolver
This prevents running more than one recursive resolution for the same
hostname in parallel, which can use excessive amounts of CPU when called
in a tight loop. Additionally, add tests that hit the network (when
run with a flag) to test the lookup behaviour.

Updates tailscale/corp#15261

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I39351e1d2a8782dd4c52cb04b3bd982eb651c81e
7 months ago
Denton Gentry a40e918d63 VERSION.txt: this is v1.55.0
Signed-off-by: Denton Gentry <dgentry@tailscale.com>
7 months ago
James Tucker e866ee9268 types/appctype: correct app-connector cap name in documentation
Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Sonia Appasamy bb31912ea5 cmd/cli: remove --webclient flag from up
Causing issues building a stable release. Getting rid of the flag
for now because it was only available in unstable, can still be
turned on through localapi.

A #cleanup

Co-authored-by: Will Norris <will@tailscale.com>
Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Will Norris 1cb8d2ffdd ipn/ipnlocal: only call serve handler if non-nil
return early if handler is nil. Go ahead and return the error from
handler, though in this case the caller isn't doing anything with it
(which has always been the case).

Updates #10177
Updates #10251

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Andrea Barisani 05d4210dbe adjust build tags for tamago
Signed-off-by: Andrea Barisani <andrea@inversepath.com>
7 months ago
Will Norris b7918341f9 ipn/ipnlocal: call serve handler for local traffic
Tailscale serve maintains a set of listeners so that serve traffic from
the local device can be properly served when running in kernel
networking mode. #10177 refactored that logic so that it could be reused
by the internal web client as well. However, in my refactoring I missed
actually calling the serve handler to handle the traffic.

Updates #10177

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Flakes Updater e3dacb3e5e go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
7 months ago
Andrew Lytvynov c3f1bd4c0a
clientupdate: fix auto-update on Windows over RDP (#10242)
`winutil.WTSGetActiveConsoleSessionId` only works for physical desktop
logins and does not return the session ID for RDP logins. We need to
`windows.WTSEnumerateSessions` and find the active session.

Fixes https://github.com/tailscale/corp/issues/15772

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Will Norris 60957e1077 client/web: fix back button on devices with URL prefix
Move Header component inside Router so that links are relative to the
router base URL.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris fb984c2b71 client/web: server /index.html on 404 requests
In production, the asset handler is receiving requests for pages like
/details, which results in a 404. Instead, if we know the requested file
does not exist, serve the main index page and let wouter route it
appropriately on the frontend.

Updates tailscale/corp/#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris 74947ce459 client/web: only trigger check mode if not authed
After logging in, the `?check=now` query string is still present if it
was passed. Reloading the page causes a new check mode to be triggered,
even though the user has an active session. Only trigger the automatic
check mode if the user is not already able to manage the device.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris 79719f05a9 ipn/ipnlocal: remove web client listeners after close
This prevents a panic in some cases where WebClientShutdown is called
multiple times.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Sonia Appasamy 7c99a1763b client/web: fix panic on logout
Fix panic due to `CurrentTailnet` being nil.

Fixes tailscale/corp#15791

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
OSS Updater 063657c65f go.mod: update web-client-prebuilt module
Signed-off-by: OSS Updater <noreply+oss-updater@tailscale.com>
7 months ago
Will Norris 7399e56acd .github: add action for updating web-client-prebuilt module
Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Andrew Lytvynov 955e2fcbfb
ipn/ipnlocal: run "tailscale update" via systemd-run on Linux (#10229)
When we run tailscled under systemd, restarting the unit kills all child
processes, including "tailscale update". And during update, the package
manager will restart the tailscaled unit. Specifically on Debian-based
distros, interrupting `apt-get install` can get the system into a wedged
state which requires the user to manually run `dpkg --configure` to
recover.

To avoid all this, use `systemd-run` where available to run the
`tailscale update` process. This launches it in a separate temporary
unit and doesn't kill it when parent unit is restarted.

Also, detect when `apt-get install` complains about aborted update and
try to restore the system by running `dpkg --configure tailscale`. This
could help if the system unexpectedly shuts down during our auto-update.

Fixes https://github.com/tailscale/corp/issues/15771

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Jordan Whited c99488ea19
wgengine/magicsock: fix typo in endpoint.sendDiscoPing() docs (#10232)
Updates #cleanup

Signed-off-by: Jordan Whited <jordan@tailscale.com>
7 months ago
Tom DNetto 90a0aafdca cmd/tailscale: warn if app-connector is enabled without ip forwarding
Fixes: ENG-2446
Signed-off-by: Tom DNetto <tom@tailscale.com>
7 months ago
Brad Fitzpatrick 1825d2337b
ipn/ipnlocal: respect ExitNodeAllowLANAccess on iOS (#10230)
Updates tailscale/corp#15783

Change-Id: I1082fbfff61a241ebd3b8275be0f45e329b67561

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Sonia Appasamy c9bfb7c683 client/web: add Tailscale SSH view
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Brad Fitzpatrick 103c00a175 ipn/ipnlocal: clean up c2n handling's big switch, add a mux table
Updates #cleanup

Change-Id: I29ec03db91e7831a3a66a63dcf6ff8e3f72ab045
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Tom DNetto ce46d92ed2 go.{mod,sum}: update inet.af/tcpproxy to fix flaking test
```
[nix-shell:~/tailscale]$ ./tool/go test ./cmd/sniproxy --failfast --count 80
ok  	tailscale.com/cmd/sniproxy	127.085s
[nix-shell:~/tailscale]$ ./tool/go test ./cmd/sniproxy --failfast --count 80
ok  	tailscale.com/cmd/sniproxy	127.030s
```

Fixes: #10056
Signed-off-by: Tom DNetto <tom@tailscale.com>
7 months ago
Joe Tsai 975c5f7684
taildrop: lazily perform full deletion scan after first taildrop use (#10137)
Simply reading the taildrop directory can pop up security dialogs
on platforms like macOS. Avoid this by only performing garbage collection
of partial and deleted files after the first received taildrop file,
which would have prompted the security dialog window.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
7 months ago
Jordan Whited e848736927
control/controlknobs,wgengine/magicsock: implement SilentDisco toggle (#10195)
This change exposes SilentDisco as a control knob, and plumbs it down to
magicsock.endpoint. No changes are being made to magicsock.endpoint
disco behavior, yet.

Updates #540

Signed-off-by: Jordan Whited <jordan@tailscale.com>
Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Kristoffer Dalby fe7f7bff4f posture: ignore not found serial errors
Updates #5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
7 months ago
Sonia Appasamy 86c8ab7502 client/web: add readonly/manage toggle
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
James Tucker c54d680682 ipn,tailconfig: clean up unreleased and removed app connector service
This was never released, and is replaced by HostInfo.AppConnector.

Updates tailscale/corp#15437
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
James Tucker 0b6636295e tailcfg,ipn/ipnlocal: add hostinfo field to replace service entry
Updates tailscale/corp#15437
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Andrew Lytvynov 1f4a38ed49
clientupdate: add support for QNAP (#10179)
Use the `qpkg_cli` to check for updates and install them. There are a
couple special things about this compare to other updaters:
* qpkg_cli can tell you when upgrade is available, but not what the
  version is
* qpkg_cli --add Tailscale works for new installs, upgrades and
  reinstalling existing version; even reinstall of existing version
  takes a while

Updates #10178

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
James Tucker 45be37cb01 ipn/ipnlocal: ensure that hostinfo is updated on app connector preference changes
Some conditional paths may otherwise skip the hostinfo update, so kick
it off asynchronously as other code paths do.

Updates tailscale/corp#15437
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
James Tucker 933d201bba ipn/policy: mark AppConnector service as interesting
Updates #15437
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
James Tucker 1a143963ec appc: prevent duplication of wildcard entries on map updates
Updates #15437
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Andrew Lytvynov 6cce5fe001
go.toolchain.rev: bump to Go 1.21.4 (#10189)
Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Brad Fitzpatrick 53c4adc982 ssh/tailssh: add envknobs to force override forwarding, sftp, pty
Updates tailscale/corp#15735

Change-Id: Ib1303406be925c3231ce7e0950a173ad12626492
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Brad Fitzpatrick ffabe5fe21 ssh/tailssh: fix sftp metric increment location
We were incrementing the sftp metric on regular sessions
too, not just sftp.

Updates #cleanup

Change-Id: I63027a39cffb3e03397c6e4829b1620c10fa3130
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Naman Sood e57fd9cda4
ipn/{ipnlocal,ipnstate,localapi}: add localapi endpoints for client self-update (#10188)
* ipn/{ipnlocal,ipnstate,localapi}: add localapi endpoints for client self-update

Updates #10187.

Signed-off-by: Naman Sood <mail@nsood.in>

* depaware

Updates #10187.

Signed-off-by: Naman Sood <mail@nsood.in>

* address review feedback

Signed-off-by: Naman Sood <mail@nsood.in>

---------

Signed-off-by: Naman Sood <mail@nsood.in>
7 months ago
Andrew Lytvynov 55cd5c575b
ipn/localapi: only perform local-admin check in serveServeConfig (#10163)
On unix systems, the check involves executing sudo, which is slow.
Instead of doing it for every incoming request, move the logic into
localapi serveServeConfig handler and do it as needed.

Updates tailscale/corp#15405

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
James Tucker 73de6a1a95 appc: add support for matching wildcard domains
The app connector matches a configuration of "*.example.com" to mean any
sub-domain of example.com.

Updates #15437

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Jordan Whited 12d5c99b04
client/tailscale,ipn/{ipnlocal,localapi}: check UDP GRO config (#10071)
Updates tailscale/corp#9990

Signed-off-by: Jordan Whited <jordan@tailscale.com>
7 months ago
Andrew Lytvynov 1fc1077052
ssh/tailssh,util: extract new osuser package from ssh code (#10170)
This package is a wrapper for os/user that handles non-cgo builds,
gokrazy and user shells.

Updates tailscale/corp#15405

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Will Norris 09de240934 ipn/ipnlocal: allow connecting to local web client
The local web client has the same characteristic as tailscale serve, in
that it needs a local listener to allow for connections from the local
machine itself when running in kernel networking mode.

This change renames and adapts the existing serveListener to allow it to
be used by the web client as well.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Brad Fitzpatrick d36a0d42aa tsnet: check a bit harder for https in Server.ListenFunnel
This was mostly already fixed already indirectly in earlier
commits but add a last second length check to this slice so
it can't ever OOB.

Fixes #7860

Change-Id: I31ac17fc93b5808deb09ff34e452fe37c87ddf3a
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Andrew Lytvynov bff786520e
clientupdate,ipn/ipnlocal: fix c2n update on freebsd (#10168)
The c2n part was broken because we were not looking up the tailscale
binary for that GOOS. The rest of the update was failing at the `pkg
upgrade` confirmation prompt. We also need to manually restart
tailscaled after update.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Sonia Appasamy d544e80fc1 client/web: populate device details view
Fills /details page with real values, passed back from the /data
endpoint.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Brad Fitzpatrick d852c616c6 logtail: fix Logger.Write return result
io.Writer says you need to write completely on err=nil. (the result
int should be the same as the input buffer length)

We weren't doing that. We used to, but at some point the verbose
filtering was modifying buf before the final return of len(buf).

We've been getting lucky probably, that callers haven't looked at our
results and turned us into a short write error.

Updates #cleanup
Updates tailscale/corp#15664

Change-Id: I01e765ba35b86b759819e38e0072eceb9d10d75c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Tom DNetto 11a20f371a ipn/ipnlocal: fix nil control client panic while updating TKA head
As part of tailnet-lock netmap processing, the LocalBackend mutex
is unlocked so we can potentially make a network call. Its possible
(during shutdown or while the control client is being reset) for
b.cc to become nil before the lock is picked up again.

Fixes: #9554
Signed-off-by: Tom DNetto <tom@tailscale.com>
7 months ago
Tom DNetto 3496d62ed3 ipn/ipnlocal: add empty address to the app-connector localNets set
App connectors handle DNS requests for app domains over PeerAPI,
but a safety check verifies the requesting peer has at least permission
to send traffic to 0.0.0.0:53 (or 2000:: for IPv6) before handling the DNS
request. The correct filter rules are synthesized by the coordination server
and sent down, but the address needs to be part of the 'local net' for the
filter package to even bother checking the filter rules, so we set them here.
See: https://github.com/tailscale/corp/issues/11961 for more information.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: ENG-2405
7 months ago
Will Norris fdbe511c41 cmd/tailscale: add -webclient flag to up and set
Initially, only expose this flag on dev and unstable builds.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Charlotte Brandhorst-Satzkorn f937cb6794 tailcfg,ipn,appc: add c2n endpoint for appc domain routes
This change introduces a c2n endpoint that returns a map of domains to a
slice of resolved IP addresses for the domain.

Fixes tailscale/corp#15657

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
7 months ago
Andrew Lytvynov 63062abadc
clientupdate: check whether running as root early (#10161)
Check for root early, before we fetch the pkgs index. This avoids
several seconds delay for the command to tell you to sudo.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Andrew Lytvynov 9b158db2c6
ipn/localapi: require root or sudo+operator access for SetServeConfig (#10142)
For an operator user, require them to be able to `sudo tailscale` to use
`tailscale serve`. This is similar to the Windows elevated token check.

Updates tailscale/corp#15405

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Will Norris fc2d63bb8c go.mod: updates web-client-prebuilt
Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris 623f669239 client/web: pass URL prefix to frontend
This allows wouter to route URLs properly when running in CGI mode.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Sonia Appasamy 0753ad6cf8 client/web: move useNodeData out of App component
Only loading data once auth request has completed.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Will Norris d530153d2f go.mod: bump web-client-prebuilt
Updates #cleanup

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Sonia Appasamy 5e095ddc20 client/web: add initial framework for exit node selector
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy de2af54ffc client/web: pipe newSession through to readonly view
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy d73e923b73 client/web: add device details view
Initial addition of device details view on the frontend. A little
more backend piping work to come to fill all of the detail fields,
for now using placeholders.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Will Norris 3e9026efda client/web: show manage button in readonly view
We render the readonly view in two situations:
- the client is in login mode, and the device is connected
- the client is in manage mode, but the user does not yet have a session

If the user is not authenticated, and they are not currently on the
Tailscale IP address, render a "Manage" button that will take them to
the Tailcale IP of the device and immediately start check mode.

Still to do is detecting if they have connectivity to the Tailscale IP,
and disabling the button if not.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Thomas Kosiewski 96a80fcce3 Add support for custom DERP port in TLS prober
Updates #10146

Signed-off-by: Thomas Kosiewski <thoma471@googlemail.com>
7 months ago
Charlotte Brandhorst-Satzkorn 839fee9ef4 wgengine/magicsock: handle wireguard only clean up and log messages
This change updates log messaging when cleaning up wireguard only peers.
This change also stops us unnecessarily attempting to clean up disco
pings for wireguard only endpoints.

Updates #7826

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
7 months ago
Sonia Appasamy 3269b36bd0 client/web: fix hotreload proxy
Previously had HMR websocket set to run from a different port
than the http proxy server. This was an old setting carried over
from the corp repo admin panel config. It's messing with hot
reloads when run from the tailscaled web client, as it keeps
causing the full page to refresh each time a connection is made.
Switching back to the default config here fixes things.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy 942d720a16 cli/web: don't block startup on status req
If the status request to check for the preview node cap fails,
continue with starting up the legacy client.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy 7df2c5d6b1 client/web: add route management for ui pages
Using wouter, a lightweight React routing library.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
License Updater a97ead9ce4 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
7 months ago
License Updater aeb5a8b123 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
7 months ago
Sonia Appasamy f2a4c4fa55 client/web: build out client home page
Hooks up more of the home page UI.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Andrew Lytvynov aba4bd0c62
util/winutil: simplify dropping privileges after use (#10099)
To safely request and drop privileges, runtime.Lock/UnlockOSThread and
windows.Impersonate/RevertToSelf should be called. Add these calls to
winutil.EnableCurrentThreadPrivilege so that callers don't need to worry
about it.

Updates https://github.com/tailscale/corp/issues/15488

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Anton Tolchanov ef6a6e94f1 derp/derphttp: use a getter method to read server key
To hold the mutex while accessing it.

Fixes #10122

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
7 months ago
Brad Fitzpatrick 44c6909c92 control/controlclient: move watchdog out of mapSession
In prep for making mapSession's lifetime not be 1:1 with a single HTTP
response's lifetime, this moves the inactivity timer watchdog out of
mapSession and into the caller that owns the streaming HTTP response.

(This is admittedly closer to how it was prior to the mapSession type
existing, but that was before we connected some dots which were
impossible to even see before the mapSession type broke the code up.)

Updates #7175

Change-Id: Ia108dac84a4953db41cbd30e73b1de4a2a676c11
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Brad Fitzpatrick c87d58063a control/controlclient: move lastPrintMap field from Direct to mapSession
It was a really a mutable field owned by mapSession that we didn't move
in earlier commits.

Once moved, it's then possible to de-func-ify the code and turn it into
a regular method rather than an installed optional hook.

Noticed while working to move map session lifetimes out of
Direct.sendMapRequest's single-HTTP-connection scope.

Updates #7175
Updates #cleanup

Change-Id: I6446b15793953d88d1cabf94b5943bb3ccac3ad9
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Matt Layher 1a1e0f460a client/tailscale: remove redundant error check
Signed-off-by: Matt Layher <mdlayher@gmail.com>
7 months ago
Will Norris e537d304ef client/web: relax CSP restrictions for manage client
Don't return CSP headers in dev mode, since that includes a bunch of
extra things like the vite server.

Allow images from any source, which is needed to load user profile
images.

Allow 'unsafe-inline' for various inline scripts and style react uses.
We can eliminate this by using CSP nonce or hash values, but we'll need
to look into the best way to handle that. There appear to be several
react plugins for this, but I haven't evaluated any of them.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Claire Wang 5de8650466
syspolicy: add Allow LAN Access visibility key (#10113)
Fixes tailscale/corp#15594

Signed-off-by: Claire Wang <claire@tailscale.com>
7 months ago
Brad Fitzpatrick b2b836214c derp/derphttp: fix derptrack fix
3d7fb6c21d dropped the explicit called to (*Client).connect when
its (*Client).WatchConnectionChanges got removed+refactored.

This puts it back, but in RunWatchConnectionLoop, before the call
to the (*Client).ServerPublicKey accessor, which is documented to
return the zero value (which is what broke us) on an unconnected
connection.

Plus some tests.

Fixes tailscale/corp#15604

Change-Id: I0f242816f5ee4ad3bb0bf0400abc961dbe9f5fc8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Flakes Updater 8dc6de6f58 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
7 months ago
Will Norris 7e81c83e64 cmd/tailscale: respect existing web client pref
After running `tailscale web`, only disable the user pref if it was not
already previously set.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris cb07ed54c6 go.mod: update web-client-prebuilt
Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris a05ab9f3bc client/web: check r.Host rather than r.URL.Host
r.URL.Host is not typically populated on server requests.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris 6b956b49e0 client/web: add some security checks for full client
Require that requests to servers in manage mode are made to the
Tailscale IP (either ipv4 or ipv6) or quad-100. Also set various
security headers on those responses.  These might be too restrictive,
but we can relax them as needed.

Allow requests to /ok (even in manage mode) with no checks. This will be
used for the connectivity check from a login client to see if the
management client is reachable.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Aaron Klotz fbc18410ad ipn/ipnauth: improve the Windows token administrator check
(*Token).IsAdministrator is supposed to return true even when the user is
running with a UAC limited token. The idea is that, for the purposes of
this check, we don't care whether the user is *currently* running with
full Admin rights, we just want to know whether the user can
*potentially* do so.

We accomplish this by querying for the token's "linked token," which
should be the fully-elevated variant, and checking its group memberships.

We also switch ipn/ipnserver/(*Server).connIsLocalAdmin to use the elevation
check to preserve those semantics for tailscale serve; I want the
IsAdministrator check to be used for less sensitive things like toggling
auto-update on and off.

Fixes #10036

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
7 months ago
Sonia Appasamy e5dcf7bdde client/web: move auth session creation out of /api/auth
Splits auth session creation into two new endpoints:

/api/auth/session/new - to request a new auth session

/api/auth/session/wait - to block until user has completed auth url

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Will Norris 658971d7c0 ipn/ipnlocal: serve web client on quad100 if enabled
if the user pref and nodecap for the new web client are enabled, serve
the client over requests to 100.100.100.100.  Today, that is just a
static page that lists the local Tailcale IP addresses.

For now, this will render the readonly full management client, with an
"access" button that sends the user through check mode.  After
completing check mode, they will still be in the read-only view, since
they are not accessing the client over Tailscale.

Instead, quad100 should serve the lobby client that has a "manage"
button that will open the management client on the Tailscale IP (and
trigger check mode). That is something we'll fix in a subsequent PR in
the web client code itself.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
James Tucker 46fd488a6d types/dnstype: update the usage documentation on dnstype.Resolver
There was pre-existing additional usage for Exit Node DNS resolution via
PeerAPI, as well as new usage just introduced for App Connectors.

Fixes ENG-2324
Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Sonia Appasamy 0ecfc1d5c3 client/web: fill devMode from an env var
Avoids the need to pipe a web client dev flag through the tailscaled
command.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Andrew Lytvynov f0bc95a066
ipn/localapi: make serveTKASign require write permission (#10094)
The existing read permission check looks like an oversight. Write seems
more appropriate for sining new nodes.

Updates https://github.com/tailscale/corp/issues/15506

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Sonia Appasamy 191e2ce719 client/web: add ServerMode to web.Server
Adds a new Mode to the web server, indicating the specific
scenario the constructed server is intended to be run in. Also
starts filling this from the cli/web and ipn/ipnlocal callers.

From cli/web this gets filled conditionally based on whether the
preview web client node cap is set. If not set, the existing
"legacy" client is served. If set, both a login/lobby and full
management client are started (in "login" and "manage" modes
respectively).

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Andrew Lytvynov 7145016414
clientupdate: do not recursively delete dirs in cleanupOldDownloads (#10093)
In case there's a wild symlink in one of the target paths, we don't want
to accidentally delete too much. Limit `cleanupOldDownloads` to deleting
individual files only.

Updates https://github.com/tailscale/tailscale/issues/10082

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Will Norris 4ce4bb6271 client/web: limit authorization checks to API calls
This completes the migration to setting up authentication state in the
client first before fetching any node data or rendering the client view.

Notable changes:
 - `authorizeRequest` is now only enforced on `/api/*` calls (with the
   exception of /api/auth, which is handled early because it's needed to
   initially setup auth, particularly for synology)
 - re-separate the App and WebClient components to ensure that auth is
   completed before moving on
 - refactor platform auth (synology and QNAP) to fit into this new
   structure. Synology no longer returns redirect for auth, but returns
   authResponse instructing the client to fetch a SynoToken

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
James Tucker f27b2cf569 appc,cmd/sniproxy,ipn/ipnlocal: split sniproxy configuration code out of appc
The design changed during integration and testing, resulting in the
earlier implementation growing in the appc package to be intended now
only for the sniproxy implementation. That code is moved to it's final
location, and the current App Connector code is now renamed.

Updates tailscale/corp#15437

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Andrew Lytvynov 6c0ac8bef3
clientupdate: cleanup SPK and MSI downloads (#10085)
After we're done installing, clean up the temp files. This prevents temp
volumes from filling up on hosts that don't reboot often.

Fixes https://github.com/tailscale/tailscale/issues/10082

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Sonia Appasamy aa5af06165 ipn/ipnlocal: include web client port in setTCPPortsIntercepted
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy da31ce3a64 ipn/localapi: remove webclient endpoint
Managing starting/stopping tailscaled web client purely via setting
the RunWebClient pref.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy b370274b29 ipn/ipnlocal: pull CapabilityPreviewWebClient into webClientAtomicBool
Now uses webClientAtomicBool as the source of truth for whether the web
client should be running in tailscaled, with it updated when either the
RunWebClient pref or CapabilityPreviewWebClient node capability changes.

This avoids requiring holding the LocalBackend lock on each call to
ShouldRunWebClient to check for the CapabilityPreviewWebClient value.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Andrew Lytvynov c6a4612915
ipn/localapi: require Write access on /watch-ipn-bus with private keys (#10059)
Clients optionally request private key filtering. If they don't, we
should require Write access for the user.

Updates https://github.com/tailscale/corp/issues/15506

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Aaron Klotz 47019ce1f1 cmd/tailscaled: pre-load wintun.dll using a fully-qualified path
In corp PR #14970 I updated the installer to set a security mitigation that
always forces system32 to the front of the Windows dynamic linker's search
path.

Unfortunately there are other products out there that, partying like it's
1995, drop their own, older version of wintun.dll into system32. Since we
look there first, we end up loading that old version.

We can fix this by preloading wintun using a fully-qualified path. When
wintun-go then loads wintun, the dynamic linker will hand it the module
that was previously loaded by us.

Fixes #10023, #10025, #10052

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
7 months ago
Irbe Krumina af49bcaa52
cmd/k8s-operator: set different app type for operator with proxy (#10081)
Updates tailscale/tailscale#9222

plain k8s-operator should have hostinfo.App set to 'k8s-operator', operator with proxy should have it set to 'k8s-operator-proxy'. In proxy mode, we were setting the type after it had already been set to 'k8s-operator'

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
7 months ago
Brad Fitzpatrick 673ff2cb0b util/groupmember: fail earlier if group doesn't exist, use slices.Contains
Noticed both while re-reading this code.

Updates #cleanup

Change-Id: I3b70f1d5dc372853fa292ae1adbdee8cfc6a9a7b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
James Tucker 228a82f178 ipn/ipnlocal,tailcfg: add AppConnector service to HostInfo when configured
Updates tailscale/corp#15437

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
James Tucker 6ad54fed00 appc,ipn/ipnlocal: add App Connector domain configuration from mapcap
The AppConnector is now configured by the mapcap from the control plane.

Updates tailscale/corp#15437

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
James Tucker e9de59a315 tstest/deptest: fix minor escaping error in regex
Fixes https://github.com/tailscale/tailscale/security/code-scanning/112

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
James Tucker b48b7d82d0 appc,ipn/ipnlocal,net/dns/resolver: add App Connector wiring when enabled in prefs
An EmbeddedAppConnector is added that when configured observes DNS
responses from the PeerAPI. If a response is found matching a configured
domain, routes are advertised when necessary.

The wiring from a configuration in the netmap capmap is not yet done, so
while the connector can be enabled, no domains can yet be added.

Updates tailscale/corp#15437

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Will Norris e7482f0df0 ipn/ipnlocal: prevent deadlock on WebClientShutdown
WebClientShutdown tries to acquire the b.mu lock, so run it in a go
routine so that it can finish shutdown after setPrefsLockedOnEntry is
finished. This is the same reason b.sshServer.Shutdown is run in a go
routine.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Sonia Appasamy 7a725bb4f0 client/web: move more session logic to auth.go
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
dependabot[bot] 535cb6c3f5 build(deps): bump github.com/docker/docker
Bumps [github.com/docker/docker](https://github.com/docker/docker) from 24.0.6+incompatible to 24.0.7+incompatible.
- [Release notes](https://github.com/docker/docker/releases)
- [Commits](https://github.com/docker/docker/compare/v24.0.6...v24.0.7)

---
updated-dependencies:
- dependency-name: github.com/docker/docker
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
7 months ago
dependabot[bot] f2bc54ba15 build(deps-dev): bump postcss from 8.4.27 to 8.4.31 in /client/web
Bumps [postcss](https://github.com/postcss/postcss) from 8.4.27 to 8.4.31.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.4.27...8.4.31)

---
updated-dependencies:
- dependency-name: postcss
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
7 months ago
dependabot[bot] 6cc81a6d3e build(deps): bump get-func-name from 2.0.0 to 2.0.2 in /client/web
Bumps [get-func-name](https://github.com/chaijs/get-func-name) from 2.0.0 to 2.0.2.
- [Release notes](https://github.com/chaijs/get-func-name/releases)
- [Commits](https://github.com/chaijs/get-func-name/commits/v2.0.2)

---
updated-dependencies:
- dependency-name: get-func-name
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
7 months ago
dependabot[bot] 80fc32588c build(deps): bump @babel/traverse from 7.22.10 to 7.23.2 in /client/web
Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.22.10 to 7.23.2.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse)

---
updated-dependencies:
- dependency-name: "@babel/traverse"
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
7 months ago
Will Norris e5fbe57908 web/client: update synology token from /api/auth call
When the /api/auth response indicates that synology auth is needed,
fetch the SynoToken and store it for future API calls.  This doesn't yet
update the server-side code to set the new SynoAuth field.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
dependabot[bot] b1a0caf056 .github: Bump actions/checkout from 3 to 4
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
7 months ago
Andrew Lytvynov 7f16e000c9
clientupdate: clarify how to run update as Administrator on Windows (#10043)
Make the error message a bit more helpful for users.

Updates #9456

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
James Tucker 01604c06d2 hostinfo: fix a couple of logic simplification lints
Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
David Anderson 37863205ec cmd/k8s-operator: strip credentials from client config in noauth mode
Updates tailscale/corp#15526

Signed-off-by: David Anderson <danderson@tailscale.com>
7 months ago
James Tucker 0ee4573a41 ipn/ipnlocal: fix small typo
Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Will Norris 237c6c44cd client/web: call /api/auth before rendering any client views
For now this is effectively a noop, since only the ManagementClientView
uses the auth data. That will change soon.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Rhea Ghosh 970eb5e784
cmd/k8s-operator: sanitize connection headers (#10063)
Fixes tailscale/corp#15526

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
7 months ago
James Tucker ca4c940a4d ipn: introduce app connector advertisement preference and flags
Introduce a preference structure to store the setting for app connector
advertisement.

Introduce the associated flags:

  tailscale up --advertise-connector{=true,=false}
  tailscale set --advertise-connector{=true,=false}

```
% tailscale set --advertise-connector=false
% tailscale debug prefs | jq .AppConnector.Advertise
false
% tailscale set --advertise-connector=true
% tailscale debug prefs | jq .AppConnector.Advertise
true
% tailscale up --advertise-connector=false
% tailscale debug prefs | jq .AppConnector.Advertise
false
% tailscale up --advertise-connector=true
% tailscale debug prefs | jq .AppConnector.Advertise
true
```

Updates tailscale/corp#15437

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
James Tucker 09fcbae900 net/dnscache: remove completed TODO
The other IP types don't appear to be imported anymore, and after a scan
through I couldn't see any substantial usage of other representations,
so I think this TODO is complete.

Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Sonia Appasamy 32ebc03591 client/web: move session logic to auth.go
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Chris Palmer 3a9f5c02bf
util/set: make Clone a method (#10044)
Updates #cleanup

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
7 months ago
Derek Kaser 5289cfce33
clientupdate: disable on Unraid (#10048)
* clientupdate: disable on Unraid

Updates dkaser/unraid-tailscale#94

Signed-off-by: Derek Kaser <derek.kaser@gmail.com>

* Update clientupdate/clientupdate.go

Signed-off-by: Andrew Lytvynov <andrew@awly.dev>

---------

Signed-off-by: Derek Kaser <derek.kaser@gmail.com>
Signed-off-by: Andrew Lytvynov <andrew@awly.dev>
Co-authored-by: Andrew Lytvynov <andrew@awly.dev>
7 months ago
Irbe Krumina c2b87fcb46
cmd/k8s-operator/deploy/chart,.github/workflows: use helm chart API v2 (#10055)
API v1 is compatible with helm v2 and v2 is not.
However, helm v2 (the Tiller deployment mechanism) was deprecated in 2020
and no-one should be using it anymore.
This PR also adds a CI lint test for helm chart

Updates tailscale/tailscale#9222

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
7 months ago
Maisem Ali d0f2c0664b wgengine/netstack: standardize var names in UpdateNetstackIPs
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Maisem Ali eaf8aa63fc wgengine/netstack: remove unnecessary map in UpdateNetstackIPs
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Maisem Ali d601c81c51 wgengine/netstack: use netip.Prefix as map keys
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Anton Tolchanov c3313133b9 derp/derphttp: close DERP client to avoid data race in test
Fixes #10041

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
7 months ago
Will Norris 66c7af3dd3 ipn: replace web client debug flag with node capability
Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Jordan Whited bd488e4ff8
go.mod: update wireguard-go (#10046)
Updates tailscale/corp#9990

Signed-off-by: Jordan Whited <jordan@tailscale.com>
7 months ago
Chris Palmer 00375f56ea
util/set: add some more Set operations (#10022)
Updates #cleanup

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
7 months ago
Andrew Lytvynov 7f3208592f
clientupdate: mention release track when running latest (#10039)
Not all users know about our tracks and versioning scheme. They can be
confused when e.g. 1.52.0 is out but 1.53.0 is available. Or when 1.52.0
is our but 1.53 has not been built yet and user is on 1.51.x.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Sonia Appasamy 44175653dc ipn/ipnlocal: rename web fields/structs to webClient
For consistency and clarity around what the LocalBackend.web field
is used for.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Anton Tolchanov 3114a1c88d derp/derphttp: add watch reconnection tests from #9719
Co-authored-by: Val <valerie@tailscale.com>
Signed-off-by: Anton Tolchanov <anton@tailscale.com>
7 months ago
Brad Fitzpatrick 3d7fb6c21d derp/derphttp: fix race in mesh watcher
The derphttp client automatically reconnects upon failure.

RunWatchConnectionLoop called derphttp.Client.WatchConnectionChanges
once, but that wrapper method called the underlying
derp.Client.WatchConnectionChanges exactly once on derphttp.Client's
currently active connection. If there's a failure, we need to re-subscribe
upon all reconnections.

This removes the derphttp.Client.WatchConnectionChanges method, which
was basically impossible to use correctly, and changes it to be a
boolean field on derphttp.Client alongside MeshKey and IsProber. Then
it moves the call to the underlying derp.Client.WatchConnectionChanges
to derphttp's client connection code, so it's resubscribed on any
reconnect.

Some paranoia is then added to make sure people hold the API right,
not calling derphttp.Client.RunWatchConnectionLoop on an
already-started Client without having set the bool to true. (But still
auto-setting it to true if that's the first method that's been called
on that derphttp.Client, as is commonly the case, and prevents
existing code from breaking)

Fixes tailscale/corp#9916
Supercedes tailscale/tailscale#9719

Co-authored-by: Val <valerie@tailscale.com>
Co-authored-by: Irbe Krumina <irbe@tailscale.com>
Co-authored-by: Anton Tolchanov <anton@tailscale.com>
Signed-off-by: Brad Fitzpatrick <brad@danga.com>
7 months ago
Tom DNetto df4b730438 types/appctype: define the nodeAttrs type for dns-driven app connectors
Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: https://github.com/tailscale/corp/issues/15440
Code-authored-by: Podtato <podtato@tailscale.com>
7 months ago
Tom DNetto a7c80c332a cmd/sniproxy: implement support for control configuration, multiple addresses
* Implement missing tests for sniproxy
 * Wire sniproxy to new appc package
 * Add support to tsnet for routing subnet router traffic into netstack, so it can be handled

Updates: https://github.com/tailscale/corp/issues/15038
Signed-off-by: Tom DNetto <tom@tailscale.com>
7 months ago
Flakes Updater 0d86eb9da5 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
7 months ago
Will Norris ea599b018c ipn: serve web client requests from LocalBackend
instead of starting a separate server listening on a particular port,
use the TCPHandlerForDst method to intercept requests for the special
web client port (currently 5252, probably configurable later).

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Will Norris 28ad910840 ipn: add user pref for running web client
This is not currently exposed as a user-settable preference through
`tailscale up` or `tailscale set`.  Instead, the preference is set when
turning the web client on and off via localapi. In a subsequent commit,
the pref will be used to automatically start the web client on startup
when appropriate.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Jordan Whited dd842d4d37
go.mod: update wireguard-go to enable TUN UDP GSO/GRO (#10029)
Updates tailscale/corp#9990

Signed-off-by: Jordan Whited <jordan@tailscale.com>
7 months ago
Sonia Appasamy 6f214dec48 client/web: split out UI components
This commit makes the following structural changes to the web
client interface. No user-visible changes.

1. Splits login, legacy, readonly, and full management clients into
   their own components, and pulls them out into their own view files.
2. Renders the same Login component for all scenarios when the client
   is not logged in, regardless of legacy or debug mode. Styling comes
   from the existing legacy login, which is removed from legacy.tsx
   now that it is shared.
3. Adds a ui folder to hold non-Tailscale-specific components,
   starting with ProfilePic, previously housed in app.tsx.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy 89953b015b ipn/ipnlocal,client/web: add web client to tailscaled
Allows for serving the web interface from tailscaled, with the
ability to start and stop the server via localapi endpoints
(/web/start and /web/stop).

This will be used to run the new full management web client,
which will only be accessible over Tailscale (with an extra auth
check step over noise) from the daemon. This switch also allows
us to run the web interface as a long-lived service in environments
where the CLI version is restricted to CGI, allowing us to manage
certain auth state in memory.

ipn/ipnlocal/web is stubbed out in ipn/ipnlocal/web_stub for
ios builds to satisfy ios restriction from adding "text/template"
and "html/template" dependencies.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy 93aa8a8cff client/web: allow providing logger implementation
Also report metrics in separate go routine with a 5 second timeout.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Andrea Gottardo 95715c4a12
ipn/localapi: add endpoint to handle APNS payloads (#9972)
* ipn/localapi: add endpoint to handle APNS payloads

Fixes #9971. This adds a new `handle-push-message` local API endpoint. When an APNS payload is delivered to the main app, this endpoint can be used to forward the JSON body of the message to the backend, making a POST request.

cc @bradfitz

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>

* Address comments from code review

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>

---------

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
7 months ago
Andrew Dunham 57c5b5a77e net/dns/recursive: update IP for b.root-servers.net
As of 2023-11-27, the official IP addresses for b.root-servers.net will
change to a new set, with the older IP addresses supported for at least
a year after that date. These IPs are already active and returning
results, so update these in our recursive DNS resolver package so as to
be ready for the switchover.

See: https://b.root-servers.org/news/2023/05/16/new-addresses.html

Fixes #9994

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I29e2fe9f019163c9ec0e62bdb286e124aa90a487
7 months ago
Tom DNetto 3df305b764 tsnet: enable use-cases with non-native IPs by setting ns.ProcessSubnets
Terminating traffic to IPs which are not the native IPs of the node requires
the netstack subsystem to intercept trafic to an IP it does not consider local.
This PR switches on such interception. In addition to supporting such termination,
this change will also enable exit nodes and subnet routers when running in
userspace mode.

DO NOT MERGE until 1.52 is cut.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: https://github.com/tailscale/corp/issues/15038
7 months ago
Irbe Krumina 452f900589
tool: download helm CLI (#9981)
Updates tailscale/tailscale#9222

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
7 months ago
Irbe Krumina ed1b935238
cmd/k8s-operator: allow to install operator via helm (#9920)
Initial helm manifests.

Updates tailscale/tailscale#9222

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
Co-authored-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Tyler Smalley fde2ba5bb3
VERSION.txt: this is v1.53.0 (#10018)
Signed-off-by: Tyler Smalley <tyler@tailscale.com>
7 months ago
Maisem Ali 62d580f0e8 util/linuxfw: add missing error checks in tests
This would surface as panics when run on Fly. Still fail, but at least don't panic.

Updates #10003

Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Rhea Ghosh 387a98fe28
ipn/ipnlocal: exclude tvOS devices from taildrop file targets (#10002) 7 months ago
Chris Palmer f66dc8dc0a
clientupdate: check for privileges earlier (#9964)
Fixes #9963

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
7 months ago
Flakes Updater f9fafe269a go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
7 months ago
Cole Helbling 087260734b flake: drop unnecessary git input
Signed-off-by: Cole Helbling <cole.helbling@determinate.systems>
7 months ago
Cole Helbling 561e7b61c3 flake: fix systemd service by hardcoding $PORT
Another solution would be to copy the `.defaults` file alongside the
service file, and set the `EnvironmentFile` to point to that, but it
would still be hardcoded (as the `.defaults` file would be stored in the
Nix store), so I figured that this is a good solution until there is a
proper NixOS module.

Fixes #9995.

Signed-off-by: Cole Helbling <cole.helbling@determinate.systems>
7 months ago
Cole Helbling 9e71851a36 go.mod.sri: update
Signed-off-by: Cole Helbling <cole.helbling@determinate.systems>
7 months ago
Cole Helbling 4f62a2ed99 flake: set a default package
This allows `nix build` to run, without needing to use `nix build
.#tailscale`.

Signed-off-by: Cole Helbling <cole.helbling@determinate.systems>
7 months ago
Cole Helbling f737496d7c flake: drop unnecessary fileContents binding
Since the tailscale derivation already has a `pkgs` binding, we can
use `pkgs.lib`. Alternatively, we could have used `nixpkgs.lib`, as
`fileContents` doesn't need a system to use (anymore?).

Signed-off-by: Cole Helbling <cole.helbling@determinate.systems>
7 months ago
Maisem Ali 9107b5eadf cmd/tailscale/cli: use status before doing interactive feature query
We were inconsistent whether we checked if the feature was already
enabled which we could do cheaply using the locally available status.
We would do the checks fine if we were turning on funnel, but not serve.

This moves the cap checks down into enableFeatureInteractive so that
are always run.

Updates #9984

Co-authored-by: Tyler Smalley <tyler@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
License Updater e94d345e26 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
7 months ago
License Updater 7c7f60be22 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
7 months ago
Tyler Smalley baa1fd976e
ipn/localapi: require local Windows admin to set serve path (#9969)
For a serve config with a path handler, ensure the caller is a local administrator on Windows.

updates #8489

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
7 months ago
Will Norris 42abf13843 .github: run tests on all PRs, regardless of branch name
The branch name selector "*" doesn't match branches with a "/" in their
name. The vast majority of our PRs are against the main (or previously,
master) branch anyway, so this will have minimal impact. But in the rare
cases that we want to open a PR against a branch with a "/" in the name,
tests should still run.

```
gh pr list --limit 9999 --state all --json baseRefName | \
  jq -cs '.[] | group_by(.baseRefName) |
    map({ base: .[0].baseRefName, count: map(.baseRefName) | length}) |
    sort_by(-.count) | .[]'

{"base":"main","count":4593}
{"base":"master","count":226}
{"base":"release-branch/1.48","count":4}
{"base":"josh-and-adrian-io_uring","count":3}
{"base":"release-branch/1.30","count":3}
{"base":"release-branch/1.32","count":3}
{"base":"release-branch/1.20","count":2}
{"base":"release-branch/1.26","count":2}
{"base":"release-branch/1.34","count":2}
{"base":"release-branch/1.38","count":2}
{"base":"Aadi/speedtest-tailscaled","count":1}
{"base":"josh/io_uring","count":1}
{"base":"maisem/hi","count":1}
{"base":"rel-144","count":1}
{"base":"release-branch/1.18","count":1}
{"base":"release-branch/1.2","count":1}
{"base":"release-branch/1.22","count":1}
{"base":"release-branch/1.24","count":1}
{"base":"release-branch/1.4","count":1}
{"base":"release-branch/1.46","count":1}
{"base":"release-branch/1.8","count":1}
{"base":"web-client-main","count":1}
```

Updates #cleanup

Signed-off-by: Will Norris <will@tailscale.com>
7 months ago
Brad Fitzpatrick b4be4f089f safesocket: make clear which net.Conns are winio types
Follow-up to earlier #9049.

Updates #9049

Change-Id: I121fbd2468770233a23ab5ee3df42698ca1dabc2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Aaron Klotz 95671b71a6 ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.

The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.

This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).

Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.

I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.

Updates https://github.com/tailscale/tailscale/issues/755

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
7 months ago
Andrew Dunham ef596aed9b net/portmapper: avoid alloc in getUPnPErrorsMetric
Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Iea558024c038face24cc46584421998d10f13a66
7 months ago
James Tucker 237b4b5a2a .github/workflows: add checklocks
Currently the checklocks step is not configured to fail, as we do not
yet have the appropriate annotations.

Updates tailscale/corp#14381

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Tyler Smalley 131518eed1
cmd/tailscale/cli: improve error when bg serve config is present (#9961)
We prevent shodow configs when starting a foreground when a background serve config already exists for the serve type and port. This PR improves the messaging to let the user know how to remove the previous config.

Updates #8489
ENG-2314

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
7 months ago
Tyler Smalley 1873bc471b
cmd/tailscale/cli: remove http flag for funnel command (#9955)
The `--http` flag can not be used with Funnel, so we should remove it to remove confusion.

Updates #8489
ENG-2316

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
7 months ago
Val 19e5f242e0 net/portmapper: convert UPnP metrics to new syncs.Map.LoadOrInit method
Simplify UPnP error metrics by using the new syncs.Map.LoadOrInit method.

Updates #cleanup

Signed-off-by: Val <valerie@tailscale.com>
7 months ago
Andrew Lytvynov 8326fdd60f
clientupdate: disable auto-updates on Synology for now (#9965)
Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Flakes Updater 143bda87a3 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
7 months ago
Marwan Sulaiman 5f3cdaf283 cmd/tailscale/cli: chage port flags to uint for serve and funnel
This PR changes the -https, -http, -tcp, and -tls-terminated-tcp
flags from string to int and also updates the validation to ensure
they fit the uint16 size as the flag library does not have a Uint16Var
method.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
7 months ago
Andrea Gottardo 741d7bcefe
Revert "ipn/ipnlocal: add new DNS and subnet router policies" (#9962)
This reverts commit 32194cdc70.

Signed-off-by: Nick O'Neill <nick@tailscale.com>
7 months ago
Marwan Sulaiman a7e4cebb90 cmd/tailscale/cli: refactor TestServeDevConfigMutations
The TestServeDevConfigMutations test has 63 steps that all run
under the same scope. This tests breaks them out into isolated
subtests that can be run independently.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
7 months ago
Sonia Appasamy d79e0fde9c client/web: split errTaggedSelf resp from getTailscaleBrowserSession
Previously returned errTaggedSource in the case that of any tagged
source. Now distinguishing whether the source was local or remote.
We'll be presenting the two cases with varying copy on the frontend.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Sonia Appasamy e0a4a02b35 client/web: pipe Server.timeNow() through session funcs
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Andrew Lytvynov 21b6d373b0
cmd/tailscale/cli: unhide auto-update flags and mark update as Beta (#9954)
Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Adrian Dewhurst 32194cdc70 ipn/ipnlocal: add new DNS and subnet router policies
In addition to the new policy keys for the new options, some
already-in-use but missing policy keys are also being added to
util/syspolicy.

Updates ENG-2133

Change-Id: Iad08ca47f839ea6a65f81b76b4f9ef21183ebdc6
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
7 months ago
Marwan Sulaiman f5a7551382 cmd/tailscale: fix help message for serve funnel
We currently print out "run tailscale serve --help" when the subcmd
might be funnel. This PR ensures the right subcmd is passed.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
7 months ago
Andrew Lytvynov d3bc575f35
cmd/tailscale/cli: set Sparkle auto-update on macsys (#9952)
On `tailscale set --auto-update`, set the Sparkle plist option for it.
Also make macsys report not supporting auto-updates over c2n, since they
will be triggered by Sparkle locally.

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
James Tucker 6f69fe8ad7 wgnengine: remove unused field in userspaceEngine
Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Tyler Smalley 269a498c1e
cmd/tailscale/cli: serve --set-path should not force background mode (#9905)
A few people have run into issues with understanding why `--set-path` started in background mode, and/or why they couldn't use a path in foreground mode. This change allows `--set-path` to be used in either case (foreground or background).

updates #8489

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
7 months ago
Thomas Kosiewski b2ae8fdf80
derp/derphttp: strip port numbers from URL hostname
When trying to set up multiple derper instances meshing with each
other, it turned out that while one can specify an alternative
listening port using the -a flag, the TLS hostname gets incorrectly
determined and includes the set alternative listening port as part of
the hostname. Thus, the TLS hostname validation always fails when the
-mesh-with values have ports.

Updates #9949

Signed-off-by: Thomas Kosiewski <thomas.kosiewski@loft.sh>
7 months ago
Brad Fitzpatrick 514539b611 wgengine/magicsock: close disco listeners on Conn.Close, fix Linux root TestNewConn
TestNewConn now passes as root on Linux. It wasn't closing the BPF
listeners and their goroutines.

The code is still a mess of two Close overlapping code paths, but that
can be refactored later. For now, make the two close paths more similar.

Updates #9945

Change-Id: I8a3cf5fb04d22ba29094243b8e645de293d9ed85
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Andrew Lytvynov 593c086866
clientupdate: distinguish when auto-updates are possible (#9896)
clientupdate.Updater will have a non-nil Update func in a few cases
where it doesn't actually perform an update:
* on Arch-like distros, where it prints instructions on how to update
* on macOS app store version, where it opens the app store page

Add a new clientupdate.Arguments field to cause NewUpdater to fail when
we hit one of these cases. This results in c2n updates being "not
supported" and `tailscale set --auto-update` returning an error.

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
James Tucker 7df6f8736a wgengine/netstack: only add addresses to correct protocols
Prior to an earlier netstack bump this code used a string conversion
path to cover multiple cases of behavior seemingly checking for
unspecified addresses, adding unspecified addresses to v6. The behavior
is now crashy in netstack, as it is enforcing address length in various
areas of the API, one in particular being address removal.

As netstack is now protocol specific, we must not create invalid
protocol addresses - an address is v4 or v6, and the address value
contained inside must match. If a control path attempts to do something
otherwise it is now logged and skipped rather than incorrect addressing
being added.

Fixes tailscale/corp#15377

Signed-off-by: James Tucker <james@tailscale.com>
7 months ago
Tyler Smalley 35d7b3aa27
cmd/tailscale/cli: updates help and background messaging (#9929)
* Fixes issue with template string not being provided in help text
* Updates background information to provide full URL, including path, to make it clear the source and destination
* Restores some tests
* Removes AllowFunnel in ServeConfig if no proxy exists for that port.

updates #8489

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
7 months ago
Marwan Sulaiman c53ee37912 cmd/tailscale: add set-raw to the new serve funnel commands
This PR adds the same set-raw from the old flow into the new one
so that users can continue to use it when transitioning into the new
flow.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
7 months ago
Marwan Sulaiman f232d4554a cmd/tailscale: translate old serve commands to new ones
This PR fixes the isLegacyInvocation to better catch serve and
funnel legacy commands. In addition, it now also returns a string
that translates the old command into the new one so that users
can have an easier transition story.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
7 months ago
Sonia Appasamy 62d08d26b6 client/web: set Server.cgiMode field
Updates tailscale/corp#15373

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
Co-authored-by: Will Norris <will@tailscale.com>
7 months ago
Maisem Ali 17b2072b72 ipn/ipnlocal: set the push device token correctly
It would end up resetting whatever hostinfo we had constructed
and leave the backend statemachine in a broken state.
This fixes that by storing the PushDeviceToken on the LocalBackend
and populating it on Hostinfo before passing it to controlclient.

Updates tailscale/corp#8940
Updates tailscale/corp#15367

Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Maisem Ali 0e89245c0f ipn/ipnlocal: drop hostinfo param from doSetHostinfoFilterServices
The value being passed was the same as whats on b.hostinfo, so just
use that directly.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Joe Tsai 152390e80a
ipn/localapi: avoid unkeyed literal (#9933)
Go has no way to explicitly identify Go struct as effectively a tuple,
so staticcheck assumes any external use of unkeyed literals is wrong.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
7 months ago
Marwan Sulaiman 60e768fd14 cmd/tailscale: allow serve|funnel off to delete an entire port
This PR allows you to do "tailscale serve -bg -https:4545 off" and it
will delete all handlers under it. It will also prompt you for a y/n in case
you wanted to delete a single port.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
7 months ago
Andrew Lytvynov e561f1ce61
clientupdate: manually restart Windows GUI after update (#9906)
When updating via c2n, `tailscale.exe update` runs from `tailscaled.exe`
which runs as SYSTEM. The MSI installer does not start the GUI when
running as SYSTEM. This results in Tailscale just existing on
auto-update, which is ungood.

Instead, always ask the MSI installer to not launch the GUI (via
`TS_NOLAUNCH` argument) and launch it manually with a token from the
current logged in user. The token code was borrowed from
d9081d6ba2/net/dns/wsl_windows.go (L207-L232)

Also, make some logging changes so that these issues are easier to debug
in the future.

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Irbe Krumina e9956419f6
cmd/k8s-operator: allow cleanup of cluster resources for deleted devices (#9917)
Users should delete proxies by deleting or modifying the k8s cluster resources
that they used to tell the operator to create they proxy. With this flow,
the tailscale operator will delete the associated device from the control.
However, in some cases users might have already deleted the device from the control manually.

Updates tailscale/tailscale#9773

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
7 months ago
Brad Fitzpatrick e87862bce3 go.toolchain.rev: bump Tailscale Go toolchain
Updates tailscale/go#77

Change-Id: I367465fb90cd4369cfbafd913c3964bfe5553dd0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
7 months ago
Maisem Ali f398712c00 ipn/ipnlocal: prevent changing serve config if conf.Locked
This adds a check to prevent changes to ServeConfig if tailscaled
is run with a Locked config.

Missed in 1fc3573446.

Updates #1412

Signed-off-by: Maisem Ali <maisem@tailscale.com>
7 months ago
Tyler Smalley d9081d6ba2
cmd/tailscale/cli: update serve/funnel CLI help text (#9895)
updates #8489
ENG-2308

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
7 months ago
Adrian Dewhurst 5347e6a292 control/controlclient: support certstore without cgo
We no longer build Windows releases with cgo enabled, which
automatically turned off certstore support. Rather than re-enabling cgo,
we updated our fork of the certstore package to no longer require cgo.
This updates the package, cleans up how the feature is configured, and
removes the cgo build tag requirement.

Fixes tailscale/corp#14797
Fixes tailscale/coral#118

Change-Id: Iaea34340761c0431d759370532c16a48c0913374
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
7 months ago
Sonia Appasamy 68da15516f ipn/localapi,client/web: clean up auth error handling
This commit makes two changes to the web client auth flow error
handling:

1. Properly passes back the error code from the noise request from
   the localapi. Previously we were using io.Copy, which was always
   setting a 200 response status code.
2. Clean up web client browser sessions on any /wait endpoint error.
   This avoids the user getting in a stuck state if something goes
   wrong with their auth path.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
7 months ago
Andrew Lytvynov 70f9c8a6ed
clientupdate: change Mac App Store support (#9891)
In the sandboxed app from the app store, we cannot check
`/Library/Preferences/com.apple.commerce.plist` or run `softwareupdate`.
We can at most print a helpful message and open the app store page.

Also, reenable macsys update function to mark it as supporting c2n
updates. macsys support in `tailscale update` was fixed.

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
7 months ago
Irbe Krumina eced054796
ipn/ipnlocal: close connections for removed proxy transports (#9884)
Ensure that when a userspace proxy config is reloaded,
connections for any removed proxies are safely closed

Updates tailscale/tailscale#9725

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
7 months ago
Sonia Appasamy 1df2d14c8f client/web: use auth ID in browser sessions
Stores ID from tailcfg.WebClientAuthResponse in browser session
data, and uses ID to hit control server /wait endpoint.

No longer need the control url cached, so removed that from Server.
Also added optional timeNow field, initially to manage time from
tests.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Joe Tsai 6ada33db77
taildrop: fix theoretical race condition in fileDeleter.Init (#9876)
It is possible that upon a cold-start, we enqueue a partial file
for deletion that is resumed shortly after startup.

If the file transfer happens to last longer than deleteDelay,
we will delete the partial file, which is unfortunate.
The client spent a long time uploading a file,
only for it to be accidentally deleted.
It's a very rare race, but also a frustrating one
if it happens to manifest.

Fix the code to only delete partial files that
do not have an active puts against it.

We also fix a minor bug in ResumeReader
where we read b[:blockSize] instead of b[:cs.Size].
The former is the fixed size of 64KiB,
while the latter is usually 64KiB,
but may be less for the last block.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Andrew Lytvynov 25b6974219
ipn/ipnlocal: send ClientVersion to Apple frontends (#9887)
Apple frontends will now understand this Notify field and handle it.

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Sonia Appasamy b4247fabec tailcfg: add ID field to WebClientAuthResponse
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Tom DNetto 7e933a8816 appctype: move to types/appctype
Having a types package at the top level was almost certainly unintentional.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: https://github.com/tailscale/corp/issues/15038
8 months ago
Tom DNetto 02908a2d8d appc: implement app connector Server type
This change refactors & moves the bulk of the app connector logic from
./cmd/sniproxy.

A future change will delete the delta in sniproxy and wire it to this type.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: https://github.com/tailscale/corp/issues/15038
8 months ago
Joe Tsai 469b7cabad
cmd/tailscale: improve taildrop progress printer on Linux (#9878)
The progress printer was buggy where it would not print correctly
and some of the truncation logic was faulty.

The progress printer now prints something like:

	go1.21.3.linux-amd64.tar.gz               21.53MiB      13.83MiB/s     33.88%    ETA 00:00:03

where it shows
* the number of bytes transferred so far
* the rate of bytes transferred
  (using a 1-second half-life for an exponentially weighted average)
* the progress made as a percentage
* the estimated time
  (as calculated from the rate of bytes transferred)

Other changes:
* It now correctly prints the progress for very small files
* It prints at a faster rate (4Hz instead of 1Hz)
* It uses IEC units for byte quantities
  (to avoid ambiguities of "kb" being kilobits or kilobytes)

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Tyler Smalley 7a3ae39025
cmd/tailscale/cli: [serve/funnel] support omitting scheme for TCP (#9856)
The `serve` command for TCP  has always required the scheme of the target to be specified. However, when it's omitted the error message reported is misleading

```
error: failed to apply TCP serve: invalid TCP target "localhost:5900": missing port in address
```

Since we know the target is TCP, we shouldn't require it to be specified. This aligns with the changes for HTTP proxies in https://github.com/tailscale/tailscale/issues/8489

closes #9855

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
8 months ago
Tyler Smalley 35376d52d4
cmd/tailscale/cli: [serve/funnel] provide correct command for disabling (#9859)
The `off` subcommand removes a serve/funnel for the corresponding type and port. Previously, we were not providing this which would result in an error if someone was using something than the default https=443.

closes #9858

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
8 months ago
Irbe Krumina f09cb45f9d
ipn/ipnlocal: initiate proxy transport once (#9883)
Initiates http/h2c transport for userspace proxy
backend lazily and at most once.

Updates tailscale/tailscale#9725

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
8 months ago
Sonia Appasamy 73bbf941f8 client/web: hook up auth flow
Connects serveTailscaleAuth to the localapi webclient endpoint
and pipes auth URLs and session cookies back to the browser to
redirect users from the frontend.

All behind debug flags for now.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Irbe Krumina 09b5bb3e55
ipn/ipnlocal: proxy gRPC requests over h2c if needed. (#9847)
Updates userspace proxy to detect plaintext grpc requests
using the preconfigured host prefix and request's content
type header and ensure that these will be proxied over h2c.

Updates tailscale/tailscale#9725

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
8 months ago
Jordan Whited 891d964bd4
wgengine/magicsock: simplify tryEnableUDPOffload() (#9872)
Don't assume Linux lacks UDP_GRO support if it lacks UDP_SEGMENT
support. This mirrors a similar change in wireguard/wireguard-go@177caa7
for consistency sake. We haven't found any issues here, just being
overly paranoid.

Updates #cleanup

Signed-off-by: Jordan Whited <jordan@tailscale.com>
8 months ago
Joe Tsai d603d18956
taildrop: fix TestResume (#9874)
Previously, the test simply relied on:
	defer close()
to cleanup file handles.

This works fine on Unix-based systems,
but not on Windows, which dislikes deleting files
where an open file handle continues to exist.

Fix the test by explicitly closing the file handle
after we are done with the resource.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Brad Fitzpatrick cf27761265 cmd/tsconnect/wasm: add missing tstun.Wrapper.Start call
It's required as of the recent 5297bd2cff.

Updates #7894
Updates #9394 (sure would be nice)

Change-Id: Id6672408dd8a6c82dba71022c8763e589d789fcd
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Joe Tsai cb00eac850
taildrop: disable TestResume (#9873)
This test is currently failing on Windows.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Joe Tsai 674beabc73
syncs: add Map.LoadFunc (#9869)
The LoadFunc loads a value and calls a user-provided function.
The utility of this method is to ensure that the map lock is held
while executing user-provided logic.
This allows us to solve TOCTOU bugs that would be nearly imposible
to the solve without this API.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
James Tucker afb72ecd73 .github/workflows: update golangci-lint
Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Sonia Appasamy 851536044a client/web: add tests for authorizeRequest
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Maisem Ali c3a8e63100 util/linuxfw: add additional nftable detection logic
We were previously using the netlink API to see if there are chains/rules that
already exist. This works fine in environments where there is either full
nftable support or no support at all. However, we have identified certain
environments which have partial nftable support and the only feasible way of
detecting such an environment is to try to create some of the chains that we
need.

This adds a check to create a dummy postrouting chain which is immediately
deleted. The goal of the check is to ensure we are able to use nftables and
that it won't error out later. This check is only done in the path where we
detected that the system has no preexisting nftable rules.

Updates #5621
Updates #8555
Updates #8762

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Maisem Ali b47cf04624 util/linuxfw: fix broken tests
These tests were broken at HEAD. CI currently does not run these
as root, will figure out how to do that in a followup.

Updates #5621
Updates #8555
Updates #8762

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Joe Tsai a8fbe284b2
taildrop: fix theoretical race condition (#9866)
WaitGroup.Wait should not be concurrently called WaitGroup.Add.
In other words, we should not start new goroutines after shutodwn is called.
Thus, add a conditional to check that shutdown has not been called
before starting off a new waitAndDelete goroutine.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
License Updater 756a4c43b6 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
8 months ago
Joe Tsai 3f27087e9d
taildrop: switch hashing to be streaming based (#9861)
While the previous logic was correct, it did not perform well.
Resuming is a dance between the client and server, where
1. the client requests hashes for a partial file,
2. the server then computes those hashes,
3. the client computes hashes locally and compares them.
4. goto 1 while the partial file still has data

While step 2 is running, the client is sitting idle.
While step 3 is running, the server is sitting idle.

By streaming over the block hash immediately after the server
computes it, the client can start checking the hash,
while the server works on the next hash (in a pipelined manner).
This performs dramatically better and also uses less memory
as we don't need to hold a list of hashes, but only need to
handle one hash at a time.

There are two detriments to this approach:
* The HTTP API relies on a JSON stream,
  which is not a standard REST-like pattern.
  However, since we implement both client and server,
  this is fine.
* While the stream is on-going, we hold an open file handle
  on the server side while the file is being hashed.
  On really slow streams, this could hold a file open forever.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Joe Tsai 7971333603
ipn: fix localapi and peerapi protocol for taildrop resume (#9860)
Minor fixes:
* The branch for listing or hashing partial files was inverted.
* The host for peerapi call needs to be real (rather than bogus).
* Handle remote peers that don't support resuming.
* Make resume failures non-fatal (since we can still continue).

This was tested locally, end-to-end system test is future work.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Andrew Lytvynov 77127a2494
clientupdate: fix background install for linux tarballs (#9852)
Two bug fixes:
1. when tailscale update is executed as root, `os.UserCacheDir` may
   return an error because `$XDG_CACHE_HOME` and `$HOME` are not set;
   fallback to `os.TempDir` in those cases
2. on some weird distros (like my EndeavourOS), `/usr/sbin` is just a
   symlink to `/usr/bin`; when we resolve `tailscale` binary path from
   `tailscaled`, allow `tailscaled` to be in either directory

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Sonia Appasamy c27870e160 client/web: refactor authorizeRequest
Moves request authorization back into Server.serve to be run at
the start of any request. Fixes Synology unstable track bug where
client would get stuck unable to auth due to not rendering the
Synology redirect auth html on index.html load.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Joe Tsai c2a551469c
taildrop: implement asynchronous file deletion (#9844)
File resumption requires keeping partial files around for some time,
but we must still eventually delete them if never resumed.
Thus, we implement asynchronous file deletion, which could
spawn a background goroutine to delete the files.

We also use the same mechanism for deleting files on Windows,
where a file can't be deleted if there is still an open file handle.
We can enqueue those with the asynchronous file deleter as well.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Andrew Lytvynov 33bb2bbfe9
tailcfg,cmd/tailscale: add UrgentSecurityUpdate flag to ClientVersion (#9848)
This flag is used in clients to surface urgent updates more prominently.

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Irbe Krumina cac290da87
cmd/k8s-operator: users can configure firewall mode for kube operator proxies (#9769)
* cmd/k8s-operator: users can configure operator to set firewall mode for proxies

Users can now pass PROXY_FIREWALL_MODE={nftables,auto,iptables} to operator to make it create ingress/egress proxies with that firewall mode

Also makes sure that if an invalid firewall mode gets configured, the operator will not start provisioning proxy resources, but will instead log an error and write an error event to the related Service.

Updates tailscale/tailscale#9310

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
8 months ago
Tyler Smalley ddb2a6eb8d
cmd/tailscale: promote new serve/funnel CLI to be default (#9833)
The change is being kept to a minimum to make a revert easy if necessary. After the release, we will go back for a final cleanup.

updates #8489

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
8 months ago
Maisem Ali f53c3be07c cmd/k8s-operator: use our own container image instead of busybox
We already have sysctl in the `tailscale/tailscale` image, just use that.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Brad Fitzpatrick 1fc3573446 ipn/{conffile,ipnlocal}: start booting tailscaled from a config file w/ auth key
Updates #1412

Change-Id: Icd880035a31df59797b8379f4af19da5c4c453e2
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick 6ca8650c7b tstest/tstest: add t.Parallel that can be disabled by TS_SERIAL_TESTS=true
Updates #9841

Change-Id: I1b8f4d6e34ac8540e3b0455a7c79bd400e2721b7
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick 4dec0c6eb9 tstest, tstest/integration, github/workflows: shard integration tests
Over four jobs for now.

Updates #cleanup

Change-Id: Ic2b1a739a454916893945a3f9efc480d6fcbd70b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Maisem Ali e6ab7d3c14 cmd/testwrapper: parse args better
Previously we were just smushing together args and not trying
to parse the values at all. This resulted in the args to testwrapper
being limited and confusing.

This makes it so that testwrapper parses flags in the exact format as `go test`
command and passes them down in the provided order. It uses tesing.Init to
register flags that `go test` understands, however those are not the only
flags understood by `go test` (such as `-exec`) so we register these separately.

Updates tailscale/corp#14975

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Rhea Ghosh 9d3c6bf52e
ipn/ipnlocal/peerapi: refactoring taildrop to just one endpoint (#9832)
Updates #14772

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Maisem Ali 4899c2c1f4 cmd/containerboot: revert to using tailscale up
This partially reverts commits a61a9ab087
and 7538f38671 and fully reverts
4823a7e591.

The goal of that commit was to reapply known config whenever the
container restarts. However, that already happens when TS_AUTH_ONCE was
false (the default back then). So we only had to selectively reapply the
config if TS_AUTH_ONCE is true, this does exactly that.

This is a little sad that we have to revert to `tailscale up`, but it
fixes the backwards incompatibility problem.

Updates tailscale/tailscale#9539

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Andrew Lytvynov b949e208bb
ipn/ipnlocal: fix AllowsUpdate disable after enable (#9827)
The old code would always retain value `true` if it was set once, even
if you then change `prefs.AutoUpdate.Apply` to `false`.
Instead of using the previous value, use the default (envknob) value to
OR with.

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Brad Fitzpatrick 18bd98d35b cmd/tailscaled,*: add start of configuration file support
Updates #1412

Co-authored-by: Maisem Ali <maisem@tailscale.com>
Change-Id: I38d559c1784d09fc804f521986c9b4b548718f7d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Rhea Ghosh 71271e41d6
ipn/{ipnlocal/peerapi, localapi} initial taildrop resume api plumbing (#9798)
This change:
* adds a partial files peerAPI endpoint to get a list of partial files
* adds a helper function to extract the basename of a file
* updates the peer put peerAPI endpoint
* updates the file put localapi endpoint to allow resume functionality

Updates #14772

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Brad Fitzpatrick 95faefd1f6 net/dnsfallback: disable recursive resolver for now
It seems to be implicated in a CPU consumption bug that's not yet
understood. Disable it until we understand.

Updates tailscale/corp#15261

Change-Id: Ia6d0c310da6464dda79a70fc3c18be0782812d3f
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Andrew Lytvynov 8a5b02133d
clientupdate: return ErrUnsupported for macSys clients (#9793)
The Sparkle-based update is not quite working yet. Make `NewUpdater`
return `ErrUnsupported` for it to avoid the proliferation of exceptions
up the stack.

Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Flakes Updater 51078b6486 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
8 months ago
Brad Fitzpatrick 7fd6cc3caa go.mod: bump alexbrainman/sspi
For https://github.com/alexbrainman/sspi/pull/13

Fixes #9131 (hopefully)

Change-Id: I27bb00bbf5e03850f65f18c45f15c4441cc54b23
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Sonia Appasamy feabb34ea0 ipn/localapi: add debug-web-client endpoint
Debug endpoint for the web client's auth flow to talk back to the
control server. Restricted behind a feature flag on control.

We will either be removing this debug endpoint, or renaming it
before launching the web client updates.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Kristoffer Dalby e06f2f1873 ipn/ipnlocal: change serial number policy to be PreferenceOption
This commit changes the PostureChecking syspolicy key to be a
PreferenceOption(user-defined, always, never) instead of Bool.

This aligns better with the defaults implementation on macOS allowing
CLI arguments to be read when user-defined or no defaults is set.

Updates #tailscale/tailscale/5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
8 months ago
Denton Gentry 97ee3891f1 net/dns: use direct when NetworkManager has no systemd-resolved
Endeavour OS, at least, uses NetworkManager 1.44.2 and does
not use systemd-resolved behind the scenes at all. If we
find ourselves in that situation, return "direct" not
"systemd-resolved"

Fixes https://github.com/tailscale/tailscale/issues/9687

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
8 months ago
Brad Fitzpatrick 56ebcd1ed4 .github/workflows: break up race builder a bit more
Move the compilation of everything to its own job too, separate
from test execution.

Updates #7894

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick e89927de2b tsnet: fix data race in TestFallbackTCPHandler
Fixes #9805

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick 18e2936d25 github/workflows: move race tests to their own job
They're slow. Make them their own job that can run in parallel.

Also, only run them in race mode. No need to run them on 386
or non-race amd64.

Updates #7894

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick c363b9055d tstest/integration: add tests for tun mode (requiring root)
Updates #7894

Change-Id: Iff0b07b21ae28c712dd665b12918fa28d6f601d0
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick a6270826a3 wgengine/magicsock: fix data race regression in disco ping callbacks
Regression from c15997511d. The callback could be run multiple times
from different endpoints.

Fixes #9801

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Maisem Ali 5297bd2cff cmd/tailscaled,net/tstun: fix data race on start-up in TUN mode
Fixes #7894

Change-Id: Ice3f8019405714dd69d02bc07694f3872bb598b8

Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Brad Fitzpatrick 5c555cdcbb tstest/integration: set race flag when cross compiling, conditionally fail on race
Misc cleanups and things noticed while working on #7894 and pulled out
of a separate change. Submitting them on their own to not distract
from later changes.

Updates #7894

Change-Id: Ie9abc8b88f121c559aeeb7e74db2aa532eb84d3d
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Rhea Ghosh 8c7169105e
ipn/{ipnlocal/peerapi, localapi}: cleaning up http statuses for consistency and readability (#9796)
Updates #cleanup

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Joe Tsai 9cb6c5bb78
util/httphdr: add new package for parsing HTTP headers (#9797)
This adds support for parsing Range and Content-Range headers
according to RFC 7230. The package could be extended in the future
to handle other headers.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Andrew Lytvynov af5a586463
ipn/ipnlocal: include AutoUpdate prefs in HostInfo.AllowsUpdate (#9792)
Updates #9260

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Claire Wang 754fb9a8a8
tailcfg: add tailnet field to register request (#9675)
Updates tailscale/corp#10967

Signed-off-by: Claire Wang <claire@tailscale.com>
8 months ago
Joe Tsai 8f948638c5
taildrop: minor cleanups and fixes (#9786)
Perform the same m==nil check in Manager.{PartialFiles,HashPartialFile}
as we do in the other methods.

Fix HashPartialFile is properly handle a length of -1.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Joe Tsai b1867eb23f
taildrop: add logic for resuming partial files (#9785)
We add the following API:
* type FileChecksums
* type Checksum
* func Manager.PartialFiles
* func Manager.HashPartialFile
* func ResumeReader

The Manager methods provide the ability to query for partial files
and retrieve a list of checksums for a given partial file.
The ResumeReader function is a helper that wraps an io.Reader
to discard content that is identical locally and remotely.
The FileChecksums type represents the checksums of a file
and is safe to JSON marshal and send over the wire.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Maisem Ali 24f322bc43 ipn/ipnlocal: do unexpired cert renewals in the background
We were eagerly doing a synchronous renewal of the cert while
trying to serve traffic. Instead of that, just do the cert
renewal in the background and continue serving traffic as long
as the cert is still valid.

This regressed in c1ecae13ab when
we introduced ARI support and were trying to make the experience
of `tailscale cert` better. However, that ended up regressing
the experience for tsnet as it would not always doing the renewal
synchronously.

Fixes #9783

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Joe Tsai 1a78f240b5
tstime: add DefaultClock (#9691)
In almost every single use of Clock, there is a default behavior
we want to use when the interface is nil,
which is to use the the standard time package.

The Clock interface exists only for testing,
and so tests that care about mocking time
can adequately plumb the the Clock down the stack
and through various data structures.

However, the problem with Clock is that there are many
situations where we really don't care about mocking time
(e.g., measuring execution time for a log message),
where making sure that Clock is non-nil is not worth the burden.
In fact, in a recent refactoring, the biggest pain point was
dealing with nil-interface panics when calling tstime.Clock methods
where mocking time wasn't even needed for the relevant tests.
This required wasted time carefully reviewing the code to
make sure that tstime.Clock was always populated,
and even then we're not statically guaranteed to avoid a nil panic.

Ideally, what we want are default methods on Go interfaces,
but such a language construct does not exist.
However, we can emulate that behavior by declaring
a concrete type that embeds the interface.
If the underlying interface value is nil,
it provides some default behavior (i.e., use StdClock).

This provides us a nice balance of two goals:
* We can plumb tstime.DefaultClock in all relevant places
  for use with mocking time in the tests that care.
* For all other logic that don't care about,
  we never need to worry about whether tstime.DefaultClock
  is nil or not. This is especially relevant in production code
  where we don't want to panic.

Longer-term, we may want to perform a large-scale change
where we rename Clock to ClockInterface
and rename DefaultClock to just Clock.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Naman Sood 7783a960e8
client/web: add metric for exit node advertising (#9781)
* client/web: add metric for exit node advertising

Updates tailscale/corp#15215

Signed-off-by: Naman Sood <mail@nsood.in>

* client/web: use http request's context for IncrementCounter

Updates #cleanup

Signed-off-by: Naman Sood <mail@nsood.in>

---------

Signed-off-by: Naman Sood <mail@nsood.in>
8 months ago
James Tucker ce0830837d appctype: introduce a configuration schema for app connectors
Updates tailscale/corp#15043

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Joe Tsai 37c646d9d3
taildrop: improve the functionality and reliability of put (#9762)
Changes made:
* Move all HTTP related functionality from taildrop to ipnlocal.
* Add two arguments to taildrop.Manager.PutFile to specify
  an opaque client ID and a resume offset (both unused for now).
* Cleanup the logic of taildrop.Manager.PutFile
  to be easier to follow.
* Implement file conflict handling where duplicate files are renamed
  (e.g., "IMG_1234.jpg" -> "IMG_1234 (2).jpg").
* Implement file de-duplication where "renaming" a partial file
  simply deletes it if it already exists with the same contents.
* Detect conflicting active puts where a second concurrent put
  results in an error.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Maisem Ali 1294b89792 cmd/k8s-operator: allow setting same host value for tls and ingress rules
We were too strict and required the user not specify the host field at all
in the ingress rules, but that degrades compatibility with existing helm charts.

Relax the constraint so that rule.Host can either be empty, or match the tls.Host[0]
value exactly.

Fixes #9548

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Maisem Ali 2d4f808a4c cmd/containerboot: fix time based serveConfig watcher
This broke in a last minute refactor and seems to have never worked.

Fixes #9686

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
James Tucker 4abd470322 tailcfg: implement text encoding for ProtoPortRange
Updates tailscale/corp#15043
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker 96f01a73b1 tailcfg: import ProtoPortRange for local use
Imported type and parsing, with minor modifications.

Updates tailscale/corp#15043

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Charlotte Brandhorst-Satzkorn d62af8e643 words: flappy birds, but real life
These birds have been visually identified as having tails. Science
prevails.

Updates tailscale/corp#9599

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
8 months ago
Maisem Ali 1cb9e33a95 cmd/k8s-operator: update env var in manifest to APISERVER_PROXY
Replace the deprecated var with the one in docs to avoid confusion.
Introduced in 335a5aaf9a.

Updates #8317
Fixes #9764

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
James Tucker c1ef55249a types/ipproto: import and test string parsing for ipproto
IPProto has been being converted to and from string formats in multiple
locations with variations in behavior. TextMarshaller and JSONMarshaller
implementations are now added, along with defined accepted and preferred
formats to centralize the logic into a single cross compatible
implementation.

Updates tailscale/corp#15043
Fixes tailscale/corp#15141

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Maisem Ali 319607625f ipn/ipnlocal: fix log spam from now expected paths
These log paths were actually unexpected until the refactor in
fe95d81b43. This moves the logs
to the callsites where they are actually unexpected.

Fixes #9670

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Maisem Ali 9d96e05267 net/packet: split off checksum munging into different pkg
The current structure meant that we were embedding netstack in
the tailscale CLI and in the GUIs. This removes that by isolating
the checksum munging to a different pkg which is only called from
`net/tstun`.

Fixes #9756

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Brad Fitzpatrick 8b630c91bc wgengine/filter: use slices.Contains in another place
We keep finding these.

Updates #cleanup

Change-Id: Iabc049b0f8da07341011356f0ecd5315c33ff548
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
James 'zofrex' Sanderson 0a412eba40
words: Na na na na na na na na na na na na na na na na (#9753)
So gnarly!

Updates tailscale/corp#14698

Signed-off-by: James Sanderson <jsanderson@tailscale.com>
8 months ago
James Tucker 11348fbe72 util/nocasemaps: import nocasemaps from corp
This is a dependency of other code being imported later.

Updates tailscale/corp#15043

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Maisem Ali fbfee6a8c0 cmd/containerboot: use linuxfw.NetfilterRunner
This migrates containerboot to reuse the NetfilterRunner used
by tailscaled instead of manipulating iptables rule itself.
This has the added advantage of now working with nftables and
we can potentially drop the `iptables` command from the container
image in the future.

Updates #9310

Co-authored-by: Irbe Krumina <irbe@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Sonia Appasamy 7a0de2997e client/web: remove unused context param from NewServer
Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Maisem Ali aad3584319 util/linuxfw: move fake runner into pkg
This allows using the fake runner in different packages
that need to manage filter rules.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Tom DNetto fffafc65d6 tsnet: support registering fallback TCP flow handlers
For the app connector use-case, it doesnt make sense to use listeners, because then you would
need to register thousands of listeners (for each proto/service/port combo) to handle ranges.

Instead, we plumb through the TCPHandlerForFlow abstraction, to avoid using the listeners
abstraction that would end up being a bit messy.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates: https://github.com/tailscale/corp/issues/15038
8 months ago
David Anderson 9f05018419 clientupdate/distsign: add new prod root signing key to keychain
Updates tailscale/corp#15179

Signed-off-by: David Anderson <danderson@tailscale.com>
8 months ago
Galen Guyer 04a8b8bb8e net/dns: properly detect newer debian resolvconf
Tailscale attempts to determine if resolvconf or openresolv
is in use by running `resolvconf --version`, under the assumption
this command will error when run with Debian's resolvconf. This
assumption is no longer true and leads to the wrong commands being
run on newer versions of Debian with resolvconf >= 1.90. We can
now check if the returned version string starts with "Debian resolvconf"
if the command is successful.

Fixes #9218

Signed-off-by: Galen Guyer <galen@galenguyer.com>
8 months ago
Paul Scott 4e083e4548
util/cmpver: only consider ascii numerals (#9741)
Fixes #9740

Signed-off-by: Paul Scott <paul@tailscale.com>
8 months ago
Maisem Ali 78a083e144 types/ipproto: drop IPProto from IPProtoVersion
Based on https://github.com/golang/go/wiki/CodeReviewComments#package-names.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Maisem Ali 05a1f5bf71 util/linuxfw: move detection logic
Just a refactor to consolidate the firewall detection logic in a single
package so that it can be reused in a later commit by containerboot.

Updates #9310

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Maisem Ali 56c0a75ea9 tool/gocross: handle VERSION file not found
Fixes #9734

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
James Tucker ba6ec42f6d util/linuxfw: add missing input rule to the tailscale tun
Add an explicit accept rule for input to the tun interface, as a mirror
to the explicit rule to accept output from the tun interface.

The rule matches any packet in to our tun interface and accepts it, and
the rule is positioned and prioritized such that it should be evaluated
prior to conventional ufw/iptables/nft rules.

Updates #391
Fixes #7332
Updates #9084

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Andrew Lytvynov 677d486830
clientupdate: abort if current version is newer than latest (#9733)
This is only relevant for unstable releases and local builds. When local
version is newer than upstream, abort release.

Also, re-add missing newlines in output that were missed in
https://github.com/tailscale/tailscale/pull/9694.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Will Norris 7f08bddfe1 tailcfg: add type for web client auth response
This will be returned from the upcoming control endpoints for doing web
client session authentication.

Updates tailscale/corp#14335

Signed-off-by: Will Norris <will@tailscale.com>
8 months ago
Flakes Updater 00977f6de9 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
8 months ago
License Updater 0ccfcb515c licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
8 months ago
Brad Fitzpatrick 3749a3bbbb go.toolchain.rev: bump for CVE-2023-39325
Updates tailscale/corp#15165

Change-Id: Ib001cfb44eb3e6d735dfece9bd3ae9eea13048c9
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick 6b1ed732df go.mod: bump x/net to 0.17 for CVE-2023-39325
https://go.googlesource.com/net/+/b225e7ca6dde1ef5a5ae5ce922861bda011cfabd

Updates tailscale/corp#15165

Change-Id: Ia8b5e16b1acfe1b2400d321034b41370396f70e2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick 70de16bda7 ipn/localapi: make whois take IP or IP:port as documented, fix capmap netstack lookup
The whois handler was documented as taking IP (e.g. 100.101.102.103)
or IP:port (e.g. usermode 127.0.0.1:1234) but that got broken at some point
and we started requiring a port always. Fix that.

Also, found in the process of adding tests: fix the CapMap lookup in
userspace mode (it was always returning the caps of 127.0.0.1 in
userspace mode). Fix and test that too.

Updates #9714

Change-Id: Ie9a59744286522fa91c4b70ebe89a1e94dbded26
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Kristoffer Dalby 7f540042d5 ipn/ipnlocal: use syspolicy to determine collection of posture data
Updates #5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
8 months ago
Kristoffer Dalby d0b8bdf8f7 posture: add get serial support for macOS
Updates #5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
8 months ago
Kristoffer Dalby 9eedf86563 posture: add get serial support for Windows/Linux
This commit adds support for getting serial numbers from SMBIOS
on Windows/Linux (and BSD) using go-smbios.

Updates #5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
8 months ago
Val 249edaa349 wgengine/magicsock: add probed MTU metrics
Record the number of MTU probes sent, the total bytes sent, the number of times
we got a successful return from an MTU probe of a particular size, and the max
MTU recorded.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 893bdd729c disco,net/tstun,wgengine/magicsock: probe peer MTU
Automatically probe the path MTU to a peer when peer MTU is enabled, but do not
use the MTU information for anything yet.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Kristoffer Dalby b4e587c3bd tailcfg,ipn: add c2n endpoint for posture identity
Updates #5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
8 months ago
Kristoffer Dalby 9593cd3871 posture: add get serial stub for all platforms
Updates #5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
8 months ago
Kristoffer Dalby 623926a25d cmd/tailscale: add --posture-checking flag to set
Updates #5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
8 months ago
Kristoffer Dalby 886917c42b ipn: add PostureChecks to Prefs
Updates #5902

Signed-off-by: Kristoffer Dalby <kristoffer@tailscale.com>
8 months ago
Simon Leonhardt 553f657248 sniproxy allows configuration of hostname
Signed-off-by: Simon Leonhardt <simon@controlzee.com>
8 months ago
Brad Fitzpatrick 6f36f8842c cmd/tailscale, magicsock: add debug command to flip DERP homes
For testing netmap patchification server-side.

Updates #1909

Change-Id: Ib1d784bd97b8d4a31e48374b4567404aae5280cc
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
James Tucker 13767e5108 docs/sysv: add a sysv style init script
The script depends on a sufficiently recent start-stop-daemon as to
provide the `-m` and `--remove-pidfile` flags.

Updates #9502

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Brad Fitzpatrick f991c8a61f tstest: make ResourceCheck panic on parallel tests
To find potential flakes earlier.

Updates #deflake-effort

Change-Id: I52add6111d660821c3a23d4b1dd032821344bc48
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
James Tucker 498f7ec663 syncs: add Map.LoadOrInit for lazily initialized values
I was reviewing some code that was performing this by hand, and wanted
to suggest using syncs.Map, however as the code in question was
allocating a non-trivial structure this would be necessary to meet the
target.

Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Joe Tsai e4cb83b18b
taildrop: document and cleanup the package (#9699)
Changes made:
* Unexport declarations specific to internal taildrop functionality.
* Document all exported functionality.
* Move TestRedactErr to the taildrop package.
* Rename and invert Handler.DirectFileDoFinalRename as AvoidFinalRename.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Andrew Lytvynov e6aa7b815d
clientupdate,cmd/tailscale/cli: use cli.Stdout/Stderr (#9694)
In case cli.Stdout/Stderr get overriden, all CLI output should use them
instead of os.Stdout/Stderr. Update the `update` command to follow this
pattern.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Brad Fitzpatrick b7988b3825 api.md: remove clientConnectivity.derp field
We don't actually send this. It's always been empty.

Updates tailscale/corp#13400

Change-Id: I99b3d7a355fca17d2159bf81ede5be4ddd4b9dc9
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Rhea Ghosh 557ddced6c
{ipn/ipnlocal, taildrop}: move put logic to taildrop (#9680)
Cleaning up taildrop logic for sending files.

Updates tailscale/corp#14772

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
Co-authored-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
David Anderson c761d102ea tool/gocross: don't absorb --tags flags passed to subcommand
Fixes tailscale/corp#15117

Signed-off-by: David Anderson <danderson@tailscale.com>
8 months ago
Andrew Lytvynov 559f560d2d
go.toolchain.rev: bump go to 1.21.2 (#9677)
Updates https://github.com/tailscale/go/pull/75

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Joe Tsai c42398b5b7
ipn/ipnlocal: cleanup incomingFile (#9678)
This is being moved to taildrop, so clean it up to stop depending
on so much unreleated functionality by removing a dependency
on peerAPIHandler.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Andrew Lytvynov 3ee756757b
cmd/tailscale/cli: add update notification to "up" (#9644)
Add available update message in "tailscale up" output. Also update the
message in "tailscale status" to match and mention auto-update.

Updates https://github.com/tailscale/tailscale/issues/755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
8 months ago
Rhea Ghosh dc1c7cbe3e
taildrop: initial commit of taildrop functionality refactoring (#9676)
Over time all taildrop functionality will be contained in the
taildrop package. This will include end to end unit tests. This is
simply the first smallest piece to move over.

There is no functionality change in this commit.

Updates tailscale/corp#14772

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
Co-authored-by: Joseph Tsai <joetsai@tailscale.com>
8 months ago
Sonia Appasamy 3befc0ef02 client/web: restrict full management client behind browser sessions
Adds `getTailscaleBrowserSession` to pull the user's session out of
api requests, and `serveTailscaleAuth` to provide the "/api/auth"
endpoint for browser to request auth status and new sessions.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Brad Fitzpatrick 7868393200 net/dns/resolver, ipnlocal: fix ExitDNS on Android and iOS
Advertise it on Android (it looks like it already works once advertised).

And both advertise & likely fix it on iOS. Yet untested.

Updates #9672

Change-Id: If3b7e97f011dea61e7e75aff23dcc178b6cf9123
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick b4816e19b6 hostinfo, ipnlocal: flesh out Wake-on-LAN support, send MACs, add c2n sender
This optionally uploads MAC address(es) to control, then adds a
c2n handler so control can ask a node to send a WoL packet.

Updates #306

RELNOTE=now supports waking up peer nodes on your LAN via Wake-on-LAN packets

Change-Id: Ibea1275fcd2048dc61d7059039abfbaf1ad4f465
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Tom DNetto da1b917575 net/tstun: finish wiring IPv6 NAT support
Updates https://github.com/tailscale/corp/issues/11202
Updates ENG-991
Signed-off-by: Tom DNetto <tom@tailscale.com>
8 months ago
Brad Fitzpatrick 52e4f24c58 portlist: populate Pid field on Linux
The Port.Pid was always more of an implementation detail on some
platforms and isn't necessary on Linux so it was never populated.
(Nothing outside the portlist package ever used it)

But might as well populate it for consistency since we have it in
memory and its absence confused people.

Updates #cleanup

Change-Id: I869768a75c9fedeff242a5452206e2b2947a17cb
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Sonia Appasamy b29047bcf0 client/web: add browser session cache to web.Server
Adds browser session cache, to be used to store sessions for the
full management web client.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Brad Fitzpatrick e499a6bae8 release/dist/unixpkgs: revert iptables move to Recommends, make it Depends
Partially reverts 1bd3edbb46 (but keeps part of it)

iptables is almost always required but not strictly needed.  Even if
you can technically run Tailscale without it (by manually configuring
nftables or userspace mode), we still now mark this as "Depends"
because our previous experiment in
https://github.com/tailscale/tailscale/issues/9236 of making it only
Recommends caused too many problems. Until our nftables table is more
mature, we'd rather err on the side of wasting a little disk by
including iptables for people who might not need it rather than
handle reports of it being missing.

Updates #9236

Change-Id: I86cc8aa3f78dafa0b4b729f55fb82eef6066be1c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick 93c6e1d53b tstest/deptest: add check that x/exp/{maps,slices} imported as xfoo
Updates #cleanup

Change-Id: I4cbb5e477c739deddf7a46b66f286c9fdb106279
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Andrew Dunham 91b9899402 net/dns/resolver: fix flaky test
Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I2d073220bb6ac78ba88d8be35085cc23b727d69f
8 months ago
Brad Fitzpatrick 730cdfc1f7 Revert "tool/gocross: disable Linux static linking if GOCROSS_STATIC=0"
This reverts commit 2c0f0ee759.

Fixed by efac2cb8d6

Updates tailscale/corp#15058
Updates tailscale/corp#13113
8 months ago
Maisem Ali 3655fb3ba0 control/controlclient: fix deadlock in shutdown
Fixes a deadlock observed in a different repo.
Regressed in 5b3f5eabb5.

Updates tailscale/corp#14950
Updates tailscale/corp#14515
Updates tailscale/corp#14139
Updates tailscale/corp#13175

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Andrew Dunham 5902d51ba4 util/race: add test to confirm we don't leak goroutines
Updates #cleanup

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Iff147268db50251d498fff5213adb8d4b8c999d4
8 months ago
Andrew Dunham 286c6ce27c
net/dns/resolver: race UDP and TCP queries (#9544)
Instead of just falling back to making a TCP query to an upstream DNS
server when the UDP query returns a truncated query, also start a TCP
query in parallel with the UDP query after a given race timeout. This
ensures that if the upstream DNS server does not reply over UDP (or if
the response packet is blocked, or there's an error), we can still make
queries if the server replies to TCP queries.

This also adds a new package, util/race, to contain the logic required for
racing two different functions and returning the first non-error answer.

Updates tailscale/corp#14809

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I4311702016c1093b1beaa31b135da1def6d86316
8 months ago
Jordan Whited eb22c0dfc7
wgengine/magicsock: use binary.NativeEndian for UDP GSO control data (#9640)
Updates #cleanup

Signed-off-by: Jordan Whited <jordan@tailscale.com>
8 months ago
Brad Fitzpatrick efac2cb8d6 tool/gocross: merge user's build tags and implicitly added build tags together
Fixes tailscale/corp#15058

Change-Id: I7e539b3324153077597f30385a2cb540846e8bdc
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick b775a3799e util/httpm, all: add a test to make sure httpm is used consistently
Updates #cleanup

Change-Id: I7dbf8a02de22fc6b317ab5e29cc97792dd75352c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Val 73e53dcd1c cmd/tailscale,ipn/ipnlocal: print debug component names
Make the 'tailscale debug component-logs' command print the component names for
which extra logging can be turned on, for easier discoverability of debug
functions.

Updates #cleanup

Co-authored-by: Paul Scott <paul@tailscale.com>
Signed-off-by: Val <valerie@tailscale.com>
8 months ago
License Updater 5efd5e093e licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
8 months ago
License Updater 6cbd002eda licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
8 months ago
Tom DNetto 656a77ab4e net/packet: implement methods for rewriting v6 addresses
Implements the ability for the address-rewriting code to support rewriting IPv6 addresses.

Specifically, UpdateSrcAddr & UpdateDstAddr.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates https://github.com/tailscale/corp/issues/11202
8 months ago
Val c26d91d6bd net/tstun: remove unused function DefaultMTU()
Now that corp is updated, remove the shim code to bridge the rename from
DefaultMTU() to DefaultTUNMTU.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 4130851f12 wgengine/magicsock: probe but don't use path MTU from CLI ping
When sending a CLI ping with a specific size, continue to probe all possible UDP
paths to the peer until we find one with a large enough MTU to accommodate the
ping. Record any peer path MTU information we discover (but don't use it for
anything other than CLI pings).

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 67926ede39 wgengine/magicsock: add MTU to addrLatency and rename to addrQuality
Add a field to record the wire MTU of the path to this address to the
addrLatency struct and rename it addrQuality.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Brad Fitzpatrick 425cf9aa9d tailcfg, all: use []netip.AddrPort instead of []string for Endpoints
It's JSON wire compatible.

Updates #cleanup

Change-Id: Ifa5c17768fec35b305b06d75eb5f0611c8a135a6
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick 5f5c9142cc util/slicesx: add EqualSameNil, like slices.Equal but same nilness
Then use it in tailcfg which had it duplicated a couple times.

I think we have it a few other places too.

And use slices.Equal in wgengine/router too. (found while looking for callers)

Updates #cleanup

Change-Id: If5350eee9b3ef071882a3db29a305081e4cd9d23
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Flakes Updater 72e53749c1 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
8 months ago
Brad Fitzpatrick d2ea9bb1eb cmd/cloner: fix typo in test type's name
s/SliceContianer/SliceContainer/g

Updates #9604

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
James Tucker ab810f1f6d cmd/cloner: add regression test for slice nil/empty semantics
We had a misstep with the semantics when applying an optimization that
showed up in the roll into corp. This test ensures that case and related
cases must be retained.

Updates #9410
Updates #9601
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker e03f0d5f5c net/dnsfallback: remove net/dnsfallback go:generate line
We should be able to freely run `./tool/go generate ./...`, but we're
continually dodging this particular generator. Instead of constantly
dodging it, let's just remove it.

Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Claire Wang a56e58c244
util/syspolicy: add read boolean setting (#9592) 8 months ago
James Tucker 324f0d5f80 cmd/cloner,*: revert: optimize nillable slice cloner
This reverts commit ee90cd02fd.

The outcome is not identical for empty slices. Cloner really needs
tests!

Updates #9601

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker ee90cd02fd cmd/cloner,*: optimize nillable slice cloner
A wild @josharian appears with a good suggestion for a refactor, thanks
Josh!

Updates #9410
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Charlotte Brandhorst-Satzkorn e91e96dfa5 words: i can't help but rave about these additions
It's no conspiracy that I love learning about new words.

Updates tailscale/corp#14698

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
8 months ago
James Tucker 41b05e6910 go.mod: bump wireguard-go
Updates #9555
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Charlotte Brandhorst-Satzkorn db9c0d0a63 words: gonna take some time to add the words we never had
(ooh, ooh)

Updates #tailscale/corp#14698

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
8 months ago
Jordan Whited 16fa3c24ea
wgengine/magicsock: use x/sys/unix constants for UDP GSO (#9597)
Updates #cleanup

Signed-off-by: Jordan Whited <jordan@tailscale.com>
8 months ago
License Updater a74970305b licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
8 months ago
Chris Palmer 8833dc51f1
util/set: add some useful utility functions for Set (#9535)
Also give each type of set its own file.

Updates #cleanup

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
8 months ago
James Tucker 0c8c374a41 go.mod: bump all dependencies except go-billy
go-billy is held back at v5.4.1 in order to avoid a newly introduced
subdependency that is not compatible with plan9.

Updates #8043
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker 84acf83019 go.mod,net/dnsfallback: bump go4.org/netipx
Updates #8043
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker 87bc831730 go.mod,cmd/tsconnect: bump esbuild
Updates #8043
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker 71f2c67c6b go.mod: bump wingoes for cross-platform HRESULT definition
Updates #9579
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Brad Fitzpatrick aae1a28a2b go.mod: add test that replace directives aren't added in oss
Prevent future problems like we earlier with go.mod replace directives
(e.g. removing our certstore replace in 6d6cf88d82 or wireguard-go
in ea5ee6f87c, both of which were reactions to problems caused by
go.mod replace in non-root modules, often because people are using tsnet
as a library from another module)

Updates #cleanup

Change-Id: I766715cfa7ce7021460ba4933bd2fa977c3081d2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Claire Wang 32c0156311
util: add syspolicy package (#9550)
Add a more generalized package for getting policies.
Updates tailcale/corp#10967

Signed-off-by: Claire Wang <claire@tailscale.com>
Co-authored-by: Adrian Dewhurst <adrian@tailscale.com>
8 months ago
Maisem Ali d71184d674 cmd/containerboot: only wipeout serve config when TS_SERVE_CONFIG is set
Fixes #9558

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Brad Fitzpatrick 246e0ccdca tsnet: add a test for restarting a tsnet server, fix Windows
Thanks to @qur and @eric for debugging!

Fixes #6973

Change-Id: Ib2cf8f030cf595cc73dd061c72e78ac19f5fae5d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Denton Gentry 4823a7e591 cmd/containerboot: set TS_AUTH_ONCE default to true.
1.50.0 switched containerboot from using `tailscale up`
to `tailscale login`. A side-effect is that a re-usable
authkey is now re-applied on every boot by `tailscale login`,
where `tailscale up` would ignore an authkey if already
authenticated.

Though this looks like it is changing the default, in reality
it is setting the default to match what 1.48 and all
prior releases actually implemented.

Fixes https://github.com/tailscale/tailscale/issues/9539
Fixes https://github.com/tailscale/corp/issues/14953

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
8 months ago
Brad Fitzpatrick 856d32b4a9 cmd/testwrapper: include flake URL in JSON metadata
Updates tailscale/corp#14975

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Flakes Updater 2a7b3ada58 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
8 months ago
Andrea Barisani f50b2a87ec wgengine/netstack: refactor address construction and conversion
Updates #9252
Updates #9253

Signed-off-by: Andrea Barisani <andrea@inversepath.com>
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Andrea Barisani b5b4298325 go.mod,*: bump gvisor
Updates #9253

Signed-off-by: Andrea Barisani <andrea@inversepath.com>
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Brad Fitzpatrick 2c92f94e2a cmd/testwrapper: output machine-readable JSON on test flakes
For parsing by other tools.

Updates tailscale/corp#14975

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Sonia Appasamy 5429ee2566 client/web: add debug mode for web client ui updates
UI updates staged behind debug mode flags. Initial new views added
in app.tsx, rendered based on the current debug setting.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Brad Fitzpatrick 5b3f5eabb5 control/controlclient: fix leaked http2 goroutines on shutdown
If a noise dial was happening concurrently with shutdown, the
http2 goroutines could leak.

Updates tailscale/corp#14950
Updates tailscale/corp#14515
Updates tailscale/corp#14139
Updates tailscale/corp#13175

Signed-off-by: Brad Fitzpatrick <brad@danga.com>
8 months ago
Brad Fitzpatrick 2c0f0ee759 tool/gocross: disable Linux static linking if GOCROSS_STATIC=0
So we can experiment with disabling static linking for tests in CI to
make GitHub Actions output less spammy.

Updates tailscale/corp#13113

Signed-off-by: Brad Fitzpatrick <brad@danga.com>
8 months ago
Sonia Appasamy 5d62b17cc5 client/web: add login client mode to web.Server
Adds new LoginOnly server option and swaps out API handler depending
on whether running in login mode or full web client mode.

Also includes some minor refactoring to the synology/qnap authorization
logic to allow for easier sharing between serveLoginAPI and serveAPI.

Updates tailscale/corp#14335

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Maisem Ali 354455e8be ipn: use NodeCapMap in CheckFunnel
These were missed when adding NodeCapMap and resulted
in tsnet binaries not being able to turn on funnel.

Fixes #9566

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
James Tucker 5c2b2fa1f8 ipn/ipnlocal: plumb ExitNodeDNSResolvers for IsWireGuardOnly exit nodes
Control sends ExitNodeDNSResolvers when configured for IsWireGuardOnly
nodes that are to be used as the default resolver with a lower
precedence than split DNS, and a lower precedence than "Override local
DNS", but otherwise before local DNS is used when the exit node is in
use.

Neither of the below changes were problematic, but appeared so alongside
a number of other client and external changes. See tailscale/corp#14809.

Reland ea9dd8fabc.
Reland d52ab181c3.

Updates #9377
Updates tailscale/corp#14809

Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker ca4396107e types/key: update some doc strings for public key serialization
Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker 80206b5323 wgengine/magicsock: add nodeid to panic condition on public key reuse
If the condition arises, it should be easy to track down.

Updates #9547
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
James Tucker 2066f9fbb2 util/linuxfw: fix crash in DelSNATRule when no rules are found
Appears to be a missing nil handling case. I looked back over other
usage of findRule and the others all have nil guards. findRule returns
nil when no rules are found matching the arguments.

Fixes #9553
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Sonia Appasamy 697f92f4a7 client/web: refactor serveGetNodeData
Remove the "JSON" ending, we no longer have a non-JSON version,
it was removed in d74c771 when we switched from the legacy web
client to React.

Also combine getNodeData into serveGetNodeData now that serveGetNodeData
is the single caller of getNodeData.

A #cleanup

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
8 months ago
Andrew Dunham d31460f793 net/portmapper: fix invalid UPnP metric name
Fixes #9551

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I06f3a15a668be621675be6cbc7e5bdcc006e8570
8 months ago
Brad Fitzpatrick 3e298e9380 go.toolchain.rev: bump go
Updates tailscale/go#74

Change-Id: I3858d785acadae6822e2387e5e62f234c4625927
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Rhea Ghosh 0275afa0c6
ipn/ipnlocal: prevent putting file if file already exists (#9515)
Also adding tests to ensure this works.

Updates tailscale/corp#14772

Signed-off-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Claire Wang e3d6236606
winutil: refactor methods to get values from registry to also return (#9536)
errors
Updates tailscale/corp#14879

Signed-off-by: Claire Wang <claire@tailscale.com>
8 months ago
Val c608660d12 wgengine,net,ipn,disco: split up and define different types of MTU
Prepare for path MTU discovery by splitting up the concept of
DefaultMTU() into the concepts of the Tailscale TUN MTU, MTUs of
underlying network interfaces, minimum "safe" TUN MTU, user configured
TUN MTU, probed path MTU to a peer, and maximum probed MTU. Add a set
of likely MTUs to probe.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 578b357849 wgengine/netstack: use buffer pools for UDP packet forwarding
Use buffer pools for UDP packet forwarding to prepare for increasing the
forwarded UDP packet size for peer path MTU discovery.

Updates #311

Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Irbe Krumina bdd9eeca90
cmd/k8s-operator: fix reconcile filters (#9533)
Ensure that when there is an event on a Tailscale managed Ingress or Service child resource, the right parent type gets reconciled

Updates tailscale/tailscale#502

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
8 months ago
Marwan Sulaiman 651620623b ipn/ipnlocal: close foreground sessions on SetServeConfig
This PR ensures zombie foregrounds are shutdown if a new
ServeConfig is created that wipes the ongoing foreground ones.
For example, "tailscale serve|funnel reset|off" should close
all open sessions.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
8 months ago
Andrew Dunham 530aaa52f1 net/dns: retry forwarder requests over TCP
We weren't correctly retrying truncated requests to an upstream DNS
server with TCP. Instead, we'd return a truncated request to the user,
even if the user was querying us over TCP and thus able to handle a
large response.

Also, add an envknob and controlknob to allow users/us to disable this
behaviour if it turns out to be buggy ( DNS ).

Updates #9264

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ifb04b563839a9614c0ba03e9c564e8924c1a2bfd
8 months ago
Aaron Klotz 098d110746 VERSION.txt: this is v1.51.0
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
8 months ago
License Updater 7aed9712d8 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
8 months ago
Brad Fitzpatrick 04fabcd359 ipn/{ipnlocal,localapi}, cli: add debug force-netmap-update
For loading testing & profiling the cost of full netmap updates.

Updates #1909

Change-Id: I0afdf5de9967f8d95c7f81d5b531ed1c92c3208f
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Anton Tolchanov 75dbd71f49 api.md: document the `invalid` field in Get Key API response
Updates tailscale/terraform-provider-tailscale#144

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
8 months ago
Brad Fitzpatrick 241c983920 net/tstun: use untyped consts, simplify DefaultMTU func
Updates #cleanup

Change-Id: Ic9ad1d6134818699f777c66a31024e846dfdc5d4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Brad Fitzpatrick 3b32d6c679 wgengine/magicsock, controlclient, net/dns: reduce some logspam
Updates #cleanup

Change-Id: I78b0697a01e94baa33f3de474b591e616fa5e6af
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Val 08302c0731 Revert "wgengine/netstack: use buffer pools for UDP packet forwarding"
This reverts commit fb2f3e4741.

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 6cc5b272d8 Revert "wgengine,net,ipn,disco: split up and define different types of MTU"
This reverts commit 059051c58a.

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 059051c58a wgengine,net,ipn,disco: split up and define different types of MTU
Prepare for path MTU discovery by splitting up the concept of
DefaultMTU() into the concepts of the Tailscale TUN MTU, MTUs of
underlying network interfaces, minimum "safe" TUN MTU, user configured
TUN MTU, probed path MTU to a peer, and maximum probed MTU. Add a set
of likely MTUs to probe.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val fb2f3e4741 wgengine/netstack: use buffer pools for UDP packet forwarding
Use buffer pools for UDP packet forwarding to prepare for increasing the
forwarded UDP packet size for peer path MTU discovery.

Updates #311

Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: Val <valerie@tailscale.com>
8 months ago
License Updater 81e8335e23 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
8 months ago
Flakes Updater b83804cc82 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
8 months ago
Joe Tsai 36242904f1
go.mod: update github.com/go-json-experiment/json (#9508)
Update github.com/go-json-experiment/json to the latest version
and fix the build in light of some breaking API changes.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
James Tucker a82a74f2cf cmd/containerboot: avoid leaking bash scripts after test runs
The test was sending SIGKILL to containerboot, which results in no
signal propagation down to the bash script that is running as a child
process, thus it leaks.

Minor changes to the test daemon script, so that it cleans up the socket
that it creates on exit, and spawns fewer processes.

Fixes tailscale/corp#14833
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
License Updater c5006f143f licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
8 months ago
Aaron Klotz ea6ca78963 release/dist, tool/gocross: add fake "windowsdll" GOOS to gocross
We're going to need to build a DLL containing custom actions for the installer.
This patch adds the foundations of that capability to dist and gocross.

Updates https://github.com/tailscale/corp/issues/13998

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
8 months ago
Joe Tsai 5473d11caa
ipn/ipnlocal: perform additional sanity check in diskPath (#9500)
Use filepath.IsLocal to further validate the baseName.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
8 months ago
Val 65dc711c76 control,tailcfg,wgengine/magicsock: add nodeAttr to enable/disable peer MTU
Add a nodeAttr to enable/disable peer path MTU discovery.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 95635857dc wgengine/magicsock: replace CanPMTUD() with ShouldPMTUD()
Replace CanPMTUD() with ShouldPMTUD() to check if peer path MTU discovery should
be enabled, in preparation for adding support for enabling/disabling peer MTU
dynamically.

Updated #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val a5ae21a832 wgengine/magicsock: improve don't fragment bit set/get support
Add an enable/disable argument to setDontFragment() in preparation for dynamic
enable/disable of peer path MTU discovery. Add getDontFragment() to get the
status of the don't fragment bit from a socket.

Updates #311

Co-authored-by: James Tucker <james@tailscale.com>
Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 4c793014af wgengine/magicsock: fix don't fragment setsockopt arg for IPv6 on linux
Use IPV6_MTU_DISCOVER for setting don't fragment on IPv6 sockets on Linux (was
using IP_MTU_DISCOVER, the IPv4 arg).

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val 055f3fd843 wgengine/magicsock: rename debugPMTUD() to debugEnablePMTUD()
Make the debugknob variable name for enabling peer path MTU discovery match the
env variable name.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
Val bb3d338334 wgengine/magicsock: rename files for peer MTU
Rename dontfrag* to peermtu* to prepare for more peer MTU related code going
into these files.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
8 months ago
James Tucker 1c88a77f68 net/dns/publicdns: update Quad9 addresses and references
One Quad9 IPv6 address was incorrect, and an additional group needed
adding. Additionally I checked Cloudflare and included source reference
URLs for both.

Updates #cleanup
Signed-off-by: James Tucker <james@tailscale.com>
8 months ago
Denton Gentry 6e6a510001 go.toolchain.rev: update to Go 1.21.1+
Updates https://github.com/tailscale/tailscale/issues/8419

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
8 months ago
Maisem Ali 4669e7f7d5 cmd/containerboot: add iptables based MSS clamping for ingress/egress proxies
In typical k8s setups, the MTU configured on the eth0 interfaces is typically 1500 which
results in packets being dropped when they make it to proxy pods as the tailscale0 interface
has a 1280 MTU.

As the primary use of this functionality is TCP, add iptables based MSS clamping to allow
connectivity.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Brad Fitzpatrick 546506a54d ipn/ipnlocal: add a test for recent WhoIs regression
This would've prevented #9470.

This used to pass, fails as of 9538e9f970, and passes again
once #9472 is in.

Updates #9470

Change-Id: Iab97666f7a318432fb3b6372a177ab50c55d4697
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
8 months ago
Joe Tsai ae89482f25
ipn/ipnlocal: fix LocalBackend.WhoIs for self (#9472)
9538e9f970 broke LocalBackend.WhoIs
where you can no longer lookup yourself in WhoIs.
This occurs because the LocalBackend.peers map only contains peers.
If we fail to lookup a peer, double-check whether it is ourself.

Fixes #9470

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
8 months ago
Irbe Krumina c5b2a365de
cmd/k8s-operator: fix egress service name (#9494)
Updates https://github.com/tailscale/tailscale/issues/502

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
8 months ago
Maisem Ali 5f4d76c18c cmd/k8s-operator: rename egress annotation
It was tailscale.com/ts-tailnet-target-ip, which was pretty
redundant. Change it to tailscale.com/tailnet-ip.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
8 months ago
Maisem Ali ea9dd8fabc Revert "ipn/ipnlocal: plumb ExitNodeDNSResolvers for IsWireGuardOnly exit nodes"
This reverts commit f6845b10f6.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
James Tucker d52ab181c3 Revert "ipn/ipnlocal: allow Split-DNS and default resolvers with WireGuard nodes"
This reverts commit c7ce4e07e5.

Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
James Tucker c7ce4e07e5 ipn/ipnlocal: allow Split-DNS and default resolvers with WireGuard nodes
The initial implementation directly mirrored the behavior of Tailscale
exit nodes, where the WireGuard exit node DNS took precedence over other
configuration.

This adjusted implementation treats the WireGuard DNS
resolvers as a lower precedence default resolver than the tailnet
default resolver, and allows split DNS configuration as well.

This also adds test coverage to the existing DNS selection behavior with
respect to default resolvers and split DNS routes for Tailscale exit
nodes above cap 25. There may be some refinement to do in the logic in
those cases, as split DNS may not be working as we intend, though that
would be a pre-existing and separate issue.

Updates #9377
Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
Maisem Ali 3056a98bbd net/tstun: add better logging of natV4Config
It might as well have been spewing out gibberish. This adds
a nicer output format for us to be able to read and identify
whats going on.

Sample output
```
natV4Config{nativeAddr: 100.83.114.95, listenAddrs: [10.32.80.33], dstMasqAddrs: [10.32.80.33: 407 peers]}
```

Fixes tailscale/corp#14650

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
David Anderson ed50f360db util/lru: update c.head when deleting the most recently used entry
Fixes tailscale/corp#14747

Signed-off-by: David Anderson <danderson@tailscale.com>
Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
Flakes Updater 4232826cce go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
9 months ago
Will Norris 652f77d236 client/web: switch to using prebuilt web client assets
Updates tailscale/corp#13775

Co-authored-by: Sonia Appasamy <sonia@tailscale.com>
Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Irbe Krumina 35ad2aafe3
Makefile: make it possibe to pass a custom tag when building dev images (#9461)
Updates #cleanup

Signed-off-by: Irbe Krumina <irbe@tailscale.com>
9 months ago
License Updater 1166765559 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
9 months ago
Tom DNetto c08cf2a9c6 all: declare & plumb IPv6 masquerade address for peer
This PR plumbs through awareness of an IPv6 SNAT/masquerade address from the wire protocol
through to the low-level (tstun / wgengine). This PR is the first in two PRs for implementing
IPv6 NAT support to/from peers.

A subsequent PR will implement the data-plane changes to implement IPv6 NAT - this is just plumbing.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates ENG-991
9 months ago
Andrew Dunham d9ae7d670e net/portmapper: add clientmetric for UPnP error codes
This should allow us to gather a bit more information about errors that
we encounter when creating UPnP mappings. Since we don't have a
"LabelMap" construction for clientmetrics, do what sockstats does and
lazily register a new metric when we see a new code.

Updates #9343

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ibb5aadd6138beb58721f98123debcc7273b611ba
9 months ago
Maisem Ali 19a9d9037f tailcfg: add NodeCapMap
Like PeerCapMap, add a field to `tailcfg.Node` which provides
a map of Capability to raw JSON messages which are deferred to be
parsed later by the application code which cares about the specific
capabilities. This effectively allows us to prototype new behavior
without having to commit to a schema in tailcfg, and it also opens up
the possibilities to develop custom behavior in tsnet applications w/o
having to plumb through application specific data in the MapResponse.

Updates #4217

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 4da0689c2c tailcfg: add Node.HasCap helpers
This makes a follow up change less noisy.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali d06b48dd0a tailcfg: add RawMessage
This adds a new RawMessage type backed by string instead of the
json.RawMessage which is backed by []byte. The byte slice makes
the generated views be a lot more defensive than the need to be
which we can get around by using a string instead.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Sonia Appasamy 258f16f84b ipn/ipnlocal: add tailnet MagicDNS name to ipn.LoginProfile
Start backfilling MagicDNS suffixes on LoginProfiles.

Updates #9286

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Brad Fitzpatrick 0d991249e1 types/netmap: remove NetworkMap.{Addresses,MachineStatus}
And convert all callers over to the methods that check SelfNode.

Now we don't have multiple ways to express things in tests (setting
fields on SelfNode vs NetworkMap, sometimes inconsistently) and don't
have multiple ways to check those two fields (often only checking one
or the other).

Updates #9443

Change-Id: I2d7ba1cf6556142d219fae2be6f484f528756e3c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Marwan Sulaiman d25217c9db cmd/tailscale/cli: error when serving foreground if bg already exists
This PR fixes a bug to make sure that we don't allow two configs
exist with duplicate ports

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Brad Fitzpatrick 98b5da47e8 types/views: add SliceContainsFunc like slices.ContainsFunc
Needed for a future change.

Updates #cleanup

Change-Id: I6d89ee8a048b3bb1eb9cfb2e5a53c93aed30b021
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Maisem Ali a61caea911 tailcfg: define a type for NodeCapability
Instead of untyped string, add a type to identify these.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Brad Fitzpatrick 3d37328af6 wgengine, proxymap: split out port mapping from Engine to new type
(Continuing quest to remove rando stuff from the "Engine")

Updates #cleanup

Change-Id: I77f39902c2194410c10c054b545d70c9744250b0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick db2f37d7c6 ipn/ipnlocal: add some test accessors
Updates tailscale/corp#12990

Change-Id: I82801ac4c003d2c7e1352c514adb908dbf01be87
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 9538e9f970 ipn/ipnlocal: keep internal map updated of latest Nodes post mutations
We have some flaky integration tests elsewhere that have no one place
to ask about the state of the world. This makes LocalBackend be that
place (as it's basically there anyway) but doesn't yet add the ForTest
accessor method.

This adds a LocalBackend.peers map[NodeID]NodeView that is
incrementally updated as mutations arrive. And then we start moving
away from using NetMap.Peers at runtime (UpdateStatus no longer uses
it now). And remove another copy of NodeView in the LocalBackend
nodeByAddr map. Change that to point into b.peers instead.

Future changes will then start streaming whole-node-granularity peer
change updates to WatchIPNBus clients, tracking statefully per client
what each has seen. This will get the GUI clients from receiving less
of a JSON storm of updates all the time.

Updates #1909

Change-Id: I14a976ca9f493bdf02ba7e6e05217363dcf422e5
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 926c990a09 types/netmap: start phasing out Addresses, add GetAddresses method
NetworkMap.Addresses is redundant with the SelfNode.Addresses. This
works towards a TODO to delete NetworkMap.Addresses and replace it
with a method.

This is similar to #9389.

Updates #cleanup

Change-Id: Id000509ca5d16bb636401763d41bdb5f38513ba0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick fb5ceb03e3 types/netmap: deprecate NetworkMap.MachineStatus, add accessor method
Step 1 of deleting it, per TODO.

Updates #cleanup

Change-Id: I1d3d0165ae5d8b20610227d60640997b73568733
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 0f3c279b86 ipn/ipnlocal: delete some unused code
Updates #cleanup

Change-Id: I90b46c476f135124d97288e776c2b428b351b8b8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 760b945bc0 ipn/{ipnlocal,ipnstate}: start simplifying UpdateStatus/StatusBuilder
* Remove unnecessary mutexes (there's no concurrency)
* Simplify LocalBackend.UpdateStatus using the StatusBuilder.WantPeers
  field that was added in 0f604923d3, removing passing around some
  method values into func args. And then merge two methods.

More remains, but this is a start.

Updates #9433

Change-Id: Iaf2d7ec6e4e590799f00bae185465a4fd089b822
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
James Tucker 8ab46952d4 net/ping: fix ICMP echo code field to 0
The code was trying to pass the ICMP protocol number here (1), which is
not a valid code. Many servers will not respond to echo messages with
codes other than 0.

https://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml#icmp-parameters-codes-8

Updates #9299
Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
James Tucker f6845b10f6 ipn/ipnlocal: plumb ExitNodeDNSResolvers for IsWireGuardOnly exit nodes
This enables installing default resolvers specified by
tailcfg.Node.ExitNodeDNSResolvers when the exit node is selected.

Updates #9377

Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
James Tucker e7727db553 tailcfg: add DNS address list for IsWireGuardOnly nodes
Tailscale exit nodes provide DNS service over the peer API, however
IsWireGuardOnly nodes do not have a peer API, and instead need client
DNS parameters passed in their node description.

For Mullvad nodes this will contain the in network 10.64.0.1 address.

Updates #9377

Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
Maisem Ali 335a5aaf9a cmd/k8s-operator: add APISERVER_PROXY env
The kube-apiserver proxy in the operator would only run in
auth proxy mode but thats not always desirable. There are
situations where the proxy should just be a transparent
proxy and not inject auth headers, so do that using a new
env var APISERVER_PROXY and deprecate the AUTH_PROXY env.

THe new env var has three options `false`, `true` and `noauth`.

Updates #8317

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
James Tucker 4c693d2ee8 net/dns/publicdns: update Mullvad DoH server list
The following IPs are not used anymore: 193.19.108.2 and 193.19.108.3.
All of the servers are now named consistently under dns.mullvad.net.
Several new servers were added.

https://mullvad.net/en/help/dns-over-https-and-dns-over-tls/

Updates #5416
Updates #9345

Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
Charlotte Brandhorst-Satzkorn 8428a64b56 words: holy mole we need some more mammals
Particularly of the polydactyl kind.

Updates #14698

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
9 months ago
James Tucker 1858ad65c8 cmd/cloner: do not allocate slices when the source is nil
tailcfg.Node zero-value clone equality checks failed when I added a
[]*foo to the structure, as the zero value and it's clone contained a
different slice header.

Updates #9377
Updates #9408
Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
James Tucker 85155ddaf3 tailcfg: remove completed TODO from IsWireGuardOnly
Updates #7826
Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
Tyler Smalley dfefaa5e35 Use parent serve config
Signed-off-by: Tyler Smalley <tyler@tailscale.com>
9 months ago
Marwan Sulaiman f3a5bfb1b9 cmd/tailscale/cli: add set serve validations
This PR adds validations for the new new funnel/serve
commands under the following rules:
1. There is always a single config for one port (bg or fg).
2. Foreground configs under the same port cannot co-exists (for now).
3. Background configs can change as long as the serve type is the same.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Andrew Lytvynov 7ce1c6f981
.github/workflows: fix slack-action format in govulncheck.yml (#9390)
Currently slack messages for errors fail:
https://github.com/tailscale/tailscale/actions/runs/6159104272/job/16713248204

```
Error: Unexpected token
 in JSON at position 151
```

This is likely due to the line break in the text. Restructure the
message to use separate title/text and fix the slack webhook body.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Marwan Sulaiman 3421784e37 cmd/tailscale/cli: use optimistic concurrency control on SetServeConfig
This PR uses the etag/if-match pattern to ensure multiple calls
to SetServeConfig are synchronized. It currently errors out and
asks the user to retry but we can add occ retries as a follow up.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Brad Fitzpatrick 6e66e5beeb cmd/tsconnect/wasm: pass a netmon to ipnserver.New
It became required as of 6e967446e4

Updates #8052

Change-Id: I08d100534254865293c1beca5beff8e529e4e9ac
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 99bb355791 wgengine: remove DiscoKey method from Engine interface
It has one user (LocalBackend) which can ask magicsock itself.

Updates #cleanup

Change-Id: I8c03cbb1e5ba57b0b442621b5fa467030c14a2e2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Will Norris 9843e922b8 README: update docs for building web client
Move into the main "building" section and add the missing `yarn install`
step.

Updates #9312

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Tyler Smalley 82c1dd8732
cmd/tailscale: funnel wip cleanup and additional test coverage (#9316)
General cleanup and additional test coverage of WIP code.

* use enum for serveType
* combine instances of ServeConfig access within unset
* cleanMountPoint rewritten into cleanURLPath as it only handles URL paths
* refactor and test expandProxyTargetDev

> **Note**
> Behind the `TAILSCALE_USE_WIP_CODE` flag

updates #8489

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
9 months ago
Brad Fitzpatrick 3c276d7de2 wgengine: remove SetDERPMap method from Engine interface
(continuing the mission of removing rando methods from the Engine
 interface that we don't need anymore)

Updates #cleanup

Change-Id: Id5190917596bf04d7185c3b331a852724a3f5a16
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 67396d716b ipn/ipnlocal: remove defensiveness around not having a magicsock.Conn
We always have one. Stop pretending we might not.

Instead, add one early panic in NewLocalBackend if we actually don't.

Updates #cleanup

Change-Id: Iba4b78ed22cb6248e59c2b01a79355ca7a200ec8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick b8a4c96c53 wgengine: remove LinkChange method from Engine interface
It was only used by Android, until
https://github.com/tailscale/tailscale-android/pull/131
which does the call to the netMon directly instead.

Updates #cleanup

Change-Id: Iab8a1d8f1e63250705835c75f40e2cd8c1c4d5b8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 727b1432a8 wgengine: remove SetNetInfoCallback method from Engine
LocalBackend can talk to magicsock on its own to do this without
the "Engine" being involved.

(Continuing a little side quest of cleaning up the Engine
interface...)

Updates #cleanup

Change-Id: I8654acdca2b883b1bd557fdc0cfb90cd3a418a62
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Andrew Dunham ad4c11aca1 net/netmon: log when the gateway/self IP changes
This logs that the gateway/self IP address has changed if one of the new
values differs.

Updates #8992

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I0919424b68ad97fbe1204dd36317ed6f5915411f
9 months ago
License Updater 45eafe1b06 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
9 months ago
Brad Fitzpatrick eb9f1db269 cmd/tsconnect/wasm: register netstack.Impl with tsd.System
I missed this in 343c0f1031 and I guess we don't have integration
tests for wasm. But it compiled! :)

Updates #fixup to a #cleanup

Change-Id: If147b90bab254d144ec851a392e8db10ab97f98e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 343c0f1031 wgengine{,/netstack}: remove AddNetworkMapCallback from Engine interface
It had exactly one user: netstack. Just have LocalBackend notify
netstack when here's a new netmap instead, simplifying the bloated
Engine interface that has grown a bunch of non-Engine-y things.
(plenty of rando stuff remains after this, but it's a start)

Updates #cleanup

Change-Id: I45e10ab48119e962fc4967a95167656e35b141d8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
David Crawshaw 47ffbffa97
clientupdate: add root key (#9364)
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
9 months ago
Brad Fitzpatrick 39ade4d0d4 tstest/integration: add start of integration tests for incremental map updates
This adds a new integration test with two nodes where the first gets a
incremental MapResponse (with only PeersRemoved set) saying that the
second node disappeared.

This extends the testcontrol package to support sending raw
MapResponses to nodes.

Updates #1909

Change-Id: Iea0c25c19cf0d72b52dba5a46d01b5cc87b9b39d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 9203916a4a control/controlknobs: move more controlknobs code from controlclient
Updates #cleanup

Change-Id: I2b8b6ac97589270f307bfb20e33674894ce873b5
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 3af051ea27 control/controlclient, types/netmap: start plumbing delta netmap updates
Currently only the top four most popular changes: endpoints, DERP
home, online, and LastSeen.

Updates #1909

Change-Id: I03152da176b2b95232b56acabfb55dcdfaa16b79
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Andrew Lytvynov c0ade132e6
clientupdate: restart tailscale after install on DSM6 (#9363)
DSM6 does not automatically restart packages on install, we have to do
it explicitly.

Also, DSM6 has a filter for publishers in Package Center. Make the error
message more helpful when update fails because of this filter not
allowing our package.

Fixes #9361

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Brad Fitzpatrick 668a0dd5ab cmd/tailscale/cli: fix panic in netcheck print when no DERP home
Fixes #8016

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Andrew Dunham 9ee173c256 net/portmapper: fall back to permanent UPnP leases if necessary
Some routers don't support lease times for UPnP portmapping; let's fall
back to adding a permanent lease in these cases. Additionally, add a
proper end-to-end test case for the UPnP portmapping behaviour.

Updates #9343

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I17dec600b0595a5bfc9b4d530aff6ee3109a8b12
9 months ago
Brad Fitzpatrick 7c1ed38ab3 ipn/ipnlocal: fix missing controlknobs.Knobs plumbing
I missed connecting some controlknobs.Knobs pieces in 4e91cf20a8
resulting in that breaking control knobs entirely.

Whoops.

The fix in ipn/ipnlocal (where it makes a new controlclient) but to
atone, I also added integration tests. Those integration tests use
a new "tailscale debug control-knobs" which by itself might be useful
for future debugging.

Updates #9351

Change-Id: Id9c89c8637746d879d5da67b9ac4e0d2367a3f0d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Marwan Sulaiman 12d4685328 ipn/localapi, ipn/ipnlocal: add etag support for SetServeConfig
This PR adds optimistic concurrency control in the local client and
api in order to ensure multiple writes of the ServeConfig do not
conflict with each other.

Updates #9273

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Brad Fitzpatrick ff6fadddb6 wgengine/magicsock: stop retaining *netmap.NetworkMap
We're trying to start using that monster type less and eventually get
rid of it.

Updates #1909

Change-Id: I8e1e725bce5324fb820a9be6c7952767863e6542
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick f06e64c562 wgengine: use set.HandleSet in another place
I guess we missed this one earlier when we unified the various
copies into set.HandleSet.

Updates #cleanup

Change-Id: I7e6de9ce16e8fc4846abf384dfcc8eaec4d99e60
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 42072683d6 control/controlknobs: move ForceBackgroundSTUN to controlknobs.Knobs
This is both more efficient (because the knobs' bool is only updated
whenever Node is changed, rarely) and also gets us one step closer to
removing a case of storing a netmap.NetworkMap in
magicsock. (eventually we want to phase out much of the use of that
type internally)

Updates #1909

Change-Id: I37e81789f94133175064fdc09984e4f3a431f1a1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 4e91cf20a8 control/controlknobs, all: add plumbed Knobs type, not global variables
Previously two tsnet nodes in the same process couldn't have disjoint
sets of controlknob settings from control as both would overwrite each
other's global variables.

This plumbs a new controlknobs.Knobs type around everywhere and hangs
the knobs sent by control on that instead.

Updates #9351

Change-Id: I75338646d36813ed971b4ffad6f9a8b41ec91560
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick d050700a3b wgengine/magicsock: make peerMap also keyed by NodeID
In prep for incremental netmap update plumbing (#1909), make peerMap
also keyed by NodeID, as all the netmap node mutations passed around
later will be keyed by NodeID.

In the process, also:

* add envknob.InDevMode, as a signal that we can panic more aggressively
  in unexpected cases.
* pull two moderately large blocks of code in Conn.SetNetworkMap out
  into their own methods
* convert a few more sets from maps to set.Set

Updates #1909

Change-Id: I7acdd64452ba58e9d554140ee7a8760f9043f961
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Paul Scott 683ba62f3e
cmd/testwrapper: fix exit deflake (#9342)
Sometimes `go test` would exit and close its stdout before we started reading
it, and we would return that "file closed" error then forget to os.Exit(1).
Fixed to prefer the go test subprocess error and exit regardless of the type of
error.

Fixes #9334

Signed-off-by: Paul Scott <paul@tailscale.com>
9 months ago
Brad Fitzpatrick 0396366aae cmd/testwrapper/flakytest: don't spam stderr in Mark when not under wrapper
If the user's running "go test" by hand, no need to spam stderr with
the sentinel marker. It already calls t.Logf (which only gets output
on actual failure, or verbose mode) which is enough to tell users it's
known flaky. Stderr OTOH always prints out and is distracting to
manual "go test" users.

Updates #cleanup

Change-Id: Ie5e6881bae291787c30f75924fa132f4a28abbb2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 70ea073478 tailcfg: flesh out some docs on MapResponse, clarify slices w/ omitempty
Updates #cleanup

Change-Id: If4caf9d00529edc09ae7af9cc70f6ba0ade38378
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick a5ffd5e7c3 tailcfg: remove unused MapRequest.IncludeIPv6 field
It's been implicitly enabled (based on capver) for years.

Updates #cleanup

Change-Id: I8ff1ab844f9ed75c97e866e778dfc0b56cfa98a2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 9a86aa5732 all: depend on zstd unconditionally, remove plumbing to make it optional
All platforms use it at this point, including iOS which was the
original hold out for memory reasons. No more reason to make it
optional.

Updates #9332

Change-Id: I743fbc2f370921a852fbcebf4eb9821e2bdd3086
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Marwan Sulaiman f12c71e71c cmd/tailscale: reduce duplicate calls to LocalBackend
This PR ensures calls to the LocalBackend are not happening
multiples times and ensures the set/unset methods are
only manipulating the serve config

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Brad Fitzpatrick dc7aa98b76 all: use set.Set consistently instead of map[T]struct{}
I didn't clean up the more idiomatic map[T]bool with true values, at
least yet.  I just converted the relatively awkward struct{}-valued
maps.

Updates #cleanup

Change-Id: I758abebd2bb1f64bc7a9d0f25c32298f4679c14f
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick d506a55c8a ipn/ipnstate: address TODO about garbage during peer sorting
Updates #cleanup

Change-Id: I34938bca70a95571cc62ce1f76eaab5db8c2c3ef
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 60e9bd6047 ipn/ipnstate: add some missing docs
Updates #cleanup

Change-Id: I689f8124a5986a98b8eb3891727d39c96408f0a7
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick db307d35e1 types/netmap: delete a copy of views.SliceEqual
Updates #cleanup

Change-Id: Ibdfa6c5dc9211f5c97c763ba323802a1c1d80c9e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
David Anderson 95082a8dde util/lru, util/limiter: add debug helper to dump state as HTML
For use in tsweb debug handlers, so that we can easily inspect cache
and limiter state when troubleshooting.

Updates tailscale/corp#3601

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
Andrew Lytvynov d23b8ffb13
cmd/tailscale/cli,ipn: mention available update in "tailscale status" (#9205)
Cache the last `ClientVersion` value that was received from coordination
server and pass it in the localapi `/status` response.
When running `tailscale status`, print a message if `RunningAsLatest` is
`false`.

Updates #6907

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Andrew Lytvynov 1073b56e18
ipn/ipnlocal: add logging and locking to c2n /update (#9290)
Log some progress info to make updates more debuggable. Also, track
whether an active update is already started and return an error if
a concurrent update is attempted.

Some planned future PRs:
* add JSON output to `tailscale update`
* use JSON output from `tailscale update` to provide a more detailed
  status of in-progress update (stage, download progress, etc)

Updates #6907

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Sonia Appasamy 1eadb2b608 client/web: clean up assets handling
A #cleanup that moves all frontend asset handling into assets.go
(formerly dev.go), and stores a single assetsHandler field back
to web.Server that manages when to serve the dev vite proxy versus
static files itself.

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
License Updater 4a38d8d372 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
9 months ago
License Updater 0dc65b2e47 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
9 months ago
License Updater 1383fc57ad licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
9 months ago
Joe Tsai 0a0adb68ad
ssh/tailssh: log when recording starts and finishes (#9294)
Updates tailscale/corp#14579

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
9 months ago
Marwan Sulaiman a1d4144b18 cmd/tailscale: combine foreground and background serve logic
Previously, foreground mode only worked in the simple case of `tailscale funnel <port>`.
This PR ensures that whatever you can do in the background can also be
done in the foreground such as setting mount paths or tcp forwarding.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Craig Rodrigues 8452d273e3 util/linuxfw: Fix comment which lists supported linux arches
Only arm64 and amd64 are supported

Signed-off-by: Craig Rodrigues <rodrigc@crodrigues.org>
9 months ago
David Anderson 0909e90890 util/lru: replace container/list with a custom ring implementation
pre-generics container/list is quite unpleasant to use, and the pointer
manipulation operations for an LRU are simple enough to implement directly
now that we have generic types.

With this change, the LRU uses a ring (aka circularly linked list) rather
than a simple doubly-linked list as its internals, because the ring makes
list manipulation edge cases more regular: the only remaining edge case is
the transition between 0 and 1 elements, rather than also having to deal
specially with manipulating the first and last members of the list.

While the primary purpose was improved readability of the code, as it
turns out removing the indirection through an interface box also speeds
up the LRU:

       │ before.txt  │              after.txt              │
       │   sec/op    │   sec/op     vs base                │
LRU-32   67.05n ± 2%   59.73n ± 2%  -10.90% (p=0.000 n=20)

       │ before.txt │             after.txt              │
       │    B/op    │    B/op     vs base                │
LRU-32   21.00 ± 0%   10.00 ± 0%  -52.38% (p=0.000 n=20)

       │ before.txt │           after.txt            │
       │ allocs/op  │ allocs/op   vs base            │
LRU-32   0.000 ± 0%   0.000 ± 0%  ~ (p=1.000 n=20) ¹

Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
David Anderson 472eb6f6f5 util/lru: add a microbenchmark
The benchmark simulates an LRU being queries with uniformly random
inputs, in a set that's too large for the LRU, which should stress
the eviction codepath.

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
Maisem Ali 18b2638b07 metrics: add missing comma in histogram JSON export
Updates tailscale/corp#8641

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Tyler Smalley 70a9854b39
cmd/tailscale: add background mode to serve/funnel wip (#9202)
> **Note**
> Behind the `TAILSCALE_FUNNEL_DEV` flag

* Expose additional listeners through flags
* Add a --bg flag to run in the background
* --set-path to set a path for a specific target (assumes running in background)

See the parent issue for more context.

Updates #8489

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
9 months ago
Maisem Ali 5ee349e075 tsweb/varz: fix exporting histograms
Updates tailscale/corp#8641

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Brad Fitzpatrick 1bd3edbb46 release/dist/unixpkgs: demote deb iptables+iproute2 packages to recommended
Fixes #9236

Change-Id: Idbad2edb0262ef842afd6b40ae47f46e685b112d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Marwan Sulaiman 50990f8931 ipn, ipn/ipnlocal: add Foreground field for ServeConfig
This PR adds a new field to the serve config that can be used to identify which serves are in "foreground mode" and then can also be used to ensure they do not get persisted to disk so that if Tailscaled gets ungracefully shutdown, the reloaded ServeConfig will not have those ports opened.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Paul Scott 96094cc07e
cmd/testwrapper: exit code 1 when go build fails (#9276)
Fixes #9275
Fixes #8586
Fixes tailscale/corp#13115

Signed-off-by: Paul Scott <paul@tailscale.com>
9 months ago
Skip Tavakkolian 6fd1961cd7 safesocket, paths: add Plan 9 support
Updates #5794

Change-Id: I69150ec18d101f55baabb38613512cde858447cb
Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: Skip Tavakkolian <skip.tavakkolian@gmail.com>
9 months ago
Marwan Sulaiman 51d3220153 ipn, ipn/ipnlocal: remove log streaming for StreamServe
This PR removes the per request logging to the CLI as the CLI
will not be displaying those logs initially.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
David Anderson 96c2cd2ada util/limiter: add a keyed token bucket rate limiter
Updates tailscale/corp#3601

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
Maisem Ali c2241248c8 tstest: relax ResourceCheck to 3s
It was only waiting for 0.5s (5ms * 100), but our CI
is too slow so make it wait up to 3s (10ms * 300).

Updates tailscale/corp#14515

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Chris Palmer ac7b4d62fd
cmd/tailscale/cli: make update visible in list (#8662)
This also makes "HIDDEN: " work (requires the custom UsageFunc).

Updates #6995

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
9 months ago
Andrew Dunham d413dd7ee5 net/dns/publicdns: add support for Wikimedia DNS
RELNOTE=Adds support for Wikimedia DNS

Updates #9255

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I4213c29e0f91ea5aa0304a5a026c32b6690fead9
9 months ago
Andrea Barisani d61494db68 adjust build tags for tamago
Signed-off-by: Andrea Barisani <andrea@inversepath.com>
9 months ago
Paul Scott 9a56184bef
cmd/tailscale: Check App Store tailscaled dialable before selecting. (#9234)
PR #9217 attempted to fix the same issue, but suffered from not letting the
user connect to non-oss tailscaled if something was listening on the socket, as
the --socket flag doesn't let you select the mac apps.

Rather than leave the user unable to choose, we keep the mac/socket preference
order the same and check a bit harder whether the macsys version really is
running. Now, we prefer the App Store Tailscale (even if it's Stopped) and you
can use --socket to sswitch. But if you quit the App Store Tailscale, we'll try
the socket without needing the flag.

Fixes #5761
Signed-off-by: Paul Scott <408401+icio@users.noreply.github.com>
9 months ago
Anton Tolchanov 86b0fc5295 util/cmpver: add a few tests covering different OS versions
Updates tailscale/corp#14491

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
9 months ago
Aaron Klotz 7686ff6c46 Update clientupdate/distsign/distsign_test.go
Co-authored-by: Andrew Lytvynov <awly@tailscale.com>
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
9 months ago
Aaron Klotz 7d60c19d7d clientupdate/distsign: add ability to validate a binary that is already located on disk
Our build system caches files locally and only updates them when something
changes. Since I need to integrate some distsign stuff into the build system
to validate our Windows 7 MSIs, I want to be able to check the cached copy
of a package before downloading a fresh copy from pkgs.

If the signature changes, then obviously the local copy is outdated and we
return an error, at which point we call Download to refresh the package.

Updates https://github.com/tailscale/corp/issues/14334

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
9 months ago
Maisem Ali f6a203fe23 control/controlclient: check c.closed in waitUnpause
We would only check if the client was paused, but not
if the client was closed. This meant that a call to
Shutdown may block forever/leak goroutines

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Marwan Sulaiman 45eeef244e ipn, ipn/ipnlocal: add Foreground field to ServeConfig
This PR adds a new field to the ServeConfig which maps
WatchIPNBus session ids to foreground serve configs.

The PR also adds a DeleteForegroundSession method to ensure the config
gets cleaned up on sessions ending.

Note this field is not currently used but will be in follow up work.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Maisem Ali cb3b281e98 ipn/ipnlocal: fix race in enterState
It would acquire the lock, calculate `nextState`, relase
the lock, then call `enterState` which would acquire the lock
again. There were obvious races there which could lead to
nil panics as seen in a test in a different repo.

```
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x70 pc=0x1050f2c7c]

goroutine 42240 [running]:
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterStateLockedOnEntry(0x14002154e00, 0x6)
        tailscale.com/ipn/ipnlocal/local.go:3715 +0x30c
tailscale.com/ipn/ipnlocal.(*LocalBackend).enterState(0x14002154e00?, 0x14002e3a140?)
        tailscale.com/ipn/ipnlocal/local.go:3663 +0x8c
tailscale.com/ipn/ipnlocal.(*LocalBackend).stateMachine(0x14001f5e280?)
        tailscale.com/ipn/ipnlocal/local.go:3836 +0x2c
tailscale.com/ipn/ipnlocal.(*LocalBackend).setWgengineStatus(0x14002154e00, 0x14002e3a190, {0x0?, 0x0?})
        tailscale.com/ipn/ipnlocal/local.go:1193 +0x4d0
tailscale.com/wgengine.(*userspaceEngine).RequestStatus(0x14005d90300)
        tailscale.com/wgengine/userspace.go:1051 +0x80
tailscale.com/wgengine.NewUserspaceEngine.func2({0x14002e3a0a0, 0x2, 0x140025cce40?})
        tailscale.com/wgengine/userspace.go:318 +0x1a0
tailscale.com/wgengine/magicsock.(*Conn).updateEndpoints(0x14002154700, {0x105c13eaf, 0xf})
        tailscale.com/wgengine/magicsock/magicsock.go:531 +0x424
created by tailscale.com/wgengine/magicsock.(*Conn).ReSTUN in goroutine 42077
        tailscale.com/wgengine/magicsock/magicsock.go:2142 +0x3a4
```

Updates tailscale/corp#14480

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Marwan Sulaiman a4aa6507fa ipn, ipn/ipnlocal: add session identifier for WatchIPNBus
This PR adds a SessionID field to the ipn.Notify struct so that
ipn buses can identify a session and register deferred clean up
code in the future. The first use case this is for is to be able to
tie foreground serve configs to a specific watch session and ensure
its clean up when a connection is closed.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Brad Fitzpatrick 7175f06e62 util/rands: add package with HexString func
We use it a number of places in different repos. Might as well make
one. Another use is coming.

Updates #cleanup

Change-Id: Ib7ce38de0db35af998171edee81ca875102349a4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Sonia Appasamy f824274093 cli/serve: shorten help text on error
Our BETA serve help text is long and often hides the actual error
in the user's usage. Instead of printing the full text, prompt
users to use `serve --help` if they want the help info.

Fixes #14274

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Maisem Ali 3280c81c95 .github,cmd/gitops-pusher: update to checkout@v4
checkout@v3 is broken:
actions/checkout#1448

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 0f397baf77 cmd/testwrapper: emit logs of failed tests on timeout
It would just fail the entire pkg, but would not print any
logs. It was already tracking all the logs, so have it emit
them when the pkg fails/times out.

Updates #9231

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 52a19b5970 ipn/ipnlocal: prevent cc leaks on multiple Start calls
If Start was called multiple times concurrently, it would
create a new client and shutdown the previous one. However
there was a race possible between shutting down the old one
and assigning a new one where the concurent goroutine may
have assigned another one already and it would leak.

Updates tailscale/corp#14471

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 6bc15f3a73 ipn/ipnlocal: fix startIsNoopLocked
It got broken back when FUS was introduced, but we
never caught it.

Updates tailscale/corp#14471

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Brad Fitzpatrick 1262df0578 net/netmon, net/tsdial: add some link change metrics
Updates #9040

Change-Id: I2c87572d79d2118bcf1f0122eccfe712c1bea9d5
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Craig Rodrigues 8683ce78c2 client/web, clientupdate, util/linuxfw, wgengine/magicsock: Use %v verb for errors
Replace %w verb with %v verb when logging errors.
Use %w only for wrapping errors with fmt.Errorf()

Fixes: #9213

Signed-off-by: Craig Rodrigues <rodrigc@crodrigues.org>
9 months ago
Maisem Ali d06a75dcd0 ipn/ipnlocal: fix deadlock in resetControlClientLocked
resetControlClientLocked is called while b.mu was held and
would call cc.Shutdown which would wait for the observer queue
to drain.
However, there may be active callbacks from cc already waiting for
b.mu resulting in a deadlock.

This makes it so that resetControlClientLocked does not call
Shutdown, and instead just returns the value.
It also makes it so that any status received from previous cc
are ignored.

Updates tailscale/corp#12827

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Joe Tsai c6fadd6d71
all: implement AppendText alongside MarshalText (#9207)
This eventually allows encoding packages that may respect
the proposed encoding.TextAppender interface.
The performance gains from this is between 10-30%.

Updates tailscale/corp#14379

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
9 months ago
Will Norris 9a3bc9049c client/web,cmd/tailscale: add prefix flag for web command
We already had a path on the web client server struct, but hadn't
plumbed it through to the CLI. Add that now and use it for Synology and
QNAP instead of hard-coding the path. (Adding flag for QNAP is
tailscale/tailscale-qpkg#112) This will allow supporting other
environments (like unraid) without additional changes to the client/web
package.

Also fix a small bug in unraid handling to only include the csrf token
on POST requests.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Andrew Lytvynov 34e3450734
cmd/tailscale,ipn: add auto-update flags and prefs (#8861)
The flags are hidden for now. Adding propagation to tailscaled and
persistence only. The prefs field is wrapped in a struct to allow for
future expansion (like update schedule).

Updates #6907

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Brad Fitzpatrick 055fdb235f cmd/tailscaled, tstest/integration: make tailscaled die when parent dies
I noticed that failed tests were leaving aroudn stray tailscaled processes
on macOS at least.

To repro, add this to tstest/integration:

    func TestFailInFewSeconds(t *testing.T) {
        t.Parallel()
        time.Sleep(3 * time.Second)
        os.Exit(1)
        t.Fatal("boom")
    }

Those three seconds let the other parallel tests (with all their
tailscaled child processes) start up and start running their tests,
but then we violently os.Exit(1) the test driver and all the children
were kept alive (and were spinning away, using all available CPU in
gvisor scheduler code, which is a separate scary issue)

Updates #cleanup

Change-Id: I9c891ed1a1ec639fb2afec2808c04dbb8a460e0e
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Tyler Smalley e1fbb5457b
cmd/tailscale: combine serve and funnel for debug wip funnel stream model (#9169)
> **Note**
> Behind the `TAILSCALE_USE_WIP_CODE` flag

In preparing for incoming CLI changes, this PR merges the code path for the `serve` and `funnel` subcommands.

See the parent issue for more context.

The following commands will run in foreground mode when using the environment flag.
```
tailscale serve localhost:3000
tailscae funnel localhost:3000
```

Replaces #9134
Updates #8489

Signed-off-by: Tyler Smalley <tyler@tailscale.com>
Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
Co-authored-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Brad Fitzpatrick 003e4aff71 control/controlclient: clean up various things in prep for state overhaul
We want the overall state (used only for tests) to be computed from
the individual states of each component, rather than moving the state
around by hand in dozens of places.

In working towards that, we found a lot of things to clean up.

Updates #cleanup

Change-Id: Ieaaae5355dfae789a8ec7a56ce212f1d7e3a92db
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 0c1e3ff625 ipn/ipnlocal: avoid calling Start from resetForProfileChangeLockedOnEntry
During Shutdown of an ephemeral node, we called Logout (to best effort
delete the node earlier), which then called back into
resetForProfileChangeLockedOnEntry, which then tried to Start
again. That's all a waste of work during shutdown and complicates
other cleanups coming later.

Updates #cleanup

Change-Id: I0b8648cac492fc70fa97c4ebef919bbe352c5d7b
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 9cbec4519b control/controlclient: serialize Observer calls
Don't just start goroutines and hope for them to be ordered.

Fixes potential regression from earlier 7074a40c0.

Updates #cleanup

Change-Id: I501a6f3e4e8e6306b958bccdc1e47869991c31f7
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 8b3ea13af0 net/tsdial: be smarter about when to close SystemDial conns
It was too aggressive before, as it only had the ill-defined "Major"
bool to work with. Now it can check more precisely.

Updates #9040

Change-Id: I20967283b64af6a9cad3f8e90cff406de91653b8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick f7b7ccf835 control/controlclient, ipn/ipnlocal: unplumb a bool true literal opt
Updates #cleanup

Change-Id: I664f280a2e06b9875942458afcaf6be42a5e462a
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 346445acdd .github/workflows: only run bench all on packages with benchmarks
Drops time by several minutes.

Also, on top of that: skip building variant CLIs on the race builder
(29s), and getting qemu (15s).

Updates #9182

Change-Id: I979e02ab8c0daeebf5200459c9e4458a1f62f728
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Maisem Ali 96277b63ff ipn/ipnlocal: rename LogoutSync to Logout
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali f52273767f ipn/ipnlocal: fix missing mutex usage for profileManager
It required holding b.mu but was documented incorrectly, fix.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 959362a1f4 ipn/ipnlocal,control/controlclient: make Logout more sync
We already removed the async API, make it more sync and remove
the FinishLogout state too.

This also makes the callback be synchronous again as the previous
attempt was trying to work around the logout callback resulting
in a client shutdown getting blocked forever.

Updates #3833

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 1f12b3aedc .github: do not use testwrapper for benchmarks
Updates #9182

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 7074a40c06 control/controlclient: run SetControlClientStatus in goroutine
We have cases where the SetControlClientStatus would result in
a Shutdown call back into the auto client that would block
forever. The right thing to do here is to fix the LocalBackend
state machine but thats a different dumpster fire that we
are slowly making progress towards.

This makes it so that the SetControlClientStatus happens in a
different goroutine so that calls back into the auto client
do not block.

Also add a few missing mu.Unlocks in LocalBackend.Start.

Updates #9181

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Brad Fitzpatrick 86dc0af5ae control/controlclient: rename Auto cancel methods, add missing Lock variant
Then use the Locked variants in Shutdown while we already hold the lock.

Updates #cleanup

Change-Id: I367d53e6be6f37f783c8f43fc9c4d498d0adf501
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 61ae16cb6f ipn/ipnlocal: add missing mutex unlock in error path
Found while debugging something else.

Updates #cleanup

Change-Id: I73fe55da14bcc3b1ffc39e2dbc0d077bc7f70cf1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 47cf836720 tsnet: remove redundant ephemeral logout on close
LocalBackend.Shutdown already does it.

Updates #cleanup

Change-Id: Ie5dd7d8e5d9e69644f211ee1de6c790f57f5ae25
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 21247f766f ipn/ipnlocal: deflake some tests
* don't try to re-Start (and thus create a new client) during Shutdown
* in tests, wait for controlclient to fully shut down when replacing it
* log a bit more

Updates tailscale/corp#14139
Updates tailscale/corp#13175 etc
Updates #9178 and its flakes.

Change-Id: I3ed2440644dc157aa6e616fe36fbd29a6056846c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 04e1ce0034 control/controlclient: remove unused StartLogout
Updates #cleanup

Co-authored-by: Maisem Ali <maisem@tailscale.com>
Change-Id: I9d052fdbee787f1e8c872124e4bee61c7f04d142
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick ecc1d6907b types/logger: add TestLogger
We have this in another repo and I wanted it here too.

Updates #cleanup

Change-Id: If93dc73f11eaaada5024acf2a885a153b88db5a0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Flakes Updater 77060c4d89 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
9 months ago
Andrew Lytvynov 4e72992900
clientupdate: add linux tarball updates (#9144)
As a fallback to package managers, allow updating tailscale that was
self-installed in some way. There are some tricky bits around updating
the systemd unit (should we stick to local binary paths or to the ones
in tailscaled.service?), so leaving that out for now.

Updates #6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Chris Palmer ce1e02096a
ipn/ipnlocal: support most Linuxes in handleC2NUpdate (#9114)
* ipn/ipnlocal: support most Linuxes in handleC2NUpdate

Updates #6995

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
9 months ago
Brad Fitzpatrick c621141746 control/controlclient: cancel map poll when logging out
Don't depend on the server to do it.

Updates #cleanup

Change-Id: I8ff40b02aa877155a71fd4db58cbecb872241ac8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 313a129fe5 control/controlclient: use slices package more
Updates #cleanup

Change-Id: Ic17384266dc59bc4e710efdda311d6e0719529da
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Will Norris 37eab31f68 client/web: simply csrf key caching in cgi mode
Instead of trying to use the user config dir, and then fail back to the
OS temp dir, just always use the temp dir. Also use a filename that is
less likely to cause collisions.

This addresses an issue on a test synology instance that was
mysteriously failing because there was a file at /tmp/tailscale. We
could still technically run into this issue if a
/tmp/tailscale-web-csrf.key file exists, but that seems far less likely.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Brad Fitzpatrick f5bfdefa00 control/controlclient: de-pointer Status.PersistView, document more
Updates #cleanup
Updates #1909

Change-Id: I31d91e120e3b299508de2136021eab3b34131a44
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 7053e19562 control/controlclient: delete Status.Log{in,out}Finished
They were entirely redundant and 1:1 with the status field
so this turns them into methods instead.

Updates #cleanup
Updates #1909

Change-Id: I7d939750749edf7dae4c97566bbeb99f2f75adbc
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Maisem Ali 794650fe50 cmd/k8s-operator: emit event if HTTPS is disabled on Tailnet
Instead of confusing users, emit an event that explicitly tells the
user that HTTPS is disabled on the tailnet and that ingress may not
work until they enable it.

Updates #9141

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Denton Gentry be9914f714 cmd/sniproxy: move default debug-port away from 8080.
Port 8080 is routinely used for HTTP services, make it easier to
use --forwards=tcp/8080/... by moving the metrics port out of the
way.

Updates #1748

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
9 months ago
Brad Fitzpatrick 9ce1f5c7d2 control/controlclient: unexport Status.state, add test-only accessor
Updates #cleanup
Updates #1909

Change-Id: I38dcde6fa0de0f58ede4529992cee2e36de33dd6
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Maisem Ali 306b85b9a3 cmd/k8s-operator: add metrics to track usage
Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Andrea Barisani 0a74d46568 adjust build tags for tamago
Signed-off-by: Andrea Barisani <andrea@inversepath.com>
9 months ago
Brad Fitzpatrick 14320290c3 control/controlclient: merge, simplify two health check calls
I'm trying to remove some stuff from the netmap update path.

Updates #1909

Change-Id: Iad2c728dda160cd52f33ef9cf0b75b4940e0ce64
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Irbe Krumina 17438a98c0
cm/k8s-operator,cmd/containerboot: fix STS config, more tests (#9155)
Ensures that Statefulset reconciler config has only one of Cluster target IP or tailnet target IP.
Adds a test case for containerboot egress proxy mode.

Updates tailscale/tailscale#8184

Signed-off-by: irbekrm <irbekrm@gmail.com>
9 months ago
Denton Gentry 29a35d4a5d cmd/sniproxy: switch to peterbourgon/ff for flags
Add support for TS_APPC_* variables to supply arguments by
switching to https://github.com/peterbourgon/ff for CLI
flag parsing. For example:
TS_APPC_FORWARDS=tcp/22/github.com ./sniproxy

Updates https://github.com/tailscale/tailscale/issues/1748

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
9 months ago
Irbe Krumina fe709c81e5
cmd/k8s-operator,cmd/containerboot: add kube egress proxy (#9031)
First part of work for the functionality that allows users to create an egress
proxy to access Tailnet services from within Kubernetes cluster workloads.
This PR allows creating an egress proxy that can access Tailscale services over HTTP only.

Updates tailscale/tailscale#8184

Signed-off-by: irbekrm <irbekrm@gmail.com>
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
9 months ago
Maisem Ali ae747a2e48 cmd/testwrapper: handle timeouts as test failures
While investigating the fix in 7538f38671,
I was curious why the testwrapper didn't fail. Turns out if the test
times out and there was no explicit failure, the only message we get
is that the overall pkg failed and no failure information about the
individual test. This resulted in a 0 exit code.

This fixes that by failing the explicit case of the pkg failing when
there is nothing to retry for that pkg.

Updates #8493

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali b90b9b4653 client/web: fix data race
Fixes #9150

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 7538f38671 cmd/containerboot: fix broken tests
The tests were broken in a61a9ab087, maybe
even earlier.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Andrew Lytvynov abfe5d3879
clientupdate: detect when tailscale is installed without package manager (#9137)
On linux users can install Tailscale via package managers or direct
tarball downloads. Detect when Tailscale is not installed via a package
manager so we can pick the correct update mechanism. Leave the tarball
update function unimplemented for now (coming in next PR!).

Updates #6995
Updates #8760

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
David Anderson 8b492b4121 net/wsconn: accept a remote addr string and plumb it through
This makes wsconn.Conns somewhat present reasonably when they are
the client of an http.Request, rather than just put a placeholder
in that field.

Updates tailscale/corp#13777

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
Sonia Appasamy e952564b59 client/web: pipe unraid csrf token through apiFetch
Ensures that we're sending back the csrf token for all requests
made back to unraid clients.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Sonia Appasamy 1cd03bc0a1 client/web: remove self node on server
This is unused. Can be added back if needed in the future.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Sonia Appasamy da6eb076aa client/web: add localapi proxy
Adds proxy to the localapi from /api/local/ web client endpoint.
The localapi proxy is restricted to an allowlist of those actually
used by the web client frontend.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Maisem Ali c919ff540f cmd/k8s-operator,ipn/store/kubestore: patch secrets instead of updating
We would call Update on the secret, but that was racey and would occasionaly
fail. Instead use patch whenever we can.

Fixes errors like
```
boot: 2023/08/29 01:03:53 failed to set serve config: sending serve config: updating config: writing ServeConfig to StateStore: Operation cannot be fulfilled on secrets "ts-webdav-kfrzv-0": the object has been modified; please apply your changes to the latest version and try again

{"level":"error","ts":"2023-08-29T01:03:48Z","msg":"Reconciler error","controller":"ingress","controllerGroup":"networking.k8s.io","controllerKind":"Ingress","Ingress":{"name":"webdav","namespace":"default"},"namespace":"default","name":"webdav","reconcileID":"96f5cfed-7782-4834-9b75-b0950fd563ed","error":"failed to provision: failed to create or get API key secret: Operation cannot be fulfilled on secrets \"ts-webdav-kfrzv-0\": the object has been modified; please apply your changes to the latest version and try again","stacktrace":"sigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller).reconcileHandler\n\tsigs.k8s.io/controller-runtime@v0.15.0/pkg/internal/controller/controller.go:324\nsigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller).processNextWorkItem\n\tsigs.k8s.io/controller-runtime@v0.15.0/pkg/internal/controller/controller.go:265\nsigs.k8s.io/controller-runtime/pkg/internal/controller.(*Controller).Start.func2.2\n\tsigs.k8s.io/controller-runtime@v0.15.0/pkg/internal/controller/controller.go:226"}
```

Updates #502
Updates #7895

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Joe Tsai 930e6f68f2
types/opt: use switch in Bool.UnmarshalJSON (#9140)
The compiler does indeed perform this optimization.

Updates #cleanup

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
9 months ago
Brad Fitzpatrick 11ece02f52 net/{interfaces,netmon}: remove "interesting", EqualFiltered API
This removes a lot of API from net/interfaces (including all the
filter types, EqualFiltered, active Tailscale interface func, etc) and
moves the "major" change detection to net/netmon which knows more
about the world and the previous/new states.

Updates #9040

Change-Id: I7fe66a23039c6347ae5458745b709e7ebdcce245
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 6dfa403e6b cmd/tailscaled: default to userspace-networking on plan9
No tun support yet.

Updates #5794

Change-Id: Ibd8db67594d4c65b47e352ae2af2ab3d2712dfad
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Sonia Appasamy 7aea219a0f client/web: pull SynoToken logic into apiFetch
Updates tailscale/corp#13775
9 months ago
Brad Fitzpatrick 6b882a1511 control/controlclient: clean up a few little things
De-pointer a *time.Time type, move it after the mutex which guard is,
rename two test-only methods with our conventional "ForTest" suffix.

Updates #cleanup

Change-Id: I4f4d1acd9c2de33d9c3cb6465d7349ed051aa9f9
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 3bce9632d9 derp/derphttp: fix data race and crash in proxy dial error path
Named result meant error paths assigned that variable to nil.
But a goroutine was concurrently using that variable.

Don't use a named result for that first parameter. Then then return
paths don't overwrite it.

Fixes #9129

Change-Id: Ie57f99d40ca8110085097780686d9bd620aaf160
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Val 8ba07aac85 ipn/iplocale: remove unused argument to shouldUseOneCGNATRoute
Remove an unused argument to shouldUseOneCGNATRoute.

Updates #cleanup

Signed-off-by: Val <valerie@tailscale.com>
9 months ago
Brad Fitzpatrick 55bb7314f2 control/controlclient: replace a status func with Observer interface
For now the method has only one interface (the same as the func it's
replacing) but it will grow, eventually with the goal to remove the
controlclient.Status type for most purposes.

Updates #1909

Change-Id: I715c8bf95e3f5943055a94e76af98d988558a2f2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick a64593d7ef types/logger: fix test failure I missed earlier
I didn't see the race builder fail on CI earlier in 590c693b9.
This fixes the test.

Updates #greenci

Change-Id: I9f271bfadfc29b010226b55bf6647f35f03730b1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 590c693b96 types/logger: add AsJSON
Printing out JSON representation things in log output is pretty common.

Updates #cleanup

Change-Id: Ife2d2e321a18e6e1185efa8b699a23061ac5e5a4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick a79b1d23b8 control/controlclient: convert PeersChanged nodes to patches internally
So even if the server doesn't support sending patches (neither the
Tailscale control server nor Headscale yet do), this makes the client
convert a changed node to its diff so the diffs can be processed
individually in a follow-up change.

This lets us make progress on #1909 without adding a dependency on
finishing the server-side part, and also means other control servers
will get the same upcoming optimizations.

And add some clientmetrics while here.

Updates #1909

Change-Id: I9533bcb8bba5227e17389f0b10dff71f33ee54ec
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Andrew Lytvynov 67e48d9285
clientupdate: use SPKsVersion instead of Version (#9118)
Top-level Version in pkgs response is not always in sync with SPK
versions, especially on unstable track. It's very confusing when the
confirmation prompt asks you "update to 1.49.x?" and you end up updating
to 1.49.y.
Instead, grab the SPK-specific version field.

Updates #cleanup.

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Andrew Lytvynov 8d2eaa1956
clientupdate: download SPK and MSI packages with distsign (#9115)
Reimplement `downloadURLToFile` using `distsign.Download` and move all
of the progress reporting logic over there.

Updates #6995
Updates #755

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Maisem Ali 0c6fe94cf4 cmd/k8s-operator: add matching family addresses to status
This was added in 3451b89e5f, but
resulted in the v6 Tailscale address being added to status when
when the forwarding only happened on the v4 address.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali f92e6a1be8 cmd/k8s-operator: update RBAC to allow creating events
The new ingress reconcile raises events on failure, but I forgot to
add the updated permission.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Joe Tsai fcbb2bf348
net/memnet: export the network name (#9111)
This makes it more maintainable for other code to statically depend
on the exact value of this string. It also makes it easier to
identify what code might depend on this string by looking up
references to this constant.

Updates tailscale/corp#13777

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
9 months ago
Chris Palmer 346dc5f37e
ipn/ipnlocal: move C2NUpdateResponse to c2ntypes.go (#9112)
Updates #cleanup

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
9 months ago
Will Norris d74c771fda client/web: always use new web client; remove old client
This uses the new react-based web client for all builds, not just with
the --dev flag.

If the web client assets have not been built, the client will serve a
message that Tailscale was built without the web client, and link to
build instructions. Because we will include the web client in all of our
builds, this should only be seen by developers or users building from
source. (And eventually this will be replaced by attempting to download
needed assets as runtime.)

We do now checkin the build/index.html file, which serves the error
message when assets are unavailable.  This will also eventually be used
to trigger in CI when new assets should be built and uploaded to a
well-known location.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Will Norris be5bd1e619 client/web: skip authorization checks for static assets
Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Andrew Lytvynov 18d9c92342
release/dist/cli: add verify-package-signature command (#9110)
Helper command to verify package signatures, mainly for debugging.
Also fix a copy-paste mistake in error message in distsign.

Updates #8760

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Andrew Dunham c86a610eb3 cmd/tailscale, net/portmapper: add --log-http option to "debug portmap"
This option allows logging the raw HTTP requests and responses that the
portmapper Client makes when using UPnP. This can be extremely helpful
when debugging strange UPnP issues with users' devices, and might allow
us to avoid having to instruct users to perform a packet capture.

Updates #8992

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I2c3cf6930b09717028deaff31738484cc9b008e4
9 months ago
Mike Beaumont 3451b89e5f cmd/k8s-operator: put Tailscale IPs in Service ingress status
Updates #502

Signed-off-by: Mike Beaumont <mjboamail@gmail.com>
9 months ago
Mike Beaumont ce4bf41dcf cmd/k8s-operator: support being the default loadbalancer controller
Updates #502

Signed-off-by: Mike Beaumont <mjboamail@gmail.com>
9 months ago
Brad Fitzpatrick 4af22f3785 util/deephash: add IncludeFields, ExcludeFields HasherForType Options
Updates tailscale/corp#6198

Change-Id: Iafc18c5b947522cf07a42a56f35c0319cc7b1c94
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick e7d1538a2d types/views: add SliceEqual, like std slices.Equal
Updates tailscale/corp#6198

Change-Id: I38614a4552c9fa933036aa493c7cdb57c7ffe2d2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
David Anderson b407fdef70 flake.nix: use Go 1.21 to build tailscale, for real this time
The previous change just switched the Go version used in the dev
environment (for use with e.g. direnv), not the version used for
the distribution build. Oops.

Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
David Anderson fe91160775 flake.nix: use Go 1.21 to build tailscale flake
Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
Flakes Updater e80ba4ce79 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
9 months ago
Maisem Ali 9430481926 cmd/containerboot: account for k8s secret reflection in fsnotify
On k8s the serve-config secret mount is symlinked so checking against
the Name makes us miss the events.

Updates #7895

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Andrew Lytvynov ce5909dafc
release/dist: remove extra Close on a signed file (#9094)
We pass the file as an io.Reader to http.Post under the hood as request
body. Post, helpfully, detects that the body is an io.Closer and closes
it. So when we try to explicitly close it again, we get "file already
closed" error.

The Close there is not load-bearing, we have a defer for it anyway.
Remove the explicit close and error check.

Updates #cleanup

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Sonia Appasamy 4828e4c2db client/web: move api handler into web.go
Also uses `http.HandlerFunc` to pass the handler into `csrfProtect`
so we can get rid of the extraneous `api` struct.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Dave Anderson 7b18ed293b
tsweb: check for key-based debug access before XFF check (#9093)
Fly apps all set X-Forwarded-For, which breaks debug access even
with a preshared key otherwise.

Updates tailscale/corp#3601

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
Aaron Klotz 6b6a8cf843 util/osdiag: add query for Windows page file configuration and status
It's very common for OOM crashes on Windows to be caused by lack of page
file space (the NT kernel does not overcommit). Since Windows automatically
manages page file space by default, unless the machine is out of disk space,
this is typically caused by manual page file configurations that are too
small.

This patch obtains the current page file size, the amount of free page file
space, and also determines whether the page file is automatically or manually
managed.

Fixes #9090

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
9 months ago
Denton Gentry 535db01b3f scripts/installer: add Kaisen, Garuda, Fedora-Asahi.
Fixes https://github.com/tailscale/tailscale/issues/8648
Fixes https://github.com/tailscale/tailscale/issues/8737
Fixes https://github.com/tailscale/tailscale/issues/9087

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
9 months ago
Maisem Ali c8dea67cbf cmd/k8s-operator: add support for Ingress resources
Previously, the operator would only monitor Services and create
a Tailscale StatefulSet which acted as a L3 proxy which proxied
traffic inbound to the Tailscale IP onto the services ClusterIP.

This extends that functionality to also monitor Ingress resources
where the `ingressClassName=tailscale` and similarly creates a
Tailscale StatefulSet, acting as a L7 proxy instead.

Users can override the desired hostname by setting:

```
- tls
  hosts:
  - "foo"
```

Hostnames specified under `rules` are ignored as we only create a single
host. This is emitted as an event for users to see.

Fixes #7895

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 320f77bd24 cmd/containerboot: add support for setting ServeConfig
This watches the provided path for a JSON encoded ipn.ServeConfig.
Everytime the file changes, or the nodes FQDN changes it reapplies
the ServeConfig.

At boot time, it nils out any previous ServeConfig just like tsnet does.

As the ServeConfig requires pre-existing knowledge of the nodes FQDN to do
SNI matching, it introduces a special `${TS_CERT_DOMAIN}` value in the JSON
file which is replaced with the known CertDomain before it is applied.

Updates #502
Updates #7895

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 12ac672542 cmd/k8s-operator: handle changes to services w/o teardown
Previously users would have to unexpose/expose the service in order to
change Hostname/TargetIP. This now applies those changes by causing a
StatefulSet rollout now that a61a9ab087 is in.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Denton Gentry 24d41e4ae7 cmd/sniproxy: add port forwarding and prometheus metrics
1. Add TCP port forwarding.
   For example: ./sniproxy -forwards=tcp/22/github.com
   will forward SSH to github.

   % ssh -i ~/.ssh/id_ecdsa.pem -T git@github.com
   Hi GitHubUser! You've successfully authenticated, but GitHub does not
   provide shell access.

   % ssh -i ~/.ssh/id_ecdsa.pem -T git@100.65.x.y
   Hi GitHubUser! You've successfully authenticated, but GitHub does not
   provide shell access.

2. Additionally export clientmetrics as prometheus metrics for local
   scraping over the tailnet: http://sniproxy-hostname:8080/debug/varz

Updates https://github.com/tailscale/tailscale/issues/1748

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
9 months ago
Brad Fitzpatrick 98a5116434 all: adjust some build tags for plan9
I'm not saying it works, but it compiles.

Updates #5794

Change-Id: I2f3c99732e67fe57a05edb25b758d083417f083e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Andrew Lytvynov de9ba1c621
clientupdate/distsign/roots: add temporary dev root key (#9080)
Adding a root key that signs the current signing key on
pkgs.tailscale.com. This key is here purely for development and should
be replaced before 1.50 release.

Updates #8760

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Sonia Appasamy f3077c6ab5 client/web: add self node cache
Adds a cached self node to the web client Server struct, which will
be used from the web client api to verify that request came from the
node's own machine (i.e. came from the web client frontend). We'll
be using when we switch the web client api over to acting as a proxy
to the localapi, to protect against DNS rebinding attacks.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Andrew Lytvynov 3b7ebeba2e
clientupdate: remove Arch support (#9081)
An Arch Linux maintainer asked us to not implement "tailscale update" on
Arch-based distros:
https://github.com/tailscale/tailscale/issues/6995#issuecomment-1687080106

Return an error to the user if they try to run "tailscale update".

Updates #6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Andrew Lytvynov b42c4e2da1
cmd/dist,release/dist: add distsign signing hooks (#9070)
Add `dist.Signer` hook which can arbitrarily sign linux/synology
artifacts. Plumb it through in `cmd/dist` and remove existing tarball
signing key. Distsign signing will happen on a remote machine, not using
a local key.

Updates #755
Updates #8760

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Will Norris dc8287ab3b client/web: enforce full path for CGI platforms
Synology and QNAP both run the web client as a CGI script. The old web
client didn't care too much about requests paths, since there was only a
single GET and POST handler. The new client serves assets on different
paths, so now we need to care.

First, enforce that the CGI script is always accessed from its full
path, including a trailing slash (e.g. /cgi-bin/tailscale/index.cgi/).
Then, strip that prefix off before passing the request along to the main
serve handler. This allows for properly serving both static files and
the API handler in a CGI environment. Also add a CGIPath option to allow
other CGI environments to specify a custom path.

Finally, update vite and one "api/data" call to no longer assume that we
are always serving at the root path of "/".

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Will Norris 0c3d343ea3 client/web: invert auth logic for synology and qnap
Add separate server methods for synology and qnap, and enforce
authentication and authorization checks before calling into the actual
serving handlers. This allows us to remove all of the auth logic from
those handlers, since all requests will already be authenticated by that
point.

Also simplify the Synology token redirect handler by using fetch.

Remove the SynologyUser from nodeData, since it was never used in the
frontend anyway.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Will Norris 05486f0f8e client/web: move synology and qnap logic into separate files
This commit doesn't change any of the logic, but just organizes the code
a little to prepare for future changes.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Maisem Ali ff7f4b4224 cmd/testwrapper: fix off-by-one error in maxAttempts check
It was checking if `>= maxAttempts` which meant that the third
attempt would never run.

Updates #8493

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali a61a9ab087 cmd/containerboot: reapply known args on restart
Previously we would not reapply changes to TS_HOSTNAME etc when
then the container restarted and TS_AUTH_ONCE was enabled.

This splits those into two steps login and set, allowing us to
only rerun the set step on restarts.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Andrew Lytvynov d45af7c66f
release/dist/cli: add sign-key and verify-key-signature commands (#9041)
Now we have all the commands to generate the key hierarchy and verify
that signing keys were signed correctly:
```
$ ./tool/go run ./cmd/dist gen-key --priv-path root-priv.pem --pub-path root-pub.pem --root
wrote private key to root-priv.pem
wrote public key to root-pub.pem

$ ./tool/go run ./cmd/dist gen-key --priv-path signing-priv.pem --pub-path signing-pub.pem --signing
wrote private key to signing-priv.pem
wrote public key to signing-pub.pem

$ ./tool/go run ./cmd/dist sign-key --root-priv-path root-priv.pem --sign-pub-path signing-pub.pem
wrote signature to signature.bin

$ ./tool/go run ./cmd/dist verify-key-signature --root-pub-path root-pub.pem --sign-pub-path signing-pub.pem --sig-path signature.bin
signature ok
```

Updates #8760

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Aaron Klotz 5fb1695bcb util/osdiag, util/osdiag/internal/wsc: add code to probe the Windows Security Center for installed software
The Windows Security Center is a component that manages the registration of
security products on a Windows system. Only products that have obtained a
special cert from Microsoft may register themselves using the WSC API.
Practically speaking, most vendors do in fact sign up for the program as it
enhances their legitimacy.

From our perspective, this is useful because it gives us a high-signal
source of information to query for the security products installed on the
system. I've tied this query into the osdiag package and is run during
bugreports.

It uses COM bindings that were automatically generated by my prototype
metadata processor, however that program still has a few bugs, so I had
to make a few manual tweaks. I dropped those binding into an internal
package because (for the moment, at least) they are effectively
purpose-built for the osdiag use case.

We also update the wingoes dependency to pick up BSTR.

Fixes #10646

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
9 months ago
Sonia Appasamy 349c05d38d client/web: refresh on tab focus
Refresh node data when user switches to the web client browser tab.
This helps clean up the auth flow where they're sent to another tab
to authenticate then return to the original tab, where the data
should be refreshed to pick up the login updates.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Will Norris 824cd02d6d client/web: cache csrf key when running in CGI mode
Indicate to the web client when it is running in CGI mode, and if it is
then cache the csrf key between requests.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
shayne 46b0c9168f
.github: update flakehub workflow to support existing tags (#9067)
This adds a workflow_dispatch input to the update-flakehub workflow that
allows the user to specify an existing tag to publish to FlakeHub. This
is useful for publishing a version of a package that has already been
tagged in the repository.

Updates #9008

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
9 months ago
shayne 7825074444
.github: fix flakehub-publish-tagged.yml glob (#9066)
The previous regex was too advanced for GitHub Actions. They only
support a simpler glob syntax.

https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet

Updates #9008

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
9 months ago
Brad Fitzpatrick 5b6a90fb33 types/logger, cmd/tailscale/cli: flesh out, simplify some non-unix build tags
Can write "wasm" instead of js || wasi1p, since there's only two:

    $ go tool dist list | grep wasm
    js/wasm
    wasip1/wasm

Plus, if GOOS=wasip2 is added later, we're already set.

Updates #5794

Change-Id: Ifcfb187c3775c17c9141bc721512dc4577ac4434
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick a5dcc4c87b paths: remove wasm file, no-op stubs, make OS-specific funcs consistent
Some OS-specific funcs were defined in init. Another used build tags
and required all other OSes to stub it out. Another one could just be in
the portable file.

Simplify it a bit, removing a file and some stubs in the process.

Updates #5794

Change-Id: I51df8772cc60a9335ac4c1dc0ab59b8a0d236961
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick d58ba59fd5 cmd/tailscale/cli: make netcheck run even if machine lacks TLS certs
We have a fancy package for doing TLS cert validation even if the machine
doesn't have TLS certs (for LetsEncrypt only) but the CLI's netcheck command
wasn't using it.

Also, update the tlsdial's outdated package docs while here.

Updates #cleanup

Change-Id: I74b3cb645d07af4d8ae230fb39a60c809ec129ad
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick e881c1caec net/netmon: factor out debounce loop, simplify polling impl
This simplifies some netmon code in prep for other changes.

It breaks up Monitor.debounce into a helper method so locking is
easier to read and things unindent, and then it simplifies the polling
netmon implementation to remove the redundant stuff that the caller
(the Monitor.debounce loop) was already basically doing.

Updates #9040

Change-Id: Idcfb45201d00ae64017042a7bdee6ef86ad37a9f
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Will Norris 9ea3942b1a client/web: don't require secure cookies for csrf
Under normal circumstances, you would typically want to keep the default
behavior of requiring secure cookies.  In the case of the Tailscale web
client, we are regularly serving on localhost (where secure cookies
don't really matter), and/or we are behind a reverse proxy running on a
network appliance like a NAS or Home Assistant. In those cases, those
devices are regularly accessed over local IP addresses without https
configured, so would not work with secure cookies.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Andrew Lytvynov f61dd12f05
clientupdate/distsign: use distinct PEM types for root/signing keys (#9045)
To make key management less error-prone, use different PEM block types
for root and signing keys. As a result, separate out most of the Go code
between root/signing keys too.

Updates #8760

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Marwan Sulaiman 9c07f4f512 all: replace deprecated ioutil references
This PR removes calls to ioutil library and replaces them
with their new locations in the io and os packages.

Fixes #9034
Updates #5210

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Denton Gentry 1b8a538953 scripts/installer.sh: add CloudLinux and Alibaba Linux
Fixes https://github.com/tailscale/tailscale/issues/9010

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
9 months ago
Sonia Appasamy 776f9b5875 client/web: open auth URLs in new browser tab
Open control server auth URLs in new browser tabs on web clients
so users don't loose original client URL when redirected for login.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Brad Fitzpatrick ad9b711a1b tailcfg: bump capver to 72 to restore UPnP
Actually fixed in 77ff705545 but that was cherry-picked to a branch
and we don't bump capver in branches.

This tells the control plane that UPnP should be re-enabled going
forward.

Updates #8992

Change-Id: I5c4743eb52fdee94175668c368c0f712536dc26b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick ea4425d8a9 ipn/ipnlocal, wgengine/magicsock: move UpdateStatus stuff around
Upcoming work on incremental netmap change handling will require some
replumbing of which subsystems get notified about what. Done naively,
it could break "tailscale status --json" visibility later. To make sure
I understood the flow of all the updates I was rereading the status code
and realized parts of ipnstate.Status were being populated by the wrong
subsystems.

The engine (wireguard) and magicsock (data plane, NAT traveral) should
only populate the stuff that they uniquely know. The WireGuard bits
were fine but magicsock was populating stuff stuff that LocalBackend
could've better handled, so move it there.

Updates #1909

Change-Id: I6d1b95d19a2d1b70fbb3c875fac8ea1e169e8cb0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Maisem Ali 74388a771f cmd/k8s-operator: fix regression from earlier refactor
I forgot to move the defer out of the func, so the tsnet.Server
immediately closed after starting.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Brad Fitzpatrick 9089efea06 net/netmon: make ChangeFunc's signature take new ChangeDelta, not bool
Updates #9040

Change-Id: Ia43752064a1a6ecefc8802b58d6eaa0b71cf1f84
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Sonia Appasamy 78f087aa02 cli/web: pass existing localClient to web client
Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
David Anderson 5cfa85e604 tsweb: clean up pprof handler registration, document why it's there
Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
9 months ago
Will Norris 09068f6c16 release: add empty embed.FS for release files
This ensures that `go mod vendor` includes these files, which are needed
for client builds run in corp.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Maisem Ali 836f932ead cmd/k8s-operator: split operator.go into svc.go/sts.go
Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Maisem Ali 7f6bc52b78 cmd/k8s-operator: refactor operator code
It was jumbled doing a lot of things, this breaks it up into
the svc reconciliation and the tailscale sts reconciliation.

Prep for future commit.

Updates #502

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Will Norris cf45d6a275 client/web: remove old /redirect handler
I thought this had something to do with Synology or QNAP support, since
they both have specific authentication logic.  But it turns out this was
part of the original web client added in #1621, and then refactored as
part of #2093.  But with how we handle logging in now, it's never
called.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Andrew Lytvynov 05523bdcdd
release/dist/cli: add gen-key command (#9023)
Add a new subcommand to generate a Ed25519 key pair for release signing.
The same command can be used to generate both root and signing keys.

Updates #8760

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
James Tucker e1c7e9b736 wgengine/magicsock: improve endpoint selection for WireGuard peers with rx time
If we don't have the ICMP hint available, such as on Android, we can use
the signal of rx traffic to bias toward a particular endpoint.

We don't want to stick to a particular endpoint for a very long time
without any signals, so the sticky time is reduced to 1 second, which is
large enough to avoid excessive packet reordering in the common case,
but should be small enough that either rx provides a strong signal, or
we rotate in a user-interactive schedule to another endpoint, improving
the feel of failover to other endpoints.

Updates #8999

Co-authored-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>

Signed-off-by: James Tucker <james@tailscale.com>
Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
9 months ago
James Tucker 5edb39d032 wgengine/magicsock: clear out endpoint statistics when it becomes bad
There are cases where we do not detect the non-viability of a route, but
we will instead observe a failure to send. In a Disco path this would
normally be handled as a side effect of Disco, which is not available to
non-Disco WireGuard nodes. In both cases, recognizing the failure as
such will result in faster convergence.

Updates #8999
Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
Charlotte Brandhorst-Satzkorn 7c9c68feed wgengine/magicsock: update lastfullping comment to include wg only
LastFullPing is now used for disco or wireguard only endpoints. This
change updates the comment to make that clear.

Updates #7826

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
9 months ago
Aaron Klotz ea693eacb6 util/winutil: add RegisterForRestart, allowing programs to indicate their preferences to the Windows restart manager
In order for the installer to restart the GUI correctly post-upgrade, we
need the GUI to be able to register its restart preferences.

This PR adds API support for doing so. I'm adding it to OSS so that it
is available should we need to do any such registrations on OSS binaries
in the future.

Updates https://github.com/tailscale/corp/issues/13998

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
9 months ago
James Tucker 3a652d7761 wgengine/magicsock: clear endpoint state in noteConnectivityChange
There are latency values stored in bestAddr and endpointState that are
no longer applicable after a connectivity change and should be cleared
out, following the documented behavior of the function.

Updates #8999

Signed-off-by: James Tucker <james@tailscale.com>
9 months ago
Andrew Lytvynov 7364c6beec
clientupdate/distsign: add new library for package signing/verification (#8943)
This library is intended for use during release to sign packages which
are then served from pkgs.tailscale.com.
The library is also then used by clients downloading packages for
`tailscale update` where OS package managers / app stores aren't used.

Updates https://github.com/tailscale/tailscale/issues/8760
Updates https://github.com/tailscale/tailscale/issues/6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
9 months ago
Maisem Ali 4b13e6e087 go.mod: bump golang.org/x/net
Theory is that our long lived http2 connection to control would
get tainted by _something_ (unclear what) and would get closed.

This picks up the fix for golang/go#60818.

Updates tailscale/corp#5761

Signed-off-by: Maisem Ali <maisem@tailscale.com>
9 months ago
Will Norris 5ebff95a4c client/web: fix globbing for file embedding
src/**/* was only grabbing files in subdirectories, but not in the src
directory itself.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Marwan Sulaiman 000c0a70f6 ipn, ipn/ipnlocal: clean up documentation and use clock instead of time
This PR addresses a number of the follow ups from PR #8491 that were written
after getting merged.

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Will Norris 0df5507c81 client/web: combine embeds into a single embed.FS
instead of embedding each file individually, embed them all into a
single embed filesystem.  This is basically a noop for the current
frontend, but sets things up a little cleaner for the new frontend.

Also added an embed.FS for the source files needed to build the new
frontend. These files are not actually embedded into the binary (since
it is a blank identifier), but causes `go mod vendor` to copy them into
the vendor directory.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Will Norris 3722b05465 release/dist: run yarn build before building CLI
This builds the assets for the new web client as part of our release
process. The path to the web client source is specified by the
-web-client-root flag.  This allows corp builds to first vendor the
tailscale.com module, and then build the web client assets in the vendor
directory.

The default value for the -web-client-root flag is empty, so no assets
are built by default.

This is an update of the previously reverted 0fb95ec

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Sonia Appasamy 09e5e68297 client/web: track web client initializations
Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Brad Fitzpatrick 947def7688 types/netmap: remove redundant Netmap.Hostinfo
It was in SelfNode.Hostinfo anyway. The redundant copy was just
costing us an allocation per netmap (a Hostinfo.Clone).

Updates #1909

Change-Id: Ifac568aa5f8054d9419828489442a0f4559bc099
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Sonia Appasamy 50b558de74 client/web: hook up remaining legacy POST requests
Hooks up remaining legacy POST request from the React side in --dev.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Brad Fitzpatrick db017d3b12 control/controlclient: remove quadratic allocs in mapSession
The mapSession code was previously quadratic: N clients in a netmap
send updates proportional to N and then for each, we do N units of
work. This removes most of that "N units of work" per update. There's
still a netmap-sized slice allocation per update (that's #8963), but
that's it.

Bit more efficient now, especially with larger netmaps:

                                 │     before     │                after                │
                                 │     sec/op     │   sec/op     vs base                │
    MapSessionDelta/size_10-8       47.935µ ±  3%   1.232µ ± 2%  -97.43% (p=0.000 n=10)
    MapSessionDelta/size_100-8      79.950µ ±  3%   1.642µ ± 2%  -97.95% (p=0.000 n=10)
    MapSessionDelta/size_1000-8    355.747µ ± 10%   4.400µ ± 1%  -98.76% (p=0.000 n=10)
    MapSessionDelta/size_10000-8   3079.71µ ±  3%   27.89µ ± 3%  -99.09% (p=0.000 n=10)
    geomean                          254.6µ         3.969µ       -98.44%

                                 │     before     │                after                 │
                                 │      B/op      │     B/op      vs base                │
    MapSessionDelta/size_10-8        9.651Ki ± 0%   2.395Ki ± 0%  -75.19% (p=0.000 n=10)
    MapSessionDelta/size_100-8      83.097Ki ± 0%   3.192Ki ± 0%  -96.16% (p=0.000 n=10)
    MapSessionDelta/size_1000-8     800.25Ki ± 0%   10.32Ki ± 0%  -98.71% (p=0.000 n=10)
    MapSessionDelta/size_10000-8   7896.04Ki ± 0%   82.32Ki ± 0%  -98.96% (p=0.000 n=10)
    geomean                          266.8Ki        8.977Ki       -96.64%

                                 │    before     │               after                │
                                 │   allocs/op   │ allocs/op   vs base                │
    MapSessionDelta/size_10-8         72.00 ± 0%   20.00 ± 0%  -72.22% (p=0.000 n=10)
    MapSessionDelta/size_100-8       523.00 ± 0%   20.00 ± 0%  -96.18% (p=0.000 n=10)
    MapSessionDelta/size_1000-8     5024.00 ± 0%   20.00 ± 0%  -99.60% (p=0.000 n=10)
    MapSessionDelta/size_10000-8   50024.00 ± 0%   20.00 ± 0%  -99.96% (p=0.000 n=10)
    geomean                          1.754k        20.00       -98.86%

Updates #1909

Change-Id: I41ee29358a5521ed762216a76d4cc5b0d16e46ac
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
shayne a3b0654ed8
.github: add flakehub-publish-tagged.yml (#9009)
This workflow will publish a flake to flakehub when a tag is pushed to
the repository. It will only publish tags that match the pattern
`v*.*.*`.

Fixes #9008

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
9 months ago
Marwan Sulaiman 35ff5bf5a6 cmd/tailscale/cli, ipn/ipnlocal: [funnel] add stream mode
Adds ability to start Funnel in the foreground and stream incoming
connections. When foreground process is stopped, Funnel is turned
back off for the port.

Exampe usage:
```
TAILSCALE_FUNNEL_V2=on tailscale funnel 8080
```

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
9 months ago
Brad Fitzpatrick cb4a61f951 control/controlclient: don't clone self node on each NetworkMap
Drop in the bucket, but have to start somewhere.

Real wins will come once this is done for peers.

                                 │     before     │                after                │
                                 │      B/op      │     B/op       vs base              │
    MapSessionDelta/size_10-8      10.213Ki ± ∞ ¹   9.650Ki ± ∞ ¹  -5.51% (p=0.008 n=5)
    MapSessionDelta/size_100-8      83.64Ki ± ∞ ¹   83.08Ki ± ∞ ¹  -0.67% (p=0.008 n=5)
    MapSessionDelta/size_1000-8     800.8Ki ± ∞ ¹   800.3Ki ± ∞ ¹  -0.07% (p=0.008 n=5)
    MapSessionDelta/size_10000-8    7.712Mi ± ∞ ¹   7.711Mi ± ∞ ¹  -0.01% (p=0.008 n=5)
    geomean                         271.1Ki         266.8Ki        -1.59%

                                 │    before    │               after                │
                                 │  allocs/op   │  allocs/op    vs base              │
    MapSessionDelta/size_10-8       73.00 ± ∞ ¹    72.00 ± ∞ ¹  -1.37% (p=0.008 n=5)
    MapSessionDelta/size_100-8      524.0 ± ∞ ¹    523.0 ± ∞ ¹  -0.19% (p=0.008 n=5)
    MapSessionDelta/size_1000-8    5.025k ± ∞ ¹   5.024k ± ∞ ¹  -0.02% (p=0.008 n=5)
    MapSessionDelta/size_10000-8   50.02k ± ∞ ¹   50.02k ± ∞ ¹  -0.00% (p=0.040 n=5)
    geomean                        1.761k         1.754k        -0.40%

Updates #1909

Change-Id: Ie19dea3371de251d64d4373dd00422f53c2675ea
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Will Norris a461d230db Revert "release/dist: run yarn build before building CLI"
This caused breakages on the build server:

synology/dsm7/x86_64: chdir /home/ubuntu/builds/2023-08-21T21-47-38Z-unstable-main-tagged-devices/0/client/web: no such file or directory
synology/dsm7/i686: chdir /home/ubuntu/builds/2023-08-21T21-47-38Z-unstable-main-tagged-devices/0/client/web: no such file or directory
synology/dsm7/armv8: chdir /home/ubuntu/builds/2023-08-21T21-47-38Z-unstable-main-tagged-devices/0/client/web: no such file or directory
...

Reverting while I investigate.

This reverts commit 0fb95ec07d.

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Will Norris 0fb95ec07d release/dist: run yarn build before building CLI
This builds the assets for the new web client as part of our release
process. These assets will soon be embedded into the cmd/tailscale
binary, but are not actually done so yet.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
9 months ago
Brad Fitzpatrick 84b94b3146 types/netmap, all: make NetworkMap.SelfNode a tailcfg.NodeView
Updates #1909

Change-Id: I8c470cbc147129a652c1d58eac9b790691b87606
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
License Updater 699f9699ca licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
9 months ago
Flakes Updater f6615931d7 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
9 months ago
Sonia Appasamy 077bbb8403 client/web: add csrf protection to web client api
Adds csrf protection and hooks up an initial POST request from
the React web client.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
9 months ago
Andrew Dunham 77ff705545 net/portmapper: never select port 0 in UPnP
Port 0 is interpreted, per the spec (but inconsistently among router
software) as requesting to map every single available port on the UPnP
gateway to the internal IP address. We'd previously avoided picking
ports below 1024 for one of the two UPnP methods (in #7457), and this
change moves that logic so that we avoid it in all cases.

Updates #8992

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I20d652c0cd47a24aef27f75c81f78ae53cc3c71e
9 months ago
Brad Fitzpatrick b5ff68a968 control/controlclient: flesh out mapSession to break up gigantic method
Now mapSession has a bunch more fields and methods, rather than being
just one massive func with a ton of local variables.

So far there are no major new optimizations, though. It should behave
the same as before.

This has been done with an eye towards testability (so tests can set
all the callback funcs as needed, or not, without a huge Direct client
or long-running HTTP requests), but this change doesn't add new tests
yet. That will follow in the changes which flesh out the NetmapUpdater
interface.

Updates #1909

Change-Id: Iad4e7442d5bbbe2614bd4b1dc4b02e27504898df
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Brad Fitzpatrick 1b223566dd util/linuxfw: fix typo in unexported doc comment
And flesh it out and use idiomatic doc style ("whether" for bools)
and end in a period while there anyway.

Updates #cleanup

Change-Id: Ieb82f13969656e2340c3510e7b102dc8e6932611
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
9 months ago
Val c85d7c301a tool: force HTTP/1.1 in curl to prevent hang behind load balancer
When running in our github CI environment, curl sometimes hangs while closing
the download from the nodejs.org server and fails with INTERNAL_ERROR. This is
likely caused by CI running behind some kind of load balancer or proxy that
handles HTTP/2 incorrectly in some minor way, so force curl to use HTTP 1.1.

Updates #8988

Signed-off-by: Val <valerie@tailscale.com>
9 months ago
Denton Gentry f486041fd1 tsnet: add support for clientmetrics.
Updates https://github.com/tailscale/tailscale/issues/1748

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
9 months ago
Val c15997511d wgengine/magicsock: only accept pong sent by CLI ping
When sending a ping from the CLI, only accept a pong that is in reply
to the specific CLI ping we sent.

Updates #311

Signed-off-by: Val <valerie@tailscale.com>
9 months ago
Brad Fitzpatrick 165f0116f1 types/netmap: move some mutations earlier, remove, document some fields
And optimize the Persist setting a bit, allocating later and only mutating
fields when there's been a Node change.

Updates #1909

Change-Id: Iaddfd9e88ef76e1d18e8d0a41926eb44d0955312
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 21170fb175 control/controlclient: scope a variable tighter, de-pointer a *time.Time
Just misc cleanups.

Updates #1909

Change-Id: I9d64cb6c46d634eb5fdf725c13a6c5e514e02e9a
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Maisem Ali 2548496cef types/views,cmd/viewer: add ByteSlice[T] to replace mem.RO
Add a new views.ByteSlice[T ~[]byte] to provide a better API to use
with views.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Maisem Ali 8a5ec72c85 cmd/cloner: use maps.Clone and ptr.To
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Brad Fitzpatrick 4511e7d64e ipn/ipnstate: add PeerStatus.AltSharerUserID, stop mangling Node.User
In b987b2ab18 (2021-01-12) when we introduced sharing we mapped
the sharer to the userid at a low layer, mostly to fix the display of
"tailscale status" and the client UIs, but also some tests.

The commit earlier today, 7dec09d169, removed the 2.5yo option
to let clients disable that automatic mapping, as clearly we were never
getting around to it.

This plumbs the Sharer UserID all the way to ipnstatus so the CLI
itself can choose to print out the Sharer's identity over the node's
original owner.

Then we stop mangling Node.User and let clients decide how they want
to render things.

To ease the migration for the Windows GUI (which currently operates on
tailcfg.Node via the NetMap from WatchIPNBus, instead of PeerStatus),
a new method Node.SharerOrUser is added to do the mapping of
Sharer-else-User.

Updates #1909
Updates tailscale/corp#1183

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Maisem Ali d483ed7774 tailcfg: generate RegisterResponse.Clone, remove manually written
It had a custom Clone func with a TODO to replace with cloner, resolve
that todo. Had to pull out the embedded Auth struct into a named struct.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Brad Fitzpatrick 282dad1b62 tailcfg: update docs on NetInfo.FirewallMode
Updates #391

Change-Id: Ifef196b31dd145f424fb0c0d0bb04565cc22c717
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick d8191a9813 ipn/ipnlocal: fix regression in printf arg type
I screwed this up in 58a4fd43d as I expected. I even looked out for
cases like this (because this always happens) and I still missed
it. Vet doesn't flag these because they're not the standard printf
funcs it knows about. TODO: make our vet recognize all our
"logger.Logf" types.

Updates #8948

Change-Id: Iae267d5f81da49d0876b91c0e6dc451bf7dcd721
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick f35ff84ee2 util/deephash: relax an annoyingly needy test
I'd added a test case of deephash against a tailcfg.Node to make sure
it worked at all more than anything. We don't care what the exact
bytes are in this test, just that it doesn't fail. So adjust for that.

Then when we make changes to tailcfg.Node and types under it, we don't
need to keep adjusting this test.

Updates #cleanup

Change-Id: Ibf4fa42820aeab8f5292fe65f9f92ffdb0b4407b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 93a806ba31 types/tkatype: add test for MarshaledSignature's JSON format
Lock in its wire format before a potential change to its Go type.

Updates #1909

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 7dec09d169 control/controlclient: remove Opts.KeepSharerAndUserSplit
It was added 2.5 years ago in c1dabd9436 but was never used.
Clearly that migration didn't matter.

We can attempt this again later if/when this matters.

Meanwhile this simplifies the code and thus makes working on other
current efforts in these parts of the code easier.

Updates #1909

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Maisem Ali 02b47d123f tailcfg: remove unused Domain field from Login/User
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Brad Fitzpatrick 58a4fd43d8 types/netmap, all: use read-only tailcfg.NodeView in NetworkMap
Updates #8948

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
KevinLiang10 b040094b90 util/linuxfw: reorganize nftables rules to allow it to work with ufw
This commit tries to mimic the way iptables-nft work with the filewall rules. We
follow the convention of using tables like filter, nat and the conventional
chains, to make our nftables implementation work with ufw.

Updates: #391

Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
10 months ago
Will Norris d4586ca75f tsnet/example/web-client: listen on localhost
Serving the web client on the tailscale interface, while useful for
remote management, is also inherently risky if ACLs are not configured
appropriately. Switch the example to listen only on localhost, which is
a much safer default. This is still a valuable example, since it still
demonstrates how to have a web client connected to a tsnet instance.

Updates #13775

Signed-off-by: Will Norris <will@tailscale.com>
10 months ago
KevinLiang10 93cab56277 wgengine/router: fall back and set iptables as default again
Due to the conflict between our nftables implementation and ufw, which is a common utility used
on linux. We now want to take a step back to prevent regression. This will give us more chance to
let users to test our nftables support and heuristic.

Updates: #391
Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
10 months ago
Brad Fitzpatrick 6e57dee7eb cmd/viewer, types/views, all: un-special case slice of netip.Prefix
Make it just a views.Slice[netip.Prefix] instead of its own named type.

Having the special case led to circular dependencies in another WIP PR
of mine.

Updates #8948

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 261cc498d3 types/views: add LenIter method to slice view types
This is basically https://github.com/bradfitz/iter which was
a joke but now that Go's adding range over int soonish, might
as well. It simplies our code elsewher that uses slice views.

Updates #8948

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick af2e4909b6 all: remove some Debug fields, NetworkMap.Debug, Reconfig Debug arg
Updates #8923

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Andrew Lytvynov 86ad1ea60e
clientupdate: parse /etc/synoinfo.conf to get CPU arch (#8940)
The hardware version in `/proc/sys/kernel/syno_hw_version` does not map
exactly to versions in
https://github.com/SynoCommunity/spksrc/wiki/Synology-and-SynoCommunity-Package-Architectures.
It contains some slightly different version formats.

Instead, `/etc/synoinfo.conf` exists and contains a `unique` line with
the CPU architecture encoded. Parse that out and filter through the list
of architectures that we have SPKs for.

Tested on DS218 and DS413j.

Updates #8927

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Marwan Sulaiman 72d2122cad cmd/tailscale: change serve and funnel calls to StatusWithoutPeers
The tailscale serve|funnel commands frequently call the LocalBackend's Status
but they never need the peers to be included. This PR changes the call to be
StatusWithoutPeers which should gain a noticeable speed improvement

Updates #8489

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
10 months ago
Brad Fitzpatrick 121d1d002c tailcfg: add nodeAttrs for forcing OneCGNAT on/off [capver 71]
Updates #8923

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 25663b1307 tailcfg: remove most Debug fields, move bulk to nodeAttrs [capver 70]
Now a nodeAttr: ForceBackgroundSTUN, DERPRoute, TrimWGConfig,
DisableSubnetsIfPAC, DisableUPnP.

Kept support for, but also now a NodeAttr: RandomizeClientPort.

Removed: SetForceBackgroundSTUN, SetRandomizeClientPort (both never
used, sadly... never got around to them. But nodeAttrs are better
anyway), EnableSilentDisco (will be a nodeAttr later when that effort
resumes).

Updates #8923

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
David Anderson e92adfe5e4 net/art: allow non-pointers as values
Values are still turned into pointers internally to maintain the
invariants of strideTable, but from the user's perspective it's
now possible to tbl.Insert(pfx, true) rather than
tbl.Insert(pfx, ptr.To(true)).

Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
Brad Fitzpatrick bc0eb6b914 all: import x/exp/maps as xmaps to distinguish from Go 1.21 "maps"
Updates #8419

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick e8551d6b40 all: use Go 1.21 slices, maps instead of x/exp/{slices,maps}
Updates #8419

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Denton Gentry e8d140654a cmd/derper: count bootstrap dns unique lookups.
Updates https://github.com/tailscale/corp/issues/13979

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
10 months ago
Denton Gentry 7e15c78a5a syncs: add map.Clear() method
Updates https://github.com/tailscale/corp/issues/13979

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
10 months ago
Brad Fitzpatrick 239ad57446 tailcfg: move LogHeapPprof from Debug to c2n [capver 69]
And delete Debug.GoroutineDumpURL, which was already in c2n.

Updates #8923

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Maisem Ali 24509f8b22 cmd/k8s-operator: add support for control plane assigned groups
Previously we would use the Impersonate-Group header to pass through
tags to the k8s api server. However, we would do nothing for non-tagged
nodes. Now that we have a way to specify these via peerCaps respect those
and send down groups for non-tagged nodes as well.

For tagged nodes, it defaults to sending down the tags as groups to retain
legacy behavior if there are no caps set. Otherwise, the tags are omitted.

Updates #5055

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Brad Fitzpatrick 0913ec023b CODEOWNERS: add the start of an owners file
Updates tailscale/corp#13972

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick b090d61c0f tailcfg: rename prototype field to reflect its status
(Added earlier today in #8916, 57da1f150)

Updates tailscale/corp#13969

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Richard Castro 57da1f1501
client: update DNSConfig type (#8916)
This PR adds DNSFilterURL to the DNSConfig type to be used by
control changes to add DNS filtering logic

Fixes #cleanup

Signed-off-by: Richard Castro <richard@tailscale.com>
10 months ago
Chris Palmer 37c0b9be63
clientupdate: return NOTREACHED for macsys (#8898)
* clientupdate: return NOTREACHED for macsys

The work is done in Swift; this is now a documentation placeholder.

Updates #6995

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
10 months ago
Sonia Appasamy 18280ebf7d client/web: hook up data fetching to fill --dev React UI
Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
David Anderson 623d72c83b net/art: move child table pointers out of strideEntry
In preparation for a different refactor, but incidentally also saves
10-25% memory on overall table size in benchmarks.

Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
Charlotte Brandhorst-Satzkorn f101a75dce cmd/tailscale/cli: fix comment accuracy
All exit nodes are shown under this subcommand.

Updates tailscale/corp#13025

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
10 months ago
Adrian Dewhurst f75a36f9bc tsweb: add request ID for errors
If an optional request ID generating func is supplied to StdHandler,
then requests that return an error will be logged with a request ID that
is also shown as part of the response.

Updates tailscale/corp#2549

Change-Id: Ic7499706df42f95b6878d44d4aab253e2fc6a69b
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
10 months ago
Andrew Lytvynov cf31b58ed1
VERSION.txt: this is v1.49.0 (#8907)
Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Brad Fitzpatrick 6c791f7d60 derp: include src IPs in mesh watch messages
Updates tailscale/corp#13945

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
KevinLiang10 7ed3681cbe tailcfg: Add FirewallMode to NetInfo to record wether host using iptables or nftables
To record wether user is using iptables or nftables after we add support to nftables on linux, we
are adding a field FirewallMode to NetInfo in HostInfo to reflect what firewall mode the host is
running, and form metrics. The information is gained from a global constant in hostinfo.go. We
set it when selection heuristic made the decision, and magicsock reports this to control.

Updates: tailscale/corp#13943
Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
10 months ago
Andrew Dunham 95d776bd8c wgengine/magicsock: only cache N most recent endpoints per-Addr
If a node is flapping or otherwise generating lots of STUN endpoints, we
can end up caching a ton of useless values and sending them to peers.
Instead, let's apply a fixed per-Addr limit of endpoints that we cache,
so that we're only sending peers up to the N most recent.

Updates tailscale/corp#13890

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8079a05b44220c46da55016c0e5fc96dd2135ef8
10 months ago
Will Norris 9c4364e0b7 client/web: copy existing UI to basic react components
This copies the existing go template frontend into very crude react
components that will be driven by a simple JSON api for fetching and
updating data.  For now, this returns a static set of test data.

This just implements the simple existing UI, so I've put these all in a
"legacy" component, with the expectation that we will rebuild this with
more properly defined components, some pulled from corp.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
10 months ago
Will Norris ddba4824c4 client/web: add prettier and format scripts
Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
10 months ago
Brad Fitzpatrick bd02d00608 ssh/tailssh: fix gokrazy SSH crash
Stupid mistake in earlier refactor.

Updates gokrazy/gokrazy#209

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 25a8daf405 wgengine/router: always use nftables mode on gokrazy
Updates gokrazy/gokrazy#209

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 17ce75347c wgengine: adjust debug logging for WireGuard-only peers
Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Sonia Appasamy 1a64166073 cli/serve: add interactive flow for enabling HTTPS certs
When trying to use serve with https, send users through https cert
provisioning enablement before editing the ServeConfig.

Updates tailscale/corp#10577

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Sonia Appasamy 0052830c64 cli/serve: funnel interactive enablement flow tweaks
1. Add metrics to funnel flow.
2. Stop blocking users from turning off funnels when no longer in
   their node capabilities.
3. Rename LocalClient.IncrementMetric to IncrementCounter to better
   callout its usage is only for counter clientmetrics.

Updates tailscale/corp#10577

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Sonia Appasamy 8e63d75018 client/tailscale: add LocalClient.IncrementMetric func
A #cleanup to add a func to utilize the already-present
"/localapi/v0/upload-client-metrics" localapi endpoint.

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Aaron Klotz c17a817769 util/osdiag: add logging for winsock layered service providers to Windows bugreports
The Layered Service Provider (LSP) is a deprecated (but still supported)
mechanism for inserting user-mode DLLs into a filter chain between the
Winsock API surface (ie, ws2_32.dll) and the internal user-mode interface
to the networking stack.

While their use is becoming more rare due to the aforementioned deprecation,
it is still possible for third-party software to install their DLLs into
this filter chain and interfere with Winsock API calls. Knowing whether
this is happening is useful for troubleshooting.

Fixes https://github.com/tailscale/tailscale/issues/8142

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
10 months ago
KevinLiang10 411e3364a9 wgengine/router: use iptablesRunner when no firewall tool is available:
The current router errors out when neither iptables nor nftables support is present. We
should fall back to the previous behaviour which we creates a dummy iptablesRunner.

Fixes: #8878
Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
10 months ago
Sonia Appasamy 12238dab48 client/web: add tailwind styling to react app
Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Aaron Klotz b07347640c util/winutil/authenticode: add missing docs for CertSubjectError
A #cleanup PR.

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
10 months ago
Brad Fitzpatrick 1fcae42055 control/controlclient: move lastUpdateGenInformed to tighter scope
No need to have it on Auto or be behind a mutex; it's only read/written
from a single goroutine. Move it there.

Updates tailscale/corp#5761

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 2398993804 control/controlclient: refactor in prep for optimized delta handling
See issue. This is a baby step towards passing through deltas
end-to-end from node to control back to node and down to the various
engine subsystems, not computing diffs from two full netmaps at
various levels. This will then let us support larger netmaps without
burning CPU.

But this change itself changes no behavior. It just changes a func
type to an interface with one method. That paves the way for future
changes to then add new NetmapUpdater methods that do more
fine-grained work than updating the whole world.

Updates #1909

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Denton Gentry 4940a718a1 scripts/installer.sh: set Deepin to a debian version
Deepin Linux 20.x reports its version as "apricot"
Set it to bullseye, the Debian version it corresponds to.

Also fix the installer CI: OpenSUSE Leap appears to have removed
curl from the base image recently, we have to install it now.

Fixes https://github.com/tailscale/tailscale/issues/8850
Updates https://github.com/tailscale/tailscale/issues/7862
Updates https://github.com/tailscale/corp/issues/8952

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
10 months ago
M. J. Fromberger 9e24a6508a
control/controlclient: avert a data race when logging (#8863)
The read of the synced field for logging takes place outside the lock, and
races with other (locked) writes of this field, including for example the one
at current line 556 in mapRoutine.

Updates tailscale/corp#13856

Change-Id: I056b36d7a93025aafdf73528dd7645f10b791af6
Signed-off-by: M. J. Fromberger <fromberger@tailscale.com>
10 months ago
Andrew Lytvynov c40d095c35
clientupdate: implement updates for Synology (#8858)
Implement naive update for Synology packages, using latest versions from
pkgs.tailscale.com. This is naive because we completely trust
pkgs.tailscale.com to give us a safe package. We should switch this to
some better signing mechanism later.

I've only tested this on one DS218 box, so all the CPU architecture
munging is purely based on docs.

Updates #6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Brad Fitzpatrick a1b8d703d6 tstime/mono: remove unsafe
This removes the unsafe/linkname and only uses the standard library.

It's a bit slower, for now, but https://go.dev/cl/518336 should get us
back.

On darwin/arm64, without https://go.dev/cl/518336

    pkg: tailscale.com/tstime/mono
              │   before    │                after                │
              │   sec/op    │   sec/op     vs base                │
    MonoNow-8   16.20n ± 0%   19.75n ± 0%  +21.92% (p=0.000 n=10)
    TimeNow-8   39.46n ± 0%   39.40n ± 0%   -0.16% (p=0.002 n=10)
    geomean     25.28n        27.89n       +10.33%

And with it,

    MonoNow-8   16.34n ±  1%   16.93n ± 0%  +3.67% (p=0.001 n=10)
    TimeNow-8   39.55n ± 15%   38.46n ± 1%  -2.76% (p=0.000 n=10)
    geomean     25.42n         25.52n       +0.41%

Updates #8839
Updates tailscale/go#70

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
shayne cc3caa4b2a
hostinfo: add Home Assistant Add-On detection (#8857)
Fixes #8856

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
10 months ago
James Tucker de8e55fda6 net/netcheck,wgengine/magicsock: reduce coupling between netcheck and magicsock
Netcheck no longer performs I/O itself, instead it makes requests via
SendPacket and expects users to route reply traffic to
ReceiveSTUNPacket.

Netcheck gains a Standalone function that stands up sockets and
goroutines to implement I/O when used in a standalone fashion.

Magicsock now unconditionally routes STUN traffic to the netcheck.Client
that it hosts, and plumbs the send packet sink.

The CLI is updated to make use of the Standalone mode.

Fixes #8723

Signed-off-by: James Tucker <james@tailscale.com>
10 months ago
Sonia Appasamy d5ac18d2c4 client/web: add tsconfig.json
Also allows us to use absolute import paths (see change in index.tsx).

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Maisem Ali 21e32b23f7 .github: use testwrapper on windows
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Sonia Appasamy 3f12b9c8b2 client/web: pipe through to React in dev mode
Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Maisem Ali 98ec8924c2 ipn/ipnlocal,net/tsdial: update docs/rename funcs
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Brad Fitzpatrick 92fc9a01fa cmd/tailscale: add debug commands to break connections
For testing reconnects.

Updates tailscale/corp#5761

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
salman aljammaz 99e06d3544
magicsock: set the don't fragment sockopt (#8715)
This sets the Don't Fragment flag, for now behind the
TS_DEBUG_ENABLE_PMTUD envknob.

Updates #311.

Signed-off-by: Val <valerie@tailscale.com>
Signed-off-by: salman <salman@tailscale.com>
10 months ago
Sonia Appasamy 16bc9350e3 client/web: add barebones vite dev setup
Currently just serving a "Hello world" page when running the web
cli in --dev mode.

Updates tailscale/corp#13775

Co-authored-by: Will Norris <will@tailscale.com>
Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Andrew Lytvynov 215480a022
cmd/tailscale/cli,clientupdate: extract new clientupdate package (#8827)
Extract the self-update logic from cmd/tailscale/cli into a standalone
package that could be used from tailscaled later.

Updates #6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Sonia Appasamy 53c722924b tool/{node,yarn}: update node and yarn tools
Syncing these up with what we've got in corp.

Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Maisem Ali d16946854f control/controlclient: add Auto.updateRoutine
Instead of having updates replace the map polls, create
a third goroutine which is solely responsible for making
sure that control is aware of the latest client state.

This also makes it so that the streaming map polls are only
broken when there are auth changes, or the client is paused.

Updates tailscale/corp#5761

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Brad Fitzpatrick 7a5263e6d0 util/linuxfw: rename ErrorFWModeNotSupported
Go style is for error variables to start with "err" (or "Err")
and for error types to end in "Error".

Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Will Norris 3d56cafd7d
tsnet: add new example serving the Tailscale web client
Updates tailscale/corp#13775

Co-authored-by: Sonia Appasamy <sonia@tailscale.com>
Signed-off-by: Will Norris <will@tailscale.com>
Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Will Norris 6ee85ba412 client/web: fix rendering of node owner profile
Fixes #8837

Signed-off-by: Will Norris <will@tailscale.com>
10 months ago
Sonia Appasamy 2bc98abbd9 client/web: add web client Server struct
Updates tailscale/corp#13775

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Sonia Appasamy 7815fbe17a tailscale/cli: add interactive flow for enabling Funnel
Updates tailscale/corp#10577

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Andrew Lytvynov 90081a25ca
control/controlhttp: remove tstest.Clock from tests (#8830)
These specific tests rely on some timers in the controlhttp code.
Without time moving forward and timers triggering, the tests fail.

Updates #8587

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Aaron Klotz 3d2e35c053 util/winutil/authenticode: fix an inaccurate doc comment
A #cleanup PR

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
10 months ago
Will Norris f9066ac1f4 client/web: extract web client from cli package
move the tailscale web client out of the cmd/tailscale/cli package, into
a new client/web package.  The remaining cli/web.go file is still
responsible for parsing CLI flags and such, and then calls into
client/web. This will allow the web client to be hooked into from other
contexts (for example, from a tsnet server), and provide a dedicated
space to add more functionality to this client.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
10 months ago
Will Norris 69f1324c9e cmd/tailscale: refactor shared utility methods
Refactor two shared functions used by the tailscale cli,
calcAdvertiseRoutes and licensesURL. These are used by the web client as
well as other tailscale subcommands. The web client is being moved out
of the cli package, so move these two functions to new locations.

Updates tailscale/corp#13775

Signed-off-by: Will Norris <will@tailscale.com>
10 months ago
Brad Fitzpatrick b3618c23bf go.toolchain.rev: merge Go 1.21.0 final (non-rc)
Diff:
d149af2823..593313088f

Updates #8419

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick be4eb6a39e derp, net/dns/recursive: use Go 1.21 min
Updates #8419

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 66f27c4beb all: require Go 1.21
Updates #8419

Change-Id: I809b6a4d59d92a2ab6ec587ccbb9053376bf02c2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Maisem Ali 682fd72f7b util/testenv: add new package to hold InTest
Removes duplicated code.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Maisem Ali 3e255d76e1 ipn/ipnlocal: fix profile duplication
We would only look for duplicate profiles when a new login
occurred but when using `--force-reauth` we could switch
users which would end up with duplicate profiles.

Updates #7726

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Maisem Ali 500b9579d5 ipn/ipnlocal: add test to find issues with profile duplication
There are a few situations where we end up with duplicate profiles.
Add tests to identify those situations, fix in followup.

Updates #7726

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Maisem Ali 734928d3cb control/controlclient: make Direct own all changes to Persist
It was being modified in two places in Direct for the auth routine
and then in LocalBackend when a new NetMap was received. This was
confusing, so make Direct also own changes to Persist when a new
NetMap is received.

Updates #7726

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Maisem Ali 6aaf1d48df types/persist: drop duplicated Persist.LoginName
It was duplicated from Persist.UserProfile.LoginName, drop it.

Updates #7726

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
KevinLiang10 ae63c51ff1 wgengine/router: add auto selection heuristic for iptables/nftables
This commit replaces the TS_DEBUG_USE_NETLINK_NFTABLES envknob with
a TS_DEBUG_FIREWALL_MODE that should be set to either 'iptables' or
'nftables' to select firewall mode manually, other wise tailscaled
will automatically choose between iptables and nftables depending on
environment and system availability.

updates: #319
Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
10 months ago
Maisem Ali 17ed2da94d control/controlclient: use ptr.To
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Maisem Ali 82454b57dd ipn/ipnlocal: make tests pass when offline
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
salman aljammaz 25a7204bb4
wgengine,ipn,cmd/tailscale: add size option to ping (#8739)
This adds the capability to pad disco ping message payloads to reach a
specified size. It also plumbs it through to the tailscale ping -size
flag.

Disco pings used for actual endpoint discovery do not use this yet.

Updates #311.

Signed-off-by: salman <salman@tailscale.com>
Co-authored-by: Val <valerie@tailscale.com>
10 months ago
Sonia Appasamy 49896cbdfa ipn/ipnlocal: add profile pic header to serve HTTP proxy
Fixes #8807

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Brad Fitzpatrick c56e94af2d ipn: avoid useless no-op WriteState calls
Rather than make each ipn.StateStore implementation guard against
useless writes (a write of the same value that's already in the
store), do writes via a new wrapper that has a fast path for the
unchanged case.

This then fixes profileManager's flood of useless writes to AWS SSM,
etc.

Updates #8785

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
License Updater a3f11e7710 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
10 months ago
Flakes Updater 10acc06389 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
10 months ago
Claire Wang a17c45fd6e
control: use tstime instead of time (#8595)
Updates #8587
Signed-off-by: Claire Wang <claire@tailscale.com>
10 months ago
License Updater a8e32f1a4b licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
10 months ago
Andrew Lytvynov 371e1ebf07
cmd/dist,release/dist: expose RPM signing hook (#8789)
Plumb a signing callback function to `unixpkgs.rpmTarget` to allow
signing RPMs. This callback is optional and RPMs will build unsigned if
not set, just as before.

Updates https://github.com/tailscale/tailscale/issues/1882

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Andrew Lytvynov eb6883bb5a
go.mod: upgrade nfpm to v2 (#8786)
Upgrade the nfpm package to the latest version to pick up
24a43c5ad7.
The upgrade is from v0 to v2, so there was some breakage to fix.
Generated packages should have the same contents as before.

Updates https://github.com/tailscale/tailscale/issues/1882

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Aaron Klotz 37925b3e7a go.mod, cmd/tailscaled, ipn/localapi, util/osdiag, util/winutil, util/winutil/authenticode: add Windows module list to OS-specific logs that are written upon bugreport
* We update wingoes to pick up new version information functionality
  (See pe/version.go in the https://github.com/dblohm7/wingoes repo);
* We move the existing LogSupportInfo code (including necessary syscall
  stubs) out of util/winutil into a new package, util/osdiag, and implement
  the public LogSupportInfo function may be implemented for other platforms
  as needed;
* We add a new reason argument to LogSupportInfo and wire that into
  localapi's bugreport implementation;
* We add module information to the Windows implementation of LogSupportInfo
  when reason indicates a bugreport. We enumerate all loaded modules in our
  process, and for each one we gather debug, authenticode signature, and
  version information.

Fixes #7802

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
10 months ago
Sonia Appasamy 301e59f398 tailcfg,ipn/localapi,client/tailscale: add QueryFeature endpoint
Updates tailscale/corp#10577

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Brad Fitzpatrick ab7749aed7 go.toolchain.rev: go1.21rc4 (now that VERSION file is updated upstream)
Updates #8419

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Andrew Lytvynov f57cc19ba2
cmd/tailscale/cli: add latest version output to "tailscale version" (#8700)
Add optional `--upstream` flag to `tailscale version` to fetch the
latest upstream release version from `pkgs.tailscale.com`. This is
useful to diagnose `tailscale update` behavior or write other tooling.

Example output:
$ tailscale version --upstream --json
{
	"majorMinorPatch": "1.47.35",
	"short": "1.47.35",
	"long": "1.47.35-t6afffece8",
	"unstableBranch": true,
	"gitCommit": "6afffece8a32509aa7a4dc2972415ec58d8316de",
	"cap": 66,
	"upstream": "1.45.61"
}

Fixes #8669

RELNOTE=adds "tailscale version --upstream"

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
License Updater b4c1f039b6 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
10 months ago
Brad Fitzpatrick c3b979a176 go.toolchain.rev: bump to ~go1.21rc4
Updates tailscale/go#69

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Sonia Appasamy 34bfd7b419 tailcfg: add CapabilityHTTPS const
A #cleanup

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
10 months ago
Brad Fitzpatrick 66e46bf501 ipnlocal, net/*: deprecate interfaces.GetState, use netmon more for it
Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
License Updater 6d65c04987 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
10 months ago
Tom DNetto 767e839db5 all: implement lock revoke-keys command
The revoke-keys command allows nodes with tailnet lock keys
to collaborate to erase the use of a compromised key, and remove trust
in it.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates ENG-1848
10 months ago
Aaron Klotz 7adf15f90e cmd/tailscale/cli, util/winutil/authenticode: flesh out authenticode support
Previously, tailscale upgrade was doing the bare minimum for checking
authenticode signatures via `WinVerifyTrustEx`. This is fine, but we can do
better:

* WinVerifyTrustEx verifies that the binary's signature is valid, but it doesn't
  determine *whose* signature is valid; tailscale upgrade should also ensure that
  the binary is actually signed *by us*.
* I added the ability to check the signatures of MSI files.
* In future PRs I will be adding diagnostic logging that lists details about
  every module (ie, DLL) loaded into our process. As part of that metadata, I
  want to be able to extract information about who signed the binaries.

This code is modelled on some C++ I wrote for Firefox back in the day. See
https://searchfox.org/mozilla-central/rev/27e4816536c891d85d63695025f2549fd7976392/toolkit/xre/dllservices/mozglue/Authenticode.cpp
for reference.

Fixes #8284

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
10 months ago
Denton Gentry ec9213a627 cmd/sniproxy: add client metrics
Count number of sessions, number of DNS queries answered
successfully and in error, and number of http->https redirects.

Updates #1748

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
10 months ago
Andrew Lytvynov eef15b4ffc
cmd/dist,release/dist: sign release tarballs with an ECDSA key (#8759)
Pass an optional PEM-encoded ECDSA key to `cmd/dist` to sign all built
tarballs. The signature is stored next to the tarball with a `.sig`
extension.

Tested this with an `openssl`-generated key pair and verified the
resulting signature.

Updates #8760

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
David Anderson ed46442cb1 client/tailscale/apitype: document never-nil property of WhoIsResponse
Every time I use WhoIsResponse I end up writing mildly irritating nil-checking
for both Node and UserProfile, but it turns out our code guarantees that both
are non-nil in successful whois responses.

Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
Brad Fitzpatrick 5ebb271322 derp/derphttp: add optional Client.BaseContext hook
Like net/http.Server.BaseContext, this lets callers specify a base
context for dials.

Updates tailscale/corp#12702

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Maisem Ali 058d427fa6 tailcfg: add helper to unmarshal PeerCap values
Updates #4217

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
salman aljammaz 68f8e5678e
wgengine/magicsock: remove dead code (#8745)
The nonce value is not read by anything, and di.sharedKey.Seal()
a few lines below generates its own. #cleanup

Signed-off-by: salman <salman@tailscale.com>
10 months ago
License Updater 0554deb48c licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
10 months ago
David Anderson 6114247d0a types/logid: add a Compare method
Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 52212f4323 all: update exp/slices and fix call sites
slices.SortFunc suffered a late-in-cycle API breakage.

Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
Claire Wang 90a7d3066c
derp: use tstime (#8634)
Updates #8587

Signed-off-by: Claire Wang <claire@tailscale.com>
10 months ago
Claire Wang 2315bf246a
ipn: use tstime (#8597)
Updates #8587
Signed-off-by: Claire Wang <claire@tailscale.com>
10 months ago
Andrew Lytvynov c1ecae13ab
ipn/{ipnlocal,localapi}: actually renew certs before expiry (#8731)
While our `shouldStartDomainRenewal` check is correct, `getCertPEM`
would always bail if the existing cert is not expired. Add the same
`shouldStartDomainRenewal` check to `getCertPEM` to make it proceed with
renewal when existing certs are still valid but should be renewed.

The extra check is expensive (ARI request towards LetsEncrypt), so cache
the last check result for 1hr to not degrade `tailscale serve`
performance.

Also, asynchronous renewal is great for `tailscale serve` but confusing
for `tailscale cert`. Add an explicit flag to `GetCertPEM` to force a
synchronous renewal for `tailscale cert`.

Fixes #8725

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
tinku-tailscale aa37be70cf
api.md: update device authorize API docs to allow for deauth (#8728)
Signed-off-by: tinku-tailscale <139132124+tinku-tailscale@users.noreply.github.com>
10 months ago
Charlotte Brandhorst-Satzkorn 35bdbeda9f cli: introduce exit-node subcommand to list and filter exit nodes
This change introduces a new subcommand, `exit-node`, along with a
subsubcommand of `list` and a `--filter` flag.

Exit nodes without location data will continue to be displayed when
`status` is used. Exit nodes with location data will only be displayed
behind `exit-node list`, and in status if they are the active exit node.

The `filter` flag can be used to filter exit nodes with location data by
country.

Exit nodes with Location.Priority data will have only the highest
priority option for each country and city listed. For countries with
multiple cities, a <Country> <Any> option will be displayed, indicating
the highest priority node within that country.

Updates tailscale/corp#13025

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
10 months ago
David Anderson 9d89e85db7 wgengine/magicsock: document mysterious-looking assignment
Updates #cleanup

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 84777354a0 wgengine/magicsock: factor out more separable parts
Updates #8720

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 9a76deb4b0 disco: move disco pcap helper to disco package
Updates tailscale/corp#13464

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson cde37f5307 wgengine/magicsock: factor out peerMap into separate file
Updates tailscale/corp#13464

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson f7016d8c00 wgengine/magicsock: factor out endpoint into its own file
Updates tailscale/corp#13464

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson c2831f6614 wgengine/magicsock: delete unused stuff
Updates tailscale/corp#13464

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
Andrew Lytvynov 9edb848505
cmd/tailscale/cli: implement update on FreeBSD (#8710)
Implement `tailscale update` on FreeBSD. This is much simpler than other
platforms because `pkg rquery` lets us get the version in their repos
without any extra parsing.

Updates #6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Maisem Ali 1ecc16da5f tailcfg,ipn/ipnlocal,wgengine: add values to PeerCapabilities
Define PeerCapabilty and PeerCapMap as the new way of sending down
inter-peer capability information.

Previously, this was unstructured and you could only send down strings
which got too limiting for certain usecases. Instead add the ability
to send down raw JSON messages that are opaque to Tailscale but provide
the applications to define them however they wish.

Also update accessors to use the new values.

Updates #4217

Signed-off-by: Maisem Ali <maisem@tailscale.com>
10 months ago
Andrew Lytvynov 306deea03a
cmd/tailscale/cli,version/distro: update support for Alpine (#8701)
Similar to Arch support, use the latest version info from the official
`apk` repo and don't offer explicit track or version switching.
Add detection for Alpine Linux in version/distro along the way.

Updates #6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
David Anderson 6afffece8a net/art: use more intelligible, go-ish state tracking in table.Get
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 4f14ed2ad6 net/art: use encoding/binary for address bit twiddling
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson f1cd67488d net/art: move slice closer to its use
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 44ad7b3746 net/art: factor out picking the right strideTable for addr family
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 125b982ba5 net/art: make Table.Get alloc-free
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson b76d8a88ae net/art: document return value of strideTable.delete
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson b242e2c2cb net/art: reword confusing function docstring
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 8478358d77 net/art: use "index", not "idx" in function names
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson de5c6ed4be net/art: document valid values of strideTable.prefix
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 736a44264f net/art: fix comment typo
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 1e6f0bb608 net/art: fix slowPrefixTable bugs found by fuzzing
One is a straight "I forgot how to Go" bug, the others are semantic
mismatches with the main implementation around masking the prefixes
passed to insert/delete.

Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson aaca911904 net/art: add another consistency test for insert/delete
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson b145a22f55 net/art: add more exhaustive table testing
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 9cc3f7a3d6 net/art: fix format of debug output
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson ac657caaf1 net/art: add debug hooks to strideTable
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson fcf4d044fa net/art: implement path compression optimization
Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 486195edf0 net/art: make each strideTable track the IP prefix it represents
This is a prerequisite for path compression, so that insert/delete
can determine when compression occurred.

Updates #7781

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
David Anderson 45b5d0983c net/art: fix running tests outside of CI
Updates #7866

Signed-off-by: David Anderson <danderson@tailscale.com>
10 months ago
License Updater 4c05d43008 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
10 months ago
Andrew Lytvynov 894b237a70
cmd/tailscale/cli: implement update for dnf/yum-based distros (#8678)
This is the Fedora family of distros, including CentOS, RHEL and others.
Tested in `fedora:latest` and `centos:7` containers.

Updates #6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
10 months ago
Brad Fitzpatrick f1cc8ab3f9 tailcfg: add UserProfile.Groups
Updates tailscale/corp#13375

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Michael Stapelberg 2a6c237d4c net/dns: overwrite /tmp/resolv.conf on gokrazy
Appliances built using https://gokrazy.org/ have a read-only root file system,
including /etc/resolv.conf, which is a symlink to /tmp/resolv.conf.

The system’s dhcp client overwrites /tmp/resolv.conf instead,
so we need to use this path in Tailscale, too.

related to https://github.com/gokrazy/gokrazy/issues/209

fixes https://github.com/tailscale/tailscale/issues/8689

Signed-off-by: Michael Stapelberg <michael@stapelberg.de>
10 months ago
Brad Fitzpatrick 453620dca1 go.toolchain.rev: bump Go version
For a96a9eddc0

Updates tailscale/corp#12702

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Brad Fitzpatrick 41db1d7bba tailcfg: deprecate Debug, flesh out Node.DERP docs
Updates #docs

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
10 months ago
Jenny Zhang 907c56c200 api.md: add documentation to API endpoint about SCIM group warnings
Updates #8645
Signed-off-by: Jenny Zhang <jz@tailscale.com>
11 months ago
Claire Wang e1bcecc393
logtail: use tstime (#8607)
Updates #8587
Signed-off-by: Claire Wang <claire@tailscale.com>
11 months ago
Joe Tsai bb4b35e923 ssh: ignore io.EOF from sftp.Server.Serve
If the connection provided to sftp.NewServer is closed,
Serve returns the io.EOF error verbatim from io.Reader.Read.
This is an odd error since this is an expected situation,
so we manually ignore io.EOF.
This is somewhat buggy since the sftp package itself
incorrectly reports io.EOF in cases where it should actually
be reporting io.ErrUnexpectedEOF.
See https://github.com/pkg/sftp/pull/554 which patches Serve to
return nil on clean closes and fixes buggy uses of io.ReadFull.

Fixes #8592

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
11 months ago
Brad Fitzpatrick 88cc0ad9f7 util/linuxfw: remove yet-unused code to fix linux/arm64 crash
The util/linuxfw/iptables.go had a bunch of code that wasn't yet used
(in prep for future work) but because of its imports, ended up
initializing code deep within gvisor that panicked on init on arm64
systems not using 4KB pages.

This deletes the unused code to delete the imports and remove the
panic. We can then cherry-pick this back to the branch and restore it
later in a different way.

A new test makes sure we don't regress in the future by depending on
the panicking package in question.

Fixes #8658

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Brad Fitzpatrick 7560435eb5 tstest/deptest: add test-only package to unify negative dep tests
Updates #8658

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Chris Palmer 32d486e2bf
cmd/tailscale/cli: ensure custom UsageFunc is always set (#8665)
Updates #6995

Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
11 months ago
Chris Palmer 3c53bedbbf
cmd/tailscale/cli: limit Darwin-only option to Darwin (#8657) 11 months ago
Anton Tolchanov 388b124513 net/dns: detect when libnss_resolve is used
Having `127.0.0.53` is not the only way to use `systemd-resolved`. An
alternative way is to enable `libnss_resolve` module, which seems to now
be used by default on Debian 12 bookworm.

Fixes #8549

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
11 months ago
Andrew Lytvynov efd6d90dd7
cmd/tailscale/cli: implement update for arch-based distros (#8655)
Arch version of tailscale is not maintained by us, but is generally
up-to-date with our releases. Therefore "tailscale update" is just a
thin wrapper around "pacman -Sy tailscale" with different flags.

Updates #6995

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
11 months ago
Chris Palmer 3f6b0d8c84
cmd/tailscale/cli: make `tailscale update` query `softwareupdate` (#8641)
* cmd/tailscale/cli: make `tailscale update` query `softwareupdate`

Even on macOS when Tailscale was installed via the App Store, we can check for
and even install new versions if people ask explicitly. Also, warn if App Store
AutoUpdate is not turned on.

Updates #6995
11 months ago
Tom DNetto bec9815f02 tka: guard against key-length panics when verifying signatures
In late 2022 a subtle but crucial part of documentation was added to ed25519.Verify: It
will panic if len(publicKey) is not [PublicKeySize].

02ed0e5e67

This change catches that error so it won't lead to a panic.

Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates https://github.com/tailscale/corp/issues/8568
11 months ago
Andrea Gottardo 486ab427b4
VERSION.txt: this is v1.47.0 (#8654)
Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
11 months ago
Andrew Lytvynov 7c04846eac
tsweb: relax CSP for debug handlers (#8649)
Allow inline CSS for debug handlers to make prototyping easier. These
are generally not accessible to the public and the small risk of CSS
injection via user content seems acceptable.

Also allow form submissions on the same domain, instead of banning all
forms. An example of such form is
http://webhooks.corp.ts.net:6359/debug/private-nodes/

Updates #3576

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
11 months ago
Jenny Zhang 9ab70212f4 cmd/gitops-pusher: re-use existing types from acl package
This changes the ACLTestError type to reuse the existing/identical
types from the ACL implementation, to avoid issues in the future if
the two types fall out of sync.

Updates #8645

Signed-off-by: Jenny Zhang <jz@tailscale.com>
11 months ago
Jenny Zhang 6b56e92acc client/tailscale: add warnings slice to ACLTestFailureSummary
Updates #8645

Signed-off-by: Jenny Zhang <jz@tailscale.com>
11 months ago
KevinLiang10 a3c7b21cd1 util/linuxfw: add nftables support
This commit adds nftable rule injection for tailscaled. If tailscaled is
started with envknob TS_DEBUG_USE_NETLINK_NFTABLES = true, the router
will use nftables to manage firewall rules.

Updates: #391

Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
11 months ago
Tom DNetto abcb7ec1ce cmd/tailscale: warn if node is locked out on bringup
Updates https://github.com/tailscale/corp/issues/12718
Signed-off-by: Tom DNetto <tom@tailscale.com>
11 months ago
Tom DNetto 2c782d742c tka: allow checkpoint AUMs to change TKA state
Updates https://github.com/tailscale/corp/issues/8568
Signed-off-by: Tom DNetto <tom@tailscale.com>
11 months ago
Xe Iaso 24f0e91169
tsnet: add examples (#8289)
Closes #8288

Follows the examples from the KB[1].

[1]: https://tailscale.com/kb/1244/tsnet/

Signed-off-by: Xe Iaso <xe@tailscale.com>
11 months ago
Val 1138f4eb5f wgengine/router,ipn/ipnlocal: add MTU field to router config
The MacOS client can't set the MTU when creating the tun due to lack
of permissions, so add it to the router config and have MacOS set it
in the callback using a method that it does have permissions for.

Updates #8219

Signed-off-by: Val <valerie@tailscale.com>
11 months ago
Andrew Dunham 9b5e29761c net/netcheck: ignore PreferredDERP changes that are small
If the absolute value of the difference between the current
PreferredDERP's latency and the best latency is <= 10ms, don't change
it and instead prefer the previous value.

This is in addition to the existing hysteresis that tries to remain
on the previous DERP region if the relative improvement is small, but
handles nodes that have low latency to >1 DERP region better.

Updates #8603

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I1e34c94178f8c9a68a69921c5bc0227337514c70
11 months ago
dependabot[bot] 8bdc03913c
go.mod: bump github.com/docker/distribution (#8121)
Bumps [github.com/docker/distribution](https://github.com/docker/distribution) from 2.8.1+incompatible to 2.8.2+incompatible.
- [Release notes](https://github.com/docker/distribution/releases)
- [Commits](https://github.com/docker/distribution/compare/v2.8.1...v2.8.2)

---
updated-dependencies:
- dependency-name: github.com/docker/distribution
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
11 months ago
Maisem Ali 3304819739 metrics: add histogram support
Add initial histogram support.

Updates tailscale/corp#8641

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
License Updater 9101fabdf8 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
11 months ago
Brad Fitzpatrick 94a51bdd62 go.toolchain.rev: bump Go to Go1.21rc3
Updates #8632

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Will Norris f8b0caa8c2 serve: fix hostname for custom http ports
When using a custom http port like 8080, this was resulting in a
constructed hostname of `host.tailnet.ts.net:8080.tailnet.ts.net` when
looking up the serve handler. Instead, strip off the port before adding
the MagicDNS suffix.

Also use the actual hostname in `serve status` rather than the literal
string "host".

Fixes #8635

Signed-off-by: Will Norris <will@tailscale.com>
11 months ago
Andrew Lytvynov c19b5bfbc3
.github/workflows: add govulncheck workflow (#8623) 11 months ago
Claire Wang 0573f6e953
tstime: add Since method (#8622)
Updates #8463

Signed-off-by: Claire Wang <claire@tailscale.com>
11 months ago
Maisem Ali 60e5761d60 control/controlclient: reset backoff in mapRoutine on netmap recv
We were never resetting the backoff in streaming mapResponses.
The call to `PollNetMap` always returns with an error. Changing that contract
is harder, so manually reset backoff when a netmap is received.

Updates tailscale/corp#12894

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Andrew Dunham 7aba0b0d78 net/netcheck, tailcfg: add DERPHomeParams and use it
This allows providing additional information to the client about how to
select a home DERP region, such as preferring a given DERP region over
all others.

Updates #8603

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I7c4a270f31d8585112fab5408799ffba5b75266f
11 months ago
Andrew Lytvynov 7a82fd8dbe
ipn/ipnlocal: add optional support for ACME Renewal Info (ARI) (#8599) 11 months ago
Andrew Lytvynov 354885a08d
wgengine/netlog: fix nil pointer dereference in logtail (#8598) 11 months ago
Denton Gentry 4f95b6966b cmd/tailscale: remove TS_EXPERIMENT_OAUTH_AUTHKEY guardrail
We've had support for OAuth client keys in `--authkey=...`
for several releases, and we're using it in
https://github.com/tailscale/github-action

Remove the TS_EXPERIMENT_* guardrail, it is fully supported now.

Fixes https://github.com/tailscale/tailscale/issues/8403

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
11 months ago
License Updater c95de4c7a8 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
11 months ago
License Updater 3d70fecde4 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
11 months ago
Andrew Lytvynov 96d7af3469
cmd/derper,tsweb: consistently add HTTP security headers (#8579)
Add a few helper functions in tsweb to add common security headers to handlers. Use those functions for all non-tailscaled-facing endpoints in derper.

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
11 months ago
Maisem Ali 8cda647a0f cmd/testwrapper: handle build failures
`go test -json` outputs invalid JSON when a build fails.
Handle that case by reseting the json.Decode and continuing to read.

Updates #8493

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Joe Tsai 49015b00fe
logtail: fix race condition with sockstats label (#8578)
Updates tailscale/corp#8427

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
11 months ago
Tom DNetto 2bbedd2001 ipn: rename CapTailnetLockAlpha -> CapTailnetLock
Updates tailscale/corp#8568
Signed-off-by: Tom DNetto <tom@tailscale.com>
11 months ago
Andrew Dunham 60ab8089ff logpolicy, various: allow overriding log function
This allows sending logs from the "logpolicy" package (and associated
callees) to something other than the log package. The behaviour for
tailscaled remains the same, passing in log.Printf

Updates #8249

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ie1d43b75fa7281933d9225bffd388462c08a5f31
11 months ago
Flakes Updater cd313e410b go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
11 months ago
Adrian Dewhurst 8c0572e088 go.mod: bump wireguard-go
This pulls in IP checksum optimization on amd64, see
tailscale/wireguard-go@bb2c8f2.

Updates tailscale/corp#9755

Change-Id: I60e932fc4031703b56eb86a676465c5d02d99236
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
11 months ago
Andrew Dunham a7648a6723 net/dnsfallback: run recursive resolver and compare results
When performing a fallback DNS query, run the recursive resolver in a
separate goroutine and compare the results returned by the recursive
resolver with the results we get from "regular" bootstrap DNS. This will
allow us to gather data about whether the recursive DNS resolver works
better, worse, or about the same as "regular" bootstrap DNS.

Updates #5853

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ifa0b0cc9eeb0dccd6f7a3d91675fe44b3b34bd48
11 months ago
Brad Fitzpatrick ffaa6be8a4 tailcfg: add json omitempty to DNSConfig.ExitNodeFilteredSet
We were storing a lot of "ExitNodeFilteredSet":null in the database.

Updates tailscale/corp#1818 (found in the process)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Brad Fitzpatrick 7b1c3dfd28 tailcfg,etc: remove unused tailcfg.Node.KeepAlive field
The server hasn't sent it in ages.

Updates #cleanup

Change-Id: I9695ab0f074ec6fb006e11faf3cdfc5ca049fbf8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Charlotte Brandhorst-Satzkorn f05a9f3e7f tsnet: mark TestLoopbackLocalAPI as flakey
Test flaked in CI.

Updates  #8557

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
11 months ago
Charlotte Brandhorst-Satzkorn 339397ab74 wgengine/magicsock: remove noV4/noV6 check in addrForSendWireGuardLocked
This change removes the noV4/noV6 check from addrForSendWireGuardLocked.

On Android, the client panics when reaching	`rand.Intn()`, likely due to
the candidates list being containing no candidates. The suspicion is
that the `noV4` and the `noV6` are both being triggered causing the
loop to continue.

Updates tailscale/corp#12938
Updates #7826

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
11 months ago
Maisem Ali 9d1a3a995c control/controlclient: use ctx passed down to NoiseClient.getConn
Without this, the client would just get stuck dialing even if the
context was canceled.

Updates tailscale/corp#12590

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Adrian Dewhurst 92fb80d55f tstest, tstime: mockable timers and tickers
This change introduces tstime.Clock which is the start of a mockable
interface for use with testing other upcoming code changes.

Fixes #8463

Change-Id: I59eabc797828809194575736615535d918242ec4
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
11 months ago
Andrea Gottardo 28ee355c56
version: fix tvOS network extension bundle identifier (#8545)
Fixes #8544 and updates #8282.

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
11 months ago
Adrian Dewhurst cd4c71c122 tstest: prepare for Clock API changes
This change introduces tstime.NewClock and tstime.ClockOpts as a new way
to construct tstime.Clock. This is a subset of #8464 as a stepping stone
so that we can update our internal code to use the new API before making
the second round of changes.

Updates #8463

Change-Id: Ib26edb60e5355802aeca83ed60e4fdf806c90e27
Signed-off-by: Adrian Dewhurst <adrian@tailscale.com>
11 months ago
Aaron Klotz fd8c8a3700 client/tailscale: add API for verifying network lock signing deeplink
Fixes #8539

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
11 months ago
Claire Wang 3f1f906b63
words: ack Miles Prower (#8479)
Signed-off-by: Claire Wang <claire@tailscale.com>
11 months ago
Brad Fitzpatrick cb53846717 tempfork/heap: add copy of Go's container/heap but using generics
From Go commit 0a48e5cbfabd679e, then with some generics sprinkled
about.

Updates tailscale/corp#7354

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
David Wolever 0c427f23bd docs/k8s: don't call kubectl directly from Makefile
Instead of calling kubectl directly in k8s Makefile, write the yaml to
stdout so it can be reviewed/edited/etc before manually applying with
kubectl.

Fixes: #8511

Signed-off-by: David Wolever <david@wolever.net>
11 months ago
Brad Fitzpatrick 4d94d72fba metrics: add LabelMap.GetIncrFunc
Updates tailscale/corp#7354

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
David Anderson 0a86705d59 release/dist: add helper to build Go binaries with custom tags
Updates tailscale/corp#12861

Signed-off-by: David Anderson <danderson@tailscale.com>
11 months ago
KevinLiang10 a795b4a641 tsnet: add TestLoopbackSOCKS5 as flaky test
Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
11 months ago
KevinLiang10 6ebd87c669 util/linuxfw: add new arch build constraints
Exclide GOARCHs including: mips, mips64, mips64le, mipsle, riscv64.
These archs are not supported by gvisor.dev/gvisor/pkg/hostarch.

Fixes: #391
Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
11 months ago
Maisem Ali 1ca5dcce15 cmd/testwrapper: stream output results
Previously it would wait for all tests to run before printing anything,
instead stream the results over a channel so that they can be emitted
immediately.

Updates #8493

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Maisem Ali 2e4e7d6b9d cmd/testwrapper: output packages tested
Previously it would only print the failures without providing
more information on which package the failures from.

This commit makes it so that it prints out the package information
as well as the attempt numbers.

```
➜  tailscale.com git:(main) ✗ go run ./cmd/testwrapper ./cmd/...
ok       tailscale.com/cmd/derper
ok       tailscale.com/cmd/k8s-operator
ok       tailscale.com/cmd/tailscale/cli
ok       tailscale.com/cmd/tailscaled
=== RUN   TestFlakeRun
    flakytest.go:38: flakytest: issue tracking this flaky test: https://github.com/tailscale/tailscale/issues/0
    flakytest_test.go:41: First run in testwrapper, failing so that test is retried. This is expected.
--- FAIL: TestFlakeRun (0.00s)
FAIL     tailscale.com/cmd/testwrapper/flakytest

Attempt #2: Retrying flaky tests:

ok       tailscale.com/cmd/testwrapper/flakytest
```

Updates #8493

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Brad Fitzpatrick 79ee6d6e1e tsweb/varz: use default metrics.LabelMap.Label on serialization
To not break Prometheus if the label is unset.

Updates tailscale/corp#12830

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Maisem Ali 2e19790f61 types/views: add JSON marshal/unmarshal and AsMap to Map
This allows cloning a Map as well as marshaling the Map
as JSON.

Updates tailscale/corp#12754

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Joe Tsai e42be5a060
tstime/mono: fix Time.Unmarshal (#8480)
Calling both mono.Now() and time.Now() is slow and
leads to unnecessary precision errors.
Instead, directly compute mono.Time relative to baseMono and baseWall.
This is the opposite calculation as mono.Time.WallTime.

Updates tailscale/corp#8427

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
11 months ago
Maisem Ali 075abd8ec1 tstest: do not panic when a panic logs
The panicLogWriter is too strict, and any panics that occur
get wrapped up in quotes. This makes it so that it will allow
panics to continue writing to Stderr without going through
logger.Logf.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Maisem Ali 12a2221db2 cmd/testwrapper/flakytest: clearly describe why TestFlakeRun fails
Fixes #8474

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Tom DNetto 97ee0bc685 cmd/tailscale: improve error message when signing without a tailnet lock key
Updates #8568
Signed-off-by: Tom DNetto <tom@tailscale.com>
11 months ago
Brad Fitzpatrick b0a984dc26 util/lru: add a package for a typed LRU cache
Updates tailscale/corp#7355

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
License Updater 626f650033 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
11 months ago
License Updater d4413f723d licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
11 months ago
Brad Fitzpatrick cafd9a2bec syncs: add ShardedMap.Mutate
To let callers do atomic/CAS-like operations.

Updates tailscale/corp#7355

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Andrew Dunham ab310a7f60 derp: use new net/tcpinfo package
Updates #8413

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8bf8046517195a6d42cabb32d6ec7f1f79cef860
11 months ago
Andrew Dunham d9eca20ee2 net/tcpinfo: add package to allow fetching TCP information
This package contains platform-independent abstractions for fetching
information about an open TCP connection.

Updates #8413

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I236657b1060d7e6a45efc7a2f6aacf474547a2fe
11 months ago
KevinLiang10 243ce6ccc1 util/linuxfw: decoupling IPTables logic from linux router
This change is introducing new netfilterRunner interface and moving iptables manipulation to a lower leveled iptables runner.

For #391

Signed-off-by: KevinLiang10 <kevinliang@tailscale.com>
11 months ago
Charlotte Brandhorst-Satzkorn 9c64e015e5 tailcfg: update location docs
This change updates the documentation for the fields on the location
struct.

Updates tailscale/corp#12146

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
11 months ago
Ross Zurowski 832f1028c7
net/netutil: parse IP forwarding val as int, not bool (#8455)
This commit updates our IP forwarding parsing logic to allow the less
common but still valid value of `2` to be parsed as `true`, which fixes
an error some users encountered.

Fixes #8375

Signed-off-by: Ross Zurowski <ross@rosszurowski.com>
11 months ago
Brad Fitzpatrick a874f1afd8 all: adjust case of "IPv4" and "IPv6"
Updates #docs

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
valscale e26376194d
ipn/ipnlocal: validate ping type (#8458)
Correct a minor cut-n-paste error that resulted in an invalid or
missing ping type being accepted as a disco ping.

Fixes #8457

Signed-off-by: Val <valerie@tailscale.com>
11 months ago
Brad Fitzpatrick 77f56794c9 types/key: add test for NodePublic.Shard
Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Tom DNetto 1377618dbc tsnet: expose field to configure Wireguard port
Signed-off-by: Tom DNetto <tom@tailscale.com>
Updates #1748
11 months ago
Maisem Ali 8e840489ed cmd/testwrapper: only retry flaky failed tests
Redo the testwrapper to track and only retry flaky tests instead
of retrying the entire pkg. It also fails early if a non-flaky test fails.

This also makes it so that the go test caches are used.

Fixes #7975

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Anton Tolchanov 2cf6e12790 hostinfo: make lxcfs container check more specific
Instead of treating any lxcfs mount as an indicator that we're running
in a container, check for one of the mounts actually used by LXC
containers.

For reference, here's a list of mounts I am seeing in an LXC container:

```
$ grep lxcfs /proc/mounts
lxcfs /proc/cpuinfo fuse.lxcfs rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other 0 0
lxcfs /proc/diskstats fuse.lxcfs rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other 0 0
lxcfs /proc/loadavg fuse.lxcfs rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other 0 0
lxcfs /proc/meminfo fuse.lxcfs rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other 0 0
lxcfs /proc/stat fuse.lxcfs rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other 0 0
lxcfs /proc/swaps fuse.lxcfs rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other 0 0
lxcfs /proc/uptime fuse.lxcfs rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other 0 0
lxcfs /sys/devices/system/cpu/online fuse.lxcfs rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other 0 0
```

Fixes #8444

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
11 months ago
Maisem Ali c11af12a49 .github: actually run tests in CI
Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
11 months ago
Brad Fitzpatrick ba41d14320 syncs: add ShardedMap type
Updates tailscale/corp#7354

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Brad Fitzpatrick 1f57088cbd words: ovuliferous was a bit too much, but...
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Charlotte Brandhorst-Satzkorn 3417ddc00c tailcfg: add location field to hostinfo
This change adds Location field to HostInfo.
Location contains the option for a Country, CountryCode, City, CityCode
and a Priority. Neither of these fields are populated by default.

The Priority field is used to determine the priority an exit
node should be given for use, if the field is set. The higher the value
set, the higher priority the node should be given for use.

Updates tailscale/corp#12146

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
11 months ago
phirework 2a9817da39
api.md: add info for key description (#8429)
Updates tailscale/corp#7773

Signed-off-by: Jenny Zhang <jz@tailscale.com>
11 months ago
David Anderson bfe5623a86 tool/gocross: make gocross behave with pre-release Go toolchains
Also switch the wrapper script to use bash not posix shell. We now
depend on bash elsewhere for saner behavior in esoteric areas, so
might as well use it everywhere for consistency.

Fixes #8425

Signed-off-by: David Anderson <danderson@tailscale.com>
11 months ago
David Anderson 4a58b1c293 release/dist/synology: remove 'version' field from ui/config
As far as I can tell from the DSM documentation and known undocumented
fields, there is no 'version' field in this config file that DSM cares
about.

Updates #8232

Signed-off-by: David Anderson <danderson@tailscale.com>
11 months ago
Brad Fitzpatrick 7c1068b7ac util/goroutines: let ScrubbedGoroutineDump get only current stack
ScrubbedGoroutineDump previously only returned the stacks of all
goroutines. I also want to be able to use this for only the current
goroutine's stack. Add a bool param to support both ways.

Updates tailscale/corp#5149

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
phirework fbacc0bd39
go.toolchain: switch to tailscale.go1.21 (#8415)
Updates #8419

Signed-off-by: Jenny Zhang <jz@tailscale.com>
11 months ago
Brad Fitzpatrick 8b80d63b42 wgengine/magicsock: clarify a log message is a warning, not an error
Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
11 months ago
Joe Tsai 61886e031e
ssh/tailssh: fix double race condition with non-pty command (#8405)
There are two race conditions in output handling.

The first race condition is due to a misuse of exec.Cmd.StdoutPipe.
The documentation explicitly forbids concurrent use of StdoutPipe
with exec.Cmd.Wait (see golang/go#60908) because Wait will
close both sides of the pipe once the process ends without
any guarantees that all data has been read from the pipe.
To fix this, we allocate the os.Pipes ourselves and
manage cleanup ourselves when the process has ended.

The second race condition is because sshSession.run waits
upon exec.Cmd to finish and then immediately proceeds to call ss.Exit,
which will close all output streams going to the SSH client.
This may interrupt any asynchronous io.Copy still copying data.
To fix this, we close the write-side of the os.Pipes after
the process has finished (and before calling ss.Exit) and
synchronously wait for the io.Copy routines to finish.

Fixes #7601

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Maisem Ali <maisem@tailscale.com>
12 months ago
dependabot[bot] d4de60c3ae .github: Bump actions/checkout from 1 to 3
Bumps [actions/checkout](https://github.com/actions/checkout) from 1 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v1...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
12 months ago
Charlotte Brandhorst-Satzkorn 30d9201a11 VERSION.txt: this is v1.45.0
Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
12 months ago
Brad Fitzpatrick 32b8f25ed1 Revert "ssh/tailssh: change to user directory when running login/command"
This reverts commit dc5bc32d8f.

It broke tests. (sadly, ones which we have disabled on CI, but go test
./ssh/tailssh broke)
12 months ago
Aaron Bieber 6829caf6de tsnet: remove extra wording from Store comment 12 months ago
Brad Fitzpatrick e48c0bf0e7 ipn/ipnlocal: quiet some spammy network lock logging
Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
12 months ago
valscale f314fa4a4a
prober: fix data race when altering derpmap (#8397)
Move the clearing of STUNOnly flag to the updateMap() function.

Fixes #8395

Signed-off-by: Val <valerie@tailscale.com>
12 months ago
Derek Burdick dc5bc32d8f ssh/tailssh: change to user directory when running login/command
On redhat 9 and similarly locked down systems, root user does not have
access to a users directory. This fix does not set a directory for the
incubator process and instead sets the directory when the actual process
requested by remote user is executed.

Fixes #8118

Signed-off-by: Derek Burdick <derek-burdick@users.noreply.github.com>
12 months ago
shayne 6697690b55
{cmd/tailscale/cli,ipn}: add http support to tailscale serve (#8358)
Updates #8357

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
12 months ago
Brad Fitzpatrick a2153afeeb types/views: add Slice methods on Slice views
Updates #cleanup for change elsewhere.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
12 months ago
Sonia Appasamy 0f5090c526 ipn/ipnlocal: add docs header to serve HTTP proxy
Adds a `Tailscale-Headers-Info` header whenever the `Tailscale-User-`
headers are filled from the HTTP proxy handler.

Planning on hooking this shorturl up to KB docs about the header
values (i.e. what's a login name vs. display name) and security
considerations to keep in mind while using these headers - notibly
that they can also be filled from external requests that do not hit
tailscaled.

Updates https://github.com/tailscale/tailscale/issues/6954

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
12 months ago
valscale 88097b836a
prober: allow monitoring of nodes marked as STUN only in default derpmap (#8391)
prober uses NewRegionClient() to connect to a derper using a faked up
single-node region, but NewRegionClient() fails to connect if there is
no non-STUN only client in the region. Set the STUN only flag to false
before we call NewRegionClient() so we can monitor nodes marked as
STUN only in the default derpmap.

Updates #11492

Signed-off-by: Val <valerie@tailscale.com>
12 months ago
Maisem Ali 2ae670eb71 ssh/tailssh: work around lack of scontext in SELinux
Trying to SSH when SELinux is enforced results in errors like:

```
➜  ~ ssh ec2-user@<ip>
Last login: Thu Jun  1 22:51:44 from <ip2>
ec2-user: no shell: Permission denied
Connection to <ip> closed.
```

while the `/var/log/audit/audit.log` has
```
type=AVC msg=audit(1685661291.067:465): avc:  denied  { transition } for  pid=5296 comm="login" path="/usr/bin/bash" dev="nvme0n1p1" ino=2564 scontext=system_u:system_r:unconfined_service_t:s0 tcontext=unconfined_u:unconfined_r:unconfined_t:s0 tclass=process permissive=0
```

The right fix here would be to somehow install the appropriate context when
tailscale is installed on host, but until we figure out a way to do that
stop using the `login` cmd in these situations.

Updates #4908

Signed-off-by: Maisem Ali <maisem@tailscale.com>
12 months ago
Ross Zurowski 0ed088b47b
tka: add function for generating signing deeplinks (#8385)
This commit continues the work from #8303, providing a method for a
tka.Authority to generate valid deeplinks for signing devices. We'll
use this to provide the necessary deeplinks for users to sign from
their mobile devices.

Updates #8302

Signed-off-by: Ross Zurowski <ross@rosszurowski.com>
12 months ago
Flakes Updater 909e9eabe4 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
12 months ago
Andrew Dunham b6d20e6f8f go.mod, net/dns/recursive: update github.com/miekg/dns
Updates #cleanup

Change-Id: If4de6a84448a17dd81cc2a8af788bd18c3d0bbe3
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
12 months ago
Maisem Ali 1302295299 Dockerfile.base: install iputils
Fixes #8361

Signed-off-by: Maisem Ali <maisem@tailscale.com>
12 months ago
License Updater c6794dec11 licenses: update android licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
12 months ago
Nick O'Neill c783f28228
tool/gocross: properly set simulator deployment target (#8355)
Fixes tailscale/corp#11876

Signed-off-by: Nick O'Neill <nick@tailscale.com>
12 months ago
License Updater c1cbd41fdc licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
12 months ago
Sonia Appasamy e1cdcf7708 ipn/ipnlocal: add identity headers to HTTP serve proxy
Adds two new headers to HTTP serve proxy:
- `Tailscale-User-Login`: Filled with requester's login name.
- `Tailscale-User-Name`: Filled with requester's display name.

These headers only get filled when the SrcAddr is associated with
a non-tagged (i.e. user-owned) node within the client's Tailnet.

The headers are passed through empty when the request originated
from another tailnet, or the public internet (via funnel).

Updates https://github.com/tailscale/tailscale/issues/6954

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
12 months ago
Claire Wang 80692edcb8
.github/workflows: Add docker build check (#8345)
Fixes #8344

Signed-off-by: Claire Wang <claire@tailscale.com>
12 months ago
Claire Wang 27a0f0a55b
Remove unused dependency from dockerfile (#8343)
Closes #8342

Signed-off-by: Claire Wang <claire@tailscale.com>
12 months ago
Andrea Gottardo 99f17a7135
tka: provide verify-deeplink local API endpoint (#8303)
* tka: provide verify-deeplink local API endpoint

Fixes https://github.com/tailscale/tailscale/issues/8302

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>

Address code review comments

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>

Address code review comments by Ross

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>

* Improve error encoding, fix logic error

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>

---------

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
12 months ago
Graham Christensen 4dda949760 tailscale ping: note that `-c` can take 0 for infinity
Signed-off-by: Graham Christensen <graham@grahamc.com>
12 months ago
Brad Fitzpatrick a076213f58 net/memnet: add optional Listener.NewConn config knob
Updates tailscale/corp#11620

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
12 months ago
License Updater 4451a7c364 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
12 months ago
Maisem Ali fe95d81b43 ipn/ipnlocal,wgengine/netstack: move LocalBackend specifc serving logic to LocalBackend
The netstack code had a bunch of logic to figure out if the LocalBackend should handle an
incoming connection and then would call the function directly on LocalBackend. Move that
logic to LocalBackend and refactor the methods to return conn handlers.

Updates #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
12 months ago
Denton Gentry 5b110685fb wgengine/netstack: increase maxInFlightConnectionAttempts
Address reports of subnet router instability when running in
`--tun=userspace-networking` mode.

Fixes https://github.com/tailscale/corp/issues/12184

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
12 months ago
License Updater 0b3b81b37a licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
12 months ago
dependabot[bot] 6172f9590b .github: Bump golangci/golangci-lint-action from 3.4.0 to 3.6.0
Bumps [golangci/golangci-lint-action](https://github.com/golangci/golangci-lint-action) from 3.4.0 to 3.6.0.
- [Release notes](https://github.com/golangci/golangci-lint-action/releases)
- [Commits](08e2f20817...639cd343e1)

---
updated-dependencies:
- dependency-name: golangci/golangci-lint-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
12 months ago
Brad Fitzpatrick 1543e233e6 net/tstun, tsnet: make happier on WASI
Also fix a js/wasm issue with tsnet in the process. (same issue as WASI)

Updates #8320
Fixes #8315

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
12 months ago
Flakes Updater 167e154bcc go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
12 months ago
Brad Fitzpatrick 67e912824a all: adjust some build tags for wasi
A start.

Updates #8320

Change-Id: I64057f977be51ba63ce635c56d67de7ecec415d1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
12 months ago
Charlotte Brandhorst-Satzkorn 63b1a4e35d words: here comes trouble
If you start hearing everything in auto-tune for the rest of the day,
I take no responsibility for it.

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
12 months ago
Andrew Dunham f077b672e4 net/dns/recursive: add initial implementation of recursive DNS resolver
We've talked in the past about reworking how bootstrap DNS works to
instead do recursive DNS resolution from the root; this would better
support on-prem customers and Headscale users where the DERP servers
don't currently resolve their DNS server. This package is an initial
implementation of recursive resolution for A and AAAA records.

Updates #5853

Change-Id: Ibe974d78709b4b03674b47c4ef61f9a00addf8b4
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
12 months ago
Maisem Ali 2e0aa151c9 ssh/tailssh: add support for remote/reverse port forwarding
This basically allows running services on the SSH client and reaching
them from the SSH server during the session.

Updates #6575

Signed-off-by: Maisem Ali <maisem@tailscale.com>
12 months ago
Andrew Dunham 62130e6b68 util/slicesx: add Partition function
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: If97995ca9ee9fad40f327420dcb1857dd7ea2315
12 months ago
Andrew Dunham 2a9d46c38f wgengine/magicsock: prefer private endpoints to public ones
Switch our best address selection to use a scoring-based approach, where
we boost each address based on whether it's a private IP or IPv6.

For users in cloud environments, this biases endpoint selection towards
using an endpoint that is less likely to cost the user money, and should
be less surprising to users.

This also involves updating the tests to not use private IPv4 addresses;
other than that change, the behaviour should be identical for existing
endpoints.

Updates #8097

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I069e3b399daea28be66b81f7e44fc27b2943d8af
12 months ago
Brad Fitzpatrick eefee6f149 all: use cmpx.Or where it made sense
I left a few out where writing it explicitly was better
for various reasons.

Updates #8296

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
12 months ago
phirework 699996ad6c
go.toolchain.rev: upgrade to Go 1.20.5 (#8304)
Change-Id: I317b6e61d62212efca0e905ea9c626cc24a6912b

Signed-off-by: Jenny Zhang <jz@tailscale.com>
12 months ago
Brad Fitzpatrick 12f8c98823 util/cmpx: add package with cmp-like things from future Go releases
Updates #8296

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
12 months ago
Andrea Gottardo 1c4a047ad0
version: detect tvOS by checking XPC_SERVICE_NAME (#8295)
Another change needed working towards #8282.

Updates https://github.com/tailscale/tailscale/issues/8282

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
12 months ago
Marwan Sulaiman f8f0b981ac portlist: remove async functionality
This PR removes all async functionality from the portlist package
which may be a breaking change for non-tailscale importers. The only
importer within this codebase (LocalBackend) is already using the synchronous
API so no further action needed.

Fixes #8171

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
12 months ago
Andrea Gottardo a353ae079b
tool/gocross: handle TVOS_DEPLOYMENT_TARGET (#8292)
This is needed in order to build our network extension on tvOS. First step for #8282

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
Co-authored-by: Andrea Gottardo <andrea@tailscale.com>
1 year ago
Xe Iaso 43e230d4cd
tsnet: document how to use Dir with multiple servers per process (#8286)
Followup from a conversation on the Gophers slack, also matches the
examples in the tsnet kb.

Closes #8287

Signed-off-by: Xe Iaso <xe@tailscale.com>
1 year ago
Marwan Sulaiman 5dd0b02133 portlist: add a synchronous Poll method
This is a follow up on PR #8172 that adds a synchronous Poll method
which allows for the Poller to be used as a zero value without needing
the constructor. The local backend is also changed to use the new API.
A follow up PR will remove the async functionality from the portlist package.

Updates #8171

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
1 year ago
Derek Burdick d3c8c3dd00 ssh/tailssh: Max Username Length 256 for linux
Max username length is increased to 256 on linux to match /usr/include/bits/local_lim.h

Fixes #8277

Signed-off-by: Derek Burdick <derek-burdick@users.noreply.github.com>
1 year ago
Denton Gentry 64f16f7f38 net/dnscache: use PreferGo on Windows.
Updates https://github.com/tailscale/tailscale/issues/5161

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Denton Gentry 6554a0cbec build_dist.sh: use $go consistently.
The invocation at the end unconditionally used
./tool/go, but the structuring on lines 14-17
sets up to use a different toolchain if the
platform requires it.

Fixes https://github.com/tailscale/tailscale/issues/8156

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
License Updater d17312265e licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Denton Gentry 4321d1d6e9 scripts/installer.sh: add sle-micro-rancher.
Fixes https://github.com/tailscale/tailscale/issues/5633

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
DJRHails 2492ca2900 words: remove misspelling of trex
Signed-off-by: DJRHails <hello@hails.info>
1 year ago
Dominic Black 570cb018da
ipn/localapi: require only read permission for WatchIPNBus (#7798)
Allow calls to `WatchIPNBus` to be permformed by clients with
Readonly permissions. This brings it in line with the permissions
required for `Status`, which also exposes the similar information.

This allows clients to get realtime updates about the tailnet
in their own applications, without needing to actively poll the
`Status` endpoint.

Fixes https://github.com/tailscale/tailscale/issues/7797

Signed-off-by: Dominic Black <dom@encore.dev>
1 year ago
Heiko Rothe dc1d8826a2
ipn/ipnlocal: [serve/funnel] add forwarded host and proto header (#8224)
This replicates the headers also sent by the golang reverse proxy by
default.

Fixes https://github.com/tailscale/tailscale/issues/7061

Signed-off-by: Heiko Rothe <me@heikorothe.com>
1 year ago
Denton Gentry 67882ad35d scripts/installer.sh: add BlendOS support.
Fixes https://github.com/tailscale/tailscale/issues/8100

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Andrew Dunham 07eacdfe92 ipn/ipnlocal: renew certificates based on lifetime
Instead of renewing certificates based on whether or not they're expired
at a fixed 14-day period in the future, renew based on whether or not
we're more than 2/3 of the way through the certificate's lifetime. This
properly handles shorter-lived certificates without issue.

Updates #8204

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I5e82a9cadc427c010d04ce58c7f932e80dd571ea
1 year ago
License Updater d06fac0ede licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Andrew Dunham 9d09c821f7 ipn/ipnlocal: add more logging during profile migration
Updates tailscale/corp#11883

Change-Id: I3a3ca8f25bfefca139115b25ec4161c069da7e4a
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
Aaron Klotz 2aa8299c37 cmd/tailscaled, util/winutil: log our registry keys during tailscaled startup
In order to improve our ability to understand the state of policies and
registry settings when troubleshooting, we enumerate all values in all subkeys.
x/sys/windows does not already offer this, so we need to call RegEnumValue
directly.

For now we're just logging this during startup, however in a future PR I plan to
also trigger this code during a bugreport. I also want to log more than just
registry.

Fixes #8141

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 year ago
Flakes Updater 88ee857bc8 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
1 year ago
Vince Prignano 1a691ec5b2 cmd/k8s-operator: update controller-runtime to v0.15
Fixes #8170

Signed-off-by: Vince Prignano <vince@prigna.com>
1 year ago
Anton Tolchanov 6a156f6243 client/tailscale: support deauthorizing a device
This adds a new `SetAuthorized` method that allows setting device
authorization to true or false. I chose the method name to be consistent
with SetTags.

Updates https://github.com/tailscale/corp/issues/10160

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
dependabot[bot] 525b9c806f .github: bump peter-evans/create-pull-request from 5.0.0 to 5.0.1
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 5.0.0 to 5.0.1.
- [Release notes](https://github.com/peter-evans/create-pull-request/releases)
- [Commits](5b4a9f6a9e...284f54f989)

---
updated-dependencies:
- dependency-name: peter-evans/create-pull-request
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
1 year ago
David Anderson fc5b137d25 release/dist/synology: build hi3535 as armv5, not armv7
This platform is technically an armv7, but has no hardware floating
point unit. armv5 is the only target Go understands to lack floating
point, so use that.

Updates #6860

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 32e0ba5e68 release/dist/synology: build synology packages with cmd/dist
Updates #8217

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Denton Gentry 399a80785e wgengine/netstack: use ping6 on BSD platforms
Various BSD-derived operating systems including macOS and FreeBSD
require that ping6 be used for IPv6 destinations. The "ping" command
does not understand an IPv6 destination.

FreeBSD 13.x and later do handle IPv6 in the regular ping command,
but also retain a ping6 command. We use ping6 on all versions of
FreeBSD.

Fixes https://github.com/tailscale/tailscale/issues/8225

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
David Anderson c0b4a54146 release/dist/cli: correctly handle absolute build outputs in manifest
Some builders return absolute paths to build products already. When that
happens, the manifest writing logic shouldn't tack on another absolute
prefix.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Brad Fitzpatrick c4fe9c536d go.toolchain.rev: bump, again
For https://go-review.googlesource.com/c/go/+/498398

Updates tailscale/go#63
Updates tailscale/go#64

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
valscale 370b2c37e0
tka: fix go vet complaint on copy of lock value in tailchonk_test.go (#8208)
go vet complains when we copy a lock value. Create clone function that
copies everything but the lock value.

Fixes #8207

Signed-off-by: Val <valerie@tailscale.com>
1 year ago
Brad Fitzpatrick cb94ddb7b8 go.toolchain.rev: bump
Updates tailscale/go#63
Updates tailscale/go#64

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrea Gottardo 66f97f4bea
tka: provide authority StateID in NetworkLockStatus response (#8200)
Fixes #8201.

Signed-off-by: Andrea Gottardo <andrea@tailscale.com>
Co-authored-by: Andrea Gottardo <andrea@tailscale.com>
1 year ago
Marwan Sulaiman e32e5c0d0c portlist: add Poller.IncludeLocalhost option
This PR parameterizes receiving loopback updates from the portlist package.
Callers can now include services bound to localhost if they want.
Note that this option is off by default still.

Fixes #8171

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
1 year ago
Will Norris 3d180a16c3 VERSION.txt: this is v1.43.0
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn 4e86857313 ssh/tailssh: add ssh session recording failed event type
This change introduces a SSHSessionRecordingFailed event type
that is used when a session recording fails to start or fails during a
session, and the on failure indicates that it should fail open.

Updates tailscale/corp#9967

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
salman aljammaz 745ee97973
api.md: update device authorized API docs to allow for deauth (#8162)
The authorize device API (/api/v2/device/{deviceID}/authorized)
will soon allow device deauthorisation.

Fixes corp#10160.

Signed-off-by: salman <salman@tailscale.com>
1 year ago
Brad Fitzpatrick a4fd4fd845 ssh/tailssh: fix regression after LDAP support
58ab66ec51 added LDAP support
for #4945 by shelling out to getdent.

It was supposed to fall back to the old method when getdent wasn't
found, but some variable name confusion (uid vs username) meant the
old path wasn't calling the right lookup function (user.LookupId
instead of user.Lookup).

Which meant that changed probably also broke FreeBSD and macOS SSH
support in addition to the reported OpenWRT regression.

The gokrazy support didn't look right either.

Fixes #8180

Change-Id: I273bbe96fe98b2517fbf0335fd476b483c051554
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
James Tucker e3cb982139 words: shell-ebrating crustacean chaos
Hey team! I've been diving deep into the code ocean for the past few
hours, tackling those sneaky race conditions that were threatening our
database. It was quite the crabby situation, but fear not! It's friday
and I've emerged and I'm ready to shell-ebrate with some punny word
additions. 🎉

This commit introduces a shell-shocking array of crustaceans to our word
list. From the lively lobsters to the clever prawns.

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
valscale 5ae786988c
derp: remove default logging of disconnecting clients (#8163)
~97% of the log messages derper outputs are related to the normal
non-error state of a client disconnecting in some manner. Add a
verbose logging feature that only logs these messages when enabled.

Fixes #8024

Signed-off-by: Val <valerie@tailscale.com>
1 year ago
Maisem Ali 0ca8bf1e26 ssh/tailssh: close tty on session close
We were only closing on side of the pty/tty pair.
Close the other side too.

Thanks to @fritterhoff for reporting and debugging the issue!

Fixes #8119

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Gabriel Martinez 03e848e3b5 cmd/k8s-operator: add support for priorityClassName
Updates #8155

Signed-off-by: Gabriel Martinez <gabrielmartinez@sisti.pt>
1 year ago
Derek Kaser 7c88eeba86
cmd/tailscale: allow Tailscale to work with Unraid web interface (#8062)
Updates tailscale/tailscale#8026

Signed-off-by: Derek Kaser <derek.kaser@gmail.com>
1 year ago
Sonia Appasamy f0ee03dfaf cmd/tailscale/cli: [serve] add reset flag
Usage: `tailscale serve reset`

Fixes #8139

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
1 year ago
Brad Fitzpatrick 4664318be2 client/tailscale: revert CreateKey API change, add Client.CreateKeyWithExpiry
The client/tailscale is a stable-ish API we try not to break. Revert
the Client.CreateKey method as it was and add a new
CreateKeyWithExpiry method to do the new thing. And document the
expiry field and enforce that the time.Duration can't be between in
range greater than 0 and less than a second.

Updates #7143
Updates #8124 (reverts it, effectively)

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
shayne 678bb92bb8
cmd/tailscale/cli: [up] fix CreateKey missing argument (#8124)
Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
Matt Brown 9b6e48658f
client: allow the expiry time to be specified for new keys
Adds a parameter for create key that allows a number of seconds
(less than 90) to be specified for new keys.

Fixes https://github.com/tailscale/tailscale/issues/7965

Signed-off-by: Matthew Brown <matthew@bargrove.com>
1 year ago
Maisem Ali 85215ed58a cmd/k8s-operator: handle NotFound secrets
getSingleObject can return `nil, nil`, getDeviceInfo was not handling
that case which resulted in panics.

Fixes #7303

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Brad Fitzpatrick b69059334b util/set: add a basic map-based Set type
We have two other types of Sets here. Add the basic obvious one too.

Needed for a change elsewhere.

Updates #cleanup

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Joe Tsai 84c99fe0d9
logtail: be less aggressive about re-uploads (#8117)
The retry logic was pathological in the following ways:

* If we restarted the logging service, any pending uploads
would be placed in a retry-loop where it depended on backoff.Backoff,
which was too aggresive. It would retry failures within milliseconds,
taking at least 10 retries to hit a delay of 1 second.

* In the event where a logstream was rate limited,
the aggressive retry logic would severely exacerbate the problem
since each retry would also log an error message.
It is by chance that the rate of log error spam
does not happen to exceed the rate limit itself.

We modify the retry logic in the following ways:

* We now respect the "Retry-After" header sent by the logging service.

* Lacking a "Retry-After" header, we retry after a hard-coded period of
30 to 60 seconds. This avoids the thundering-herd effect when all nodes
try reconnecting to the logging service at the same time after a restart.

* We do not treat a status 400 as having been uploaded.
This is simply not the behavior of the logging service.

Updates #tailscale/corp#11213

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
James Tucker da90fab899 net/netcheck: reenable TestBasic on Windows
This test was either fixed by intermediate changes or was mis-flagged as
failing during #7876 triage.

Updates #7876

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
James Tucker ca49b29582 tsnet: reenable TestLoopbackSOCKS5 on Windows
This test was either fixed in the intermediate time or mis-flagged
during the #7876 triage, but is now passing.

Updates #7876

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
Brad Fitzpatrick cb2fd5be92 cmd/tsconnect: fix forgotten API change for wasm
Fix regression from 6e967446e4

Updates #8036

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
David Anderson d27a6e1c53 tool/gocross: fix incorrect relpath usage in bootstrap script
The subshell in which gocross gets built cd's to the corp checkout dir
near the top, so all future references to corp repository files should
be simple relative paths, and not reference $repo_root. When $repo_root
is an absolute path, it doesn't matter and everything works out, but on
some OSes and shells and invocations, $repo_root is a completely relative
path that is invalidated by the "cd".

Fixes tailscale/corp#11183

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Brad Fitzpatrick 4f454f4122 util/codegen: support embedded fields
I noticed cmd/{cloner,viewer} didn't support structs with embedded
fields while working on a change in another repo. This adds support.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Will Norris ea84fc9ad2 net/sockstats: wait before reporting battery usage
Wait 2 minutes before we start reporting battery usage. There is always
radio activity on initial startup, which gets reported as 100% high
power usage.  Let that settle before we report usage data.

Updates tailscale/corp#9230

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
salman 1ce08256c0 release/dist: add deb/rpm arch mappings for mipses
According to https://wiki.debian.org/SupportedArchitectures Debian does
not support big-endian mips64, so that one remains disabled.

According to https://fedoraproject.org/wiki/Architectures Fedora only
supports little-endian mips, so leaving both big-endian ones out too.

Updates #8005.

Signed-off-by: salman <salman@tailscale.com>
1 year ago
Craig Rodrigues 827abbeeaa cmd/k8s-operator: print version in startup logs
Fixes: #7813

Signed-off-by: Craig Rodrigues <rodrigc@crodrigues.org>
1 year ago
License Updater d1ecb1f43b licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Brad Fitzpatrick a743b66f9d ssh/tailssh: move some user-related code into new user.go
The previous commit 58ab66e added ssh/tailssh/user.go as part of
working on #4945. So move some more user-related code over to it.

Updates #cleanup

Change-Id: I24de66df25ffb8f867e1a0a540d410f9ef16d7b0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 58ab66ec51 ssh/tailssh: support LDAP users for Tailscale SSH
Fixes #4945

Change-Id: Ie013cb47684cb87928a44f92c66352310bfe53f1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Chenyang Gao e8b06b2232 version: properly handle vcs.modified when it's "false"
Current code will set the "dirty" field of VersionInfo always "true"
if vcs.modified flag is there. No matter whether the flag is "true" or
"false".  It will make sense to set this field due to vcs.modified
value, not only the existence of the key.

Signed-off-by: Chenyang Gao <gps949@outlook.com>
1 year ago
License Updater df8b1b2179 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
License Updater 4d730e154c licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Chenyang Gao b9fb8ac702 fix sys.Set(router) issue will crash the daemon in some OSs
Signed-off-by: Chenyang Gao <gps949@outlook.com>

in commit 6e96744, the tsd system type has been added.
Which will cause the daemon will crash on some  OSs (Windows, darwin and so on).
The root cause is that on those OSs, handleSubnetsInNetstack() will return true and set the conf.Router with a wrapper. 
Later in NewUserspaceEngine() it will do subsystem set and found that early set router mismatch to current value, then panic.
1 year ago
James Tucker 5c38f0979e tsweb/promvarz: fix repeated expvar definition in test
expvar can only be defined once, so running tests with a repeat counter
will fail if the variables are defined inside of the test function.

Observed failure:

```
--- FAIL: TestHandler (0.00s)
panic: Reuse of exported var name: gauge_promvarz_test_expvar
 [recovered]
        panic: Reuse of exported var name: gauge_promvarz_test_expvar

goroutine 9 [running]:
testing.tRunner.func1.2({0x100f267e0, 0x1400026e770})
        /usr/local/go/src/testing/testing.go:1526 +0x1c8
testing.tRunner.func1()
        /usr/local/go/src/testing/testing.go:1529 +0x364
panic({0x100f267e0, 0x1400026e770})
        /usr/local/go/src/runtime/panic.go:884 +0x1f4
log.Panicln({0x140000b8e20?, 0x1a?, 0x1400026e750?})
        /usr/local/go/src/log/log.go:398 +0x60
expvar.Publish({0x100e2b21d, 0x1a}, {0x100fd7a08?, 0x140000232c0})
        /usr/local/go/src/expvar/expvar.go:284 +0xc0
expvar.NewInt(...)
        /usr/local/go/src/expvar/expvar.go:304
tailscale.com/tsweb/promvarz.TestHandler(0x14000082b60)
        /Users/charlotte/ts-src/tailscale/tsweb/promvarz/promvarz_test.go:18 +0x5c
testing.tRunner(0x14000082b60, 0x100fd5858)
        /usr/local/go/src/testing/testing.go:1576 +0x104
created by testing.(*T).Run
        /usr/local/go/src/testing/testing.go:1629 +0x370
FAIL    tailscale.com/tsweb/promvarz    0.149s
```

Fixes #8065
Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn 024d48d9c1 tailcfg: bump capability version
This change bumps the capability version to 62, after support for
sending SSHEventNotificationRequests to control via noise for failure
events was introduced.

Updates tailscale/corp#9967

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn 29ded8f9f9 ssh/tailssh,tailcfg: add connID to ssheventnotifyrequest and castheader
This change adds a ConnectionID field to both SSHEventNotifyRequest and
CastHeader that identifies the ID of a connection to the SSH server.

Updates tailscale/corp#9967

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn 68307c1411 ssh/tailssh: send ssh event notifications on recording failures
This change sends an SSHEventNotificationRequest over noise when a
SSH session is set to fail closed and the session is unable to start
because a recorder is not available or a session is terminated because
connection to the recorder is ended. Each of these scenarios have their
own event type.

Updates tailscale/corp#9967

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn 2804327074 tailcfg: update rename SSHFailureNotifyRequest and add EventType
This change renames SSHFailureNotifyRequest to SSHEventNotifyRequest
to better reflect the additional events we could add in the future.
This change also adds an EventType used to catagories the events.

Updates tailscale/corp#9967

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn 8d3d48e000 ipn/ipnlocal: add NodeKey func to return the public node NodeKey
This change introduces a NodeKey func on localbackend that returns the
public node key.

Updates tailscale/corp#9967

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Brad Fitzpatrick 8864112a0c ipn/ipnlocal: bound how long cert fetchher checks for existing DNS records
It was supposed to be best effort but in some cases (macsys at least,
per @marwan-at-work) it hangs and exhausts the whole context.Context
deadline so we fail to make the SetDNS call to the server.

Updates #8067
Updates #3273 etc

Change-Id: Ie1f04abe9689951484748aecdeae312afbafdb0f
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
James Tucker 9ed3a061c3 net/netns: fix segv when no tailscale interface is found
`interfaces.Tailscale()` returns all zero values when it finds no
Tailscale interface and encounters no errors. The netns package was
treating no error as a signal that it would receive a non-zero pointer
value leading to nil pointer dereference.

Observed in:

```
--- FAIL: TestGetInterfaceIndex (0.00s)
    --- FAIL: TestGetInterfaceIndex/IP_and_port (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
        panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x1029eb7d8]

goroutine 7 [running]:
testing.tRunner.func1.2({0x102a691e0, 0x102bc05c0})
        /Users/raggi/.cache/tailscale-go/src/testing/testing.go:1526 +0x1c8
testing.tRunner.func1()
        /Users/raggi/.cache/tailscale-go/src/testing/testing.go:1529 +0x384
panic({0x102a691e0, 0x102bc05c0})
        /Users/raggi/.cache/tailscale-go/src/runtime/panic.go:884 +0x204
tailscale.com/net/netns.getInterfaceIndex(0x14000073f28, 0x1028d0284?, {0x1029ef3b7, 0xa})
        /Users/raggi/src/github.com/tailscale/tailscale/net/netns/netns_darwin.go:114 +0x228
tailscale.com/net/netns.TestGetInterfaceIndex.func2(0x14000138000)
        /Users/raggi/src/github.com/tailscale/tailscale/net/netns/netns_darwin_test.go:37 +0x54
testing.tRunner(0x14000138000, 0x140000551b0)
        /Users/raggi/.cache/tailscale-go/src/testing/testing.go:1576 +0x10c
created by testing.(*T).Run
        /Users/raggi/.cache/tailscale-go/src/testing/testing.go:1629 +0x368
FAIL    tailscale.com/net/netns 0.824s
```

Fixes #8064

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
Brad Fitzpatrick 6e967446e4 tsd: add package with System type to unify subsystem init, discovery
This is part of an effort to clean up tailscaled initialization between
tailscaled, tailscaled Windows service, tsnet, and the mac GUI.

Updates #8036

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Derek Kaser 0d7303b798 various: add detection and Taildrop for Unraid
Updates tailscale/tailscale#8025

Signed-off-by: Derek Kaser <derek.kaser@gmail.com>
1 year ago
Flakes Updater d1ce7a9b5e go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
1 year ago
James Tucker 5def4f4a1c go.mod: bump goreleaser deps
Periodic update for start of cycle. goreleaser is not updated to v2 yet,
but indirects updated.

Updates #8043

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Flakes Updater 1c6ff310ae go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
1 year ago
James Tucker 48605226dd go.mod: bump gvisor
Periodic update for start of cycle.

Updates #8043

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Maisem Ali f46c1aede0 go.mod: bump k8s libs
The key is to update sigs.k8s.io/controller-runtime and let it update others.

Updates #8043

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Brad Fitzpatrick 73d128238e envknob: support tailscaled-env.txt on macOS too
Updates #3707

Co-authored-by: Marwan Sulaiman <marwan@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Anton Tolchanov 787fc41fa4 scripts/installer.sh: check connectivity with pkgs.tailscale.com
Installer script relies on pkgs.tailscale.com being reachable, both for
checking what Linux distros are supported, but also for actually
downloading repo configuration files, gpg keys and packages themselves.

This change adds a simple reachability check which will print an error
message when pkgs.tailscale.com is not reachable.

Fixes https://github.com/tailscale/corp/issues/8952

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Flakes Updater 5783adcc6f go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply+flakes-updater@tailscale.com>
1 year ago
License Updater 503b6dd8be licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Brad Fitzpatrick 9e9ea6e974 go.mod: bump all deps possible that don't break the build
This holds back gvisor, kubernetes, goreleaser, and esbuild, which all
had breaking API changes.

Updates #8043
Updates #7381
Updates #8042 (updates u-root which adds deps)

Change-Id: I889759bea057cd3963037d41f608c99eb7466a5b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
M. J. Fromberger 459744c9ea
.github: mark bots for exemption by issuebot (#8041)
#cleanup

Change-Id: I13757ee20240166af72606d166e840ae3ee797d7
Signed-off-by: M. J. Fromberger <fromberger@tailscale.com>
1 year ago
License Updater 7675d323fa licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
dependabot[bot] 270942094f build(deps): bump github.com/docker/docker
Bumps [github.com/docker/docker](https://github.com/docker/docker) from 20.10.16+incompatible to 20.10.24+incompatible.
- [Release notes](https://github.com/docker/docker/releases)
- [Commits](https://github.com/docker/docker/compare/v20.10.16...v20.10.24)

---
updated-dependencies:
- dependency-name: github.com/docker/docker
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
1 year ago
Maisem Ali be190e990f ssh/tailssh: restore support for recording locally
We removed it earlier in 916aa782af, but we still want to support it for some time longer.

Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Brad Fitzpatrick 4d7927047c wgengine/magicsock: annotate, skip flaky TestIsWireGuardOnlyPickEndpointByPing
Updates #8037
Updates #7826

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn ddb4040aa0
wgengine/magicsock: add address selection for wireguard only endpoints (#7979)
This change introduces address selection for wireguard only endpoints.
If a endpoint has not been used before, an address is randomly selected
to be used based on information we know about, such as if they are able
to use IPv4 or IPv6. When an address is initially selected, we also
initiate a new ICMP ping to the endpoints addresses to determine which
endpoint offers the best latency. This information is then used to
update which endpoint we should be using based on the best possible
route. If the latency is the same for a IPv4 and an IPv6 address, IPv6
will be used.

Updates #7826

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Brad Fitzpatrick c1e6888fc7 derp: add a README.md with some docs
Updates #docs

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Maisem Ali 3ae7140690 net/tstun: handle exit nodes in NAT configs
In the case where the exit node requires SNAT, we would SNAT all traffic not just the
traffic meant to go through the exit node. This was a result of the default route being
added to the routing table which would match basically everything.

In this case, we need to account for all peers in the routing table not just the ones
that require NAT.

Fix and add a test.

Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Andrew Dunham bcf7b63d7e wgengine/magicsock: add hysteresis to endpoint selection
Avoid selecting an endpoint as "better" than the current endpoint if the
total latency improvement is less than 1%. This adds some hysteresis to
avoid flapping between endpoints for a minimal improvement in latency.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: If8312e1768ea65c4b4d4e13d8de284b3825d7a73
1 year ago
Tom DNetto c5bf868940 ssh/tailssh: improve debug logging around revoked sessions
Updates https://github.com/tailscale/corp/issues/10943
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Andrew Dunham 42fd964090 control/controlclient: use dnscache.Resolver for Noise client
This passes the *dnscache.Resolver down from the Direct client into the
Noise client and from there into the controlhttp client. This retains
the Resolver so that it can share state across calls instead of creating
a new resolver.

Updates #4845
Updates #6110

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ia5d6af1870f3b5b5d7dd5685d775dcf300aec7af
1 year ago
License Updater 979d29b5f5 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Anton Tolchanov 1f4a34588b .github: test installer script in CI in docker
Every time we change `installer.sh`, run it in a few docker
containers based on different Linux distros, just as a simple test.

Also includes a few changes to the installer script itself to make
installation work in docker:
- install dnf config-manager command before running it
- run zypper in non-interactive mode
- update pacman indexes before installing packages

Updates https://github.com/tailscale/corp/issues/8952

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Denton Gentry a82f275619 cmd/sniproxy: Set App name in tsnet hostinfo
Updates #1748
Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
James Tucker b3c3a9f174 syncs: add Map.Len to get the length of the Map
I need this for a corp change where I have a set as a queue, and make a
different decisison if the set is empty.

Updates tailscale/corp#10344

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
ayanamist 042f82ea32 build_dist.sh: make cross-compilation friendly for env CC specified
Signed-off-by: ayanamist <ayanamist@gmail.com>
1 year ago
dependabot[bot] 633d08bd7b .github: Bump actions/setup-go from 3 to 4
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
1 year ago
James Tucker d35ce1add9 syncs: add documentation to Map.Range
Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn c3ab36cb9d
words: charlotte 1 spell-checking-linter 0 (#7993)
Can't have a dupe when the dupe is wrong. Clearly we need to up
our spell checking game. Did anyone say AI?

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
James Tucker 8032b966a1 .github/workflows: add recency bias to action cache keys
The action cache restore process either matches the restore key pattern
exactly, or uses a matching prefix with the most recent date.

If the restore key is an exact match, then no updates are uploaded, but
if we've just computed tests executions for more recent code then we
will likely want to use those results in future runs.

Appending run_id to the cache key will give us an always new key, and
then we will be restore a recently uploaded cache that is more likely
has a higher overlap with the code being tested.

Updates #7975

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Kyle Carberry d78b334964 cmd/derper: disable http2
DERP doesn't support HTTP/2. If an HTTP/2 proxy was placed in front of
a DERP server requests would fail because the connection would
be initialized with HTTP/2, which the DERP client doesn't support.

Signed-off-by: Kyle Carberry <kyle@carberry.com>
1 year ago
Charlotte Brandhorst-Satzkorn 161d1d281a
net/ping,netcheck: add v6 pinging capabilities to pinger (#7971)
This change adds a v6conn to the pinger to enable sending pings to v6
addrs.

Updates #7826

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Denton Gentry 1145b9751d VERSION.txt: this is v1.41.0
Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Brad Fitzpatrick 1e876a3c1d ipn/ipnlocal: fix fmt format arg type mismatch in log line
It was printing like "v0xxxxxxxx" after version.Long became a func
in 8b2ae47c31.

Fixes #7976

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Maisem Ali a8f10c23b2 cmd/tailscale/cli: [up] reuse --advertise-tags for OAuth key generation
We need to always specify tags when creating an AuthKey from an OAuth key.

Check for that, and reuse the `--advertise-tags` param.

Updates #7982

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Brad Fitzpatrick b2b5379348 cmd/tailscale/cli: [up] change oauth authkey format
Updates #7982

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 13de36303d cmd/tailscale/cli: [up] add experimental oauth2 authkey support
Updates #7982

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
James Tucker 095d3edd33 ipn/ipnlocal: reenable profile tests on Windows
This fix does not seem ideal, but the test infrastructure using a local
goos doesn't seem to avoid all of the associated challenges, but is
somewhat deeply tied to the setup.

The core issue this addresses for now is that when run on Windows there
can be no code paths that attempt to use an invalid UID string, which on
Windows is described in [1].

For the goos="linux" tests, we now explicitly skip the affected
migration code if runtime.GOOS=="windows", and for the Windows test we
explicitly use the running users uid, rather than just the string
"user1". We also now make the case where a profile exists and has
already been migrated a non-error condition toward the outer API.

Updates #7876

[1] https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
James Tucker 43819309e1 .github/workflows: split tests and benchmarks for caching
Benchmark flags prevent test caching, so benchmarks are now executed
independently of tests.

Fixes #7975

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Maisem Ali 1b8a0dfe5e ssh/tailssh: also handle recording upload failure during writes
Previously we would error out when the recording server disappeared after the in memory
buffer filled up for the io.Copy. This makes it so that we handle failing open correctly
in that path.

Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
shayne 018a382729
cmd/tailscale/cli: [serve] fix MinGW path conversion (#7964)
Fixes #7963

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
License Updater 2e07245384 licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
License Updater aa87e999dc licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Maisem Ali f58751eb2b net/packet: add NAT support for DCCP and GRE
Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Marwan Sulaiman ce11c82d51 ipn/store/awsstore: persist state with intelligent tiering
Fixes #6784

This PR makes it so that we can persist the tailscaled state with
intelligent tiering which increases the capacity from 4kb to 8kb

Signed-off-by: Marwan Sulaiman <marwan@tailscale.com>
1 year ago
Brad Fitzpatrick 90ba26cea1 net/netcheck: fix crash when IPv6 kinda but not really works
Looks like on some systems there's an IPv6 address, but then opening
a IPv6 UDP socket fails later. Probably some firewall. Tolerate it
better and don't crash.

To repro: check the "udp6" to something like "udp7" (something that'll
fail) and run "go run ./cmd/tailscale netcheck" on a machine with
active IPv6. It used to crash and now it doesn't.

Fixes #7949

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Maisem Ali 7778d708a6 ssh/tailssh: handle dialing multiple recorders and failing open
This adds support to try dialing out to multiple recorders each
with a 5s timeout and an overall 30s timeout. It also starts respecting
the actions `OnRecordingFailure` field if set, if it is not set
it fails open.

Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali f66ddb544c tailcfg: add SSHRecorderFailureAction and SSHRecordingFailureNotifyRequest
This allows control to specify how to handle situations where the recorder
isn't available.

Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Flakes Updater e3b2250e26 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Andrew Dunham 6f521c138d tailcfg: add CanPort80 field to DERPNode
A follow-up PR will start using this field after we set it in our
production DERPMap.

Updates #7925

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Idb41b79e6055dddb8944f79d91ad4a186ace98c7
1 year ago
Andrew Dunham 04a3118d45 net/tstun: add tests for captureHook
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I630f852d9f16c951c721b34f2bc4128e68fe9475
1 year ago
Denton Gentry c791e64881 scripts/installer: add Deepin, RisiOS.
Fixes https://github.com/tailscale/tailscale/issues/7862
Fixes https://github.com/tailscale/tailscale/issues/7899

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Mihai Parparita 7330aa593e all: avoid repeated default interface lookups
On some platforms (notably macOS and iOS) we look up the default
interface to bind outgoing connections to. This is both duplicated
work and results in logspam when the default interface is not available
(i.e. when a phone has no connectivity, we log an error and thus cause
more things that we will try to upload and fail).

Fixed by passing around a netmon.Monitor to more places, so that we can
use its cached interface state.

Fixes #7850
Updates #7621

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Will Norris 7f17e04a5a log/sockstatlog: bump logInterval to 10 seconds
We are seeing indications that some devices are still getting into an
upload loop.  Bump logInterval in case these devices are on slow
connections that are taking more than 3 seconds to uploads sockstats.

Updates #7719

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Mihai Parparita 4722f7e322 all: move network monitoring from wgengine/monitor to net/netmon
We're using it in more and more places, and it's not really specific to
our use of Wireguard (and does more just link/interface monitoring).

Also removes the separate interface we had for it in sockstats -- it's
a small enough package (we already pull in all of its dependencies
via other paths) that it's not worth the extra complexity.

Updates #7621
Updates #7850

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Andrew Dunham 3ede3aafe4 ipn/localapi: also verify STUN queries work in 'debug derp'
Updates #6526

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I274b7ed53ee0be3fb94fdb00cafe06a1d676e1cf
1 year ago
James Tucker f844791e15 safesocket: enable test to run on Windows unpriviliged
I manually tested that the code path that relaxes pipe permissions is
not executed when run with elevated priviliges, and the test also passes
in that case.

Updates #7876

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
James Tucker cd35a79136 syncs: relax TestWatchMultipleValues timing on Windows
The test is re-enabled for Windows with a relaxed time assertion.

On Windows the runtime poller currently does not have sufficient
resolution to meet the normal requirements for this test.

See https://github.com/golang/go/issues/44343 for background.

Updates #7876

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
Andrew Dunham f85dc6f97c
ci: add more lints (#7909)
This is a follow-up to #7905 that adds two more linters and fixes the corresponding findings. As per the previous PR, this only flags things that are "obviously" wrong, and fixes the issues found.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8739bdb7bc4f75666a7385a7a26d56ec13741b7c
1 year ago
dependabot[bot] 5acc7c4b1e .github: Bump ruby/action-slack from 3.0.0 to 3.2.1
Bumps [ruby/action-slack](https://github.com/ruby/action-slack) from 3.0.0 to 3.2.1.
- [Release notes](https://github.com/ruby/action-slack/releases)
- [Commits](https://github.com/ruby/action-slack/compare/v3.0.0...v3.2.1)

---
updated-dependencies:
- dependency-name: ruby/action-slack
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
1 year ago
dependabot[bot] c328770184 .github: Bump peter-evans/create-pull-request from 4.2.4 to 5.0.0
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 4.2.4 to 5.0.0.
- [Release notes](https://github.com/peter-evans/create-pull-request/releases)
- [Commits](38e0b6e68b...5b4a9f6a9e)

---
updated-dependencies:
- dependency-name: peter-evans/create-pull-request
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
1 year ago
License Updater 588a234fdc licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Maisem Ali c3ef6fb4ee ipn/ipnlocal: handle masquerade addresses in PeerAPI
Without this, the peer fails to do anything over the PeerAPI if it
has a masquerade address.

```
Apr 19 13:58:15 hydrogen tailscaled[6696]: peerapi: invalid request from <ip>:58334: 100.64.0.1/32 not found in self addresses
```

Updates #8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 85de580455 net/tsdial: do not use proxies when dialing out to PeerAPI
Found this when adding a test that does a ping over PeerAPI.

Our integration tests set up a trafficTrap to ensure that tailscaled
does not call out to the internet, and it does so via a HTTP_PROXY.

When adding a test for pings over PeerAPI, it triggered the trap and investigation
lead to the realization that we were not removing the Proxy when trying to
dial out to the PeerAPI.

Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Mihai Parparita d0906cda97 net/sockstats: expose debug info
Exposes some internal state of the sockstats package via the C2N and
PeerAPI endpoints, so that it can be used for debugging. For now this
includes the estimated radio on percentage and a second-by-second view
of the times the radio was active.

Also fixes another off-by-one error in the radio on percentage that
was leading to >100% values (if n seconds have passed since we started
to monitor, there may be n + 1 possible seconds where the radio could
have been on).

Updates tailscale/corp#9230

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Will Norris 7c386ca6d2 net/sockstats: fix calculation of radio power usage
When splitting the radio monitor usage array, we were splitting at now %
3600 to get values into chronological order.  This caused the value for
the final second to be included at the beginning of the ordered slice
rather than the end.  If there was activity during that final second, an
extra five seconds of high power usage would get recorded in some cases.
This could result in a final calculation of greater than 100% usage.

This corrects that by splitting values at (now+1 % 3600).

This also simplifies the percentage calculation by always rounding
values down, which is sufficient for our usage.

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
License Updater 7f057d7489 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Mihai Parparita c7cea825ae net/netns: don't log errors when we can't get the default route on Darwin
It's somewhat common (e.g. when a phone has no reception), and leads to
lots of logspam.

Updates #7850

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Andrew Dunham 280255acae
various: add golangci-lint, fix issues (#7905)
This adds an initial and intentionally minimal configuration for
golang-ci, fixes the issues reported, and adds a GitHub Action to check
new pull requests against this linter configuration.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8f38fbc315836a19a094d0d3e986758b9313f163
1 year ago
Joe Tsai ff1b35ec6c
net/connstats: exclude traffic with internal Tailscale service (#7904)
Exclude traffic with 100.100.100.100 (for IPv4) and
with fd7a:115c:a1e0::53 (for IPv6) since this traffic with the
Tailscale service running locally on the node.
This traffic never left the node.

It also happens to be a high volume amount of traffic since
DNS requests occur over UDP with each request coming from a
unique port, thus resulting in many discrete traffic flows.

Fixes tailscale/corp#10554

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Mihai Parparita 9a655a1d58 net/dnsfallback: more explicitly pass through logf function
Redoes the approach from #5550 and #7539 to explicitly pass in the logf
function, instead of having global state that can be overridden.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
dependabot[bot] 28cb1221ba .github: Bump actions/setup-go from 3 to 4
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
1 year ago
Brad Fitzpatrick d5a870b4dc wgengine/monitor: add --monitor-duration flag to opt-in TestMonitorMode
TestMonitorMode skips by default, without the --monitor flag, and then
it previously ran forever. This adds an option --monitor-duration flag
that defaults to zero (run forever) but if non-zero bounds how long
the tests runs. This means you can then also use e.g. `go test
--cpuprofile` and capture a CPU/mem profile for a minute or two.

Updates #7621

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 162488a775 net/interfaces: cache "home" router lookup on big Linux routers
This is a continuation of the earlier 2a67beaacf but more aggressive;
this now remembers that we failed to find the "home" router IP so we
don't try again later on the next call.

Updates #7621

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
James Tucker c5150eae67 net/netcheck: reenable TestNodeAddrResolve on Windows
Updates #7876

Co-authored-by: Andrew Dunham <andrew@du.nham.ca>
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Signed-off-by: James Tucker <james@tailscale.com>
Change-Id: Idb2e6cc2edf6ca123b751d6c8f8729b0cba86023
1 year ago
Andrew Dunham 80b138f0df wgengine/magicsock: keep advertising endpoints after we stop discovering them
Previously, when updating endpoints we would immediately stop
advertising any endpoint that wasn't discovered during
determineEndpoints. This could result in, for example, a case where we
performed an incremental netcheck, didn't get any of our three STUN
packets back, and then dropped our STUN endpoint from the set of
advertised endpoints... which would result in clients falling back to a
DERP connection until the next call to determineEndpoints.

Instead, let's cache endpoints that we've discovered and continue
reporting them to clients until a timeout expires. In the above case
where we temporarily don't have a discovered STUN endpoint, we would
continue reporting the old value, then re-discover the STUN endpoint
again and continue reporting it as normal, so clients never see a
withdrawal.

Updates tailscale/coral#108

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I42de72e7418ab328a6c732bdefc74549708cf8b9
1 year ago
Brad Fitzpatrick 4b49ca4a12 wgengine/magicsock: update comments on what implements conn.Bind
The comment still said *magicsock.Conn implemented wireguard-go conn.Bind.
That wasn't accurate anymore.

A doc #cleanup.

Change-Id: I7fd003b939497889cc81147bfb937b93e4f6865c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 10f1c90f4d wgengine/magicsock, types/nettype, etc: finish ReadFromUDPAddrPort netip migration
So we're staying within the netip.Addr/AddrPort consistently and
avoiding allocs/conversions to the legacy net addr types.

Updates #5162

Change-Id: I59feba60d3de39f773e68292d759766bac98c917
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 29f7df9d8f wgengine/magicsock, etc: remove mostly unused WriteTo methods
Updates #2331
Updates #5162

Change-Id: I8291884425481eeaedde38a54adfd8ed7292a497
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 83c41f3697 net/netcheck: remove unused method from interface
Updates #2331
Updates #5162

Change-Id: I77ff956c2d59bde611d47523659a07afb4a6da2d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
James Tucker 20f17d6e7b wgengine/magicsock: reenable magicsock tests on Windows
These tests are passing locally and on CI. They had failed earlier in
the day when first fixing up CI, and it is not immediately clear why. I
have cycled IPv6 support locally, but this should not have a substantial
effect.

Updates #7876

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
James Tucker bd0c32ca21 tsnet: disable TestLoopbackSOCKS5 on Windows
This test is not regularly passing on CI, but seems to pass reliably
locally. Needs deeper debugging.

Updates #7876

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
James Tucker b7f51a1468 .github/workflows: add artifact caching and remove double build on race
Go artifact caching will help provided that the cache remains small
enough - we can reuse the strategy from the Windows build where we only
cache and pull the zips, but let go(1) do the many-file unpacking as it
does so faster.

The race matrix was building once without race, then running all the
tests with race, so change the matrix to incldue a `buildflags`
parameter and use that both in the build and test steps.

Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Andrew Dunham f352f8a0e6 util/set: move Slice type from corp to oss
This is an exact copy of the files misc/set/set{,_test}.go from
tailscale/corp@a5415daa9c, plus the
license headers.

For use in #7877

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I712d09c6d1a180c6633abe3acf8feb59b27e2866
1 year ago
James Tucker 8dec1a8724 .github/workflows: reenable Windows CI, disable broken tests
We accidentally switched to ./tool/go in
4022796484 which resulted in no longer
running Windows builds, as this is attempting to run a bash script.

I was unable to quickly fix the various tests that have regressed, so
instead I've added skips referencing #7876, which we need to back and
fix.

Updates #7262
Updates #7876

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Will Norris 4ecc7fdf5f api.md: update example auth key value
example was missing the "-auth" type in the key prefix, which all new
keys now contain.  Also update key ID to match the full key, and fix
indenting of closing braces.

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Brad Fitzpatrick 6866aaeab3 wgengine/magicsock: factor out receiveIPv4 & receiveIPv6 common code
Updates #2331

Change-Id: I801df38b217f5d17203e8dc3b8654f44747e0f4b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick c889254b42 net/art: skip tests on CI for now
To get the tree green again for other people.

Updates #7866

Change-Id: Ibdad2e1408e5f0c97e49a148bfd77aad17c2c5e5
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 228d0c6aea net/netcheck: use dnscache.Resolver when resolving DERP IPs
This also adds a bunch of tests for this function to ensure that we're
returning the proper IP(s) in all cases.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I0d9d57170dbab5f2bf07abdf78ecd17e0e635399
1 year ago
Maisem Ali 64bbf1738e tailcfg: make SelfNodeV4MasqAddrForThisPeer a pointer
This makes `omitempty` actually work, and saves bytes in each map response.

Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
David Anderson a5fd51ebdc net/art: disable the IPv6 100k routes benchmark.
At the current unoptimized memory utilization of the various data structures,
100k IPv6 routes consumes in the ballpark of 3-4GiB, which risks OOMing our
386 test machine.

Until we have the optimizations to (drastically) reduce that consumption,
skip the test that bloats too much for 32-bit machines.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson a7c910e361 net/art: implement the Table type, a multi-level art route table.
Updates #7781

                           │    sec/op     │
TableInsertion/ipv4/10       1.562µ ±   2%
TableInsertion/ipv4/100      2.398µ ±   5%
TableInsertion/ipv4/1000     2.097µ ±   3%
TableInsertion/ipv4/10000    2.756µ ±   4%
TableInsertion/ipv4/100000   2.473µ ±  13%
TableInsertion/ipv6/10       7.649µ ±   2%
TableInsertion/ipv6/100      12.09µ ±   3%
TableInsertion/ipv6/1000     14.84µ ±   5%
TableInsertion/ipv6/10000    14.72µ ±   8%
TableInsertion/ipv6/100000   13.23µ ±  41%
TableDelete/ipv4/10          378.4n ±   5%
TableDelete/ipv4/100         366.9n ±   3%
TableDelete/ipv4/1000        418.6n ±   3%
TableDelete/ipv4/10000       609.2n ±  11%
TableDelete/ipv4/100000      679.2n ±  28%
TableDelete/ipv6/10          504.2n ±   4%
TableDelete/ipv6/100         959.5n ±  12%
TableDelete/ipv6/1000        1.436µ ±   6%
TableDelete/ipv6/10000       1.772µ ±  15%
TableDelete/ipv6/100000      1.172µ ± 113%
TableGet/ipv4/10             32.14n ±  11%
TableGet/ipv4/100            38.58n ±   2%
TableGet/ipv4/1000           45.03n ±   2%
TableGet/ipv4/10000          52.90n ±   7%
TableGet/ipv4/100000         135.2n ±  11%
TableGet/ipv6/10             41.55n ±   1%
TableGet/ipv6/100            44.78n ±   2%
TableGet/ipv6/1000           49.03n ±   2%
TableGet/ipv6/10000          65.38n ±   5%
TableGet/ipv6/100000         525.0n ±  39%

                           │   avg-B/op   │
TableInsertion/ipv4/10       25.18Ki ± 0%
TableInsertion/ipv4/100      17.63Ki ± 0%
TableInsertion/ipv4/1000     14.14Ki ± 0%
TableInsertion/ipv4/10000    12.92Ki ± 0%
TableInsertion/ipv4/100000   11.13Ki ± 0%
TableInsertion/ipv6/10       76.87Ki ± 0%
TableInsertion/ipv6/100      98.33Ki ± 0%
TableInsertion/ipv6/1000     91.44Ki ± 0%
TableInsertion/ipv6/10000    90.39Ki ± 0%
TableInsertion/ipv6/100000   87.19Ki ± 0%
TableDelete/ipv4/10            3.230 ± 0%
TableDelete/ipv4/100           4.020 ± 0%
TableDelete/ipv4/1000          3.990 ± 0%
TableDelete/ipv4/10000         4.000 ± 0%
TableDelete/ipv4/100000        4.000 ± 0%
TableDelete/ipv6/10            16.00 ± 0%
TableDelete/ipv6/100           16.00 ± 0%
TableDelete/ipv6/1000          16.00 ± 0%
TableDelete/ipv6/10000         16.00 ± 0%
TableDelete/ipv6/100000        16.00 ± 0%

                           │ avg-allocs/op │
TableInsertion/ipv4/10          2.900 ± 0%
TableInsertion/ipv4/100         2.330 ± 0%
TableInsertion/ipv4/1000        2.070 ± 0%
TableInsertion/ipv4/10000       1.980 ± 0%
TableInsertion/ipv4/100000      1.840 ± 0%
TableInsertion/ipv6/10          6.800 ± 0%
TableInsertion/ipv6/100         8.420 ± 0%
TableInsertion/ipv6/1000        7.900 ± 0%
TableInsertion/ipv6/10000       7.820 ± 0%
TableInsertion/ipv6/100000      7.580 ± 0%
TableDelete/ipv4/10             1.000 ± 0%
TableDelete/ipv4/100            1.000 ± 0%
TableDelete/ipv4/1000           1.000 ± 0%
TableDelete/ipv4/10000          1.000 ± 0%
TableDelete/ipv4/100000         1.000 ± 0%
TableDelete/ipv6/10             1.000 ± 0%
TableDelete/ipv6/100            1.000 ± 0%
TableDelete/ipv6/1000           1.000 ± 0%
TableDelete/ipv6/10000          1.000 ± 0%
TableDelete/ipv6/100000         1.000 ± 0%

                           │   routes/s   │
TableInsertion/ipv4/10       640.3k ±  2%
TableInsertion/ipv4/100      417.1k ±  5%
TableInsertion/ipv4/1000     477.0k ±  3%
TableInsertion/ipv4/10000    362.8k ±  5%
TableInsertion/ipv4/100000   404.5k ± 15%
TableInsertion/ipv6/10       130.7k ±  1%
TableInsertion/ipv6/100      82.69k ±  3%
TableInsertion/ipv6/1000     67.37k ±  5%
TableInsertion/ipv6/10000    67.93k ±  9%
TableInsertion/ipv6/100000   75.63k ± 29%
TableDelete/ipv4/10          2.642M ±  6%
TableDelete/ipv4/100         2.726M ±  3%
TableDelete/ipv4/1000        2.389M ±  3%
TableDelete/ipv4/10000       1.641M ± 12%
TableDelete/ipv4/100000      1.472M ± 27%
TableDelete/ipv6/10          1.984M ±  4%
TableDelete/ipv6/100         1.042M ± 11%
TableDelete/ipv6/1000        696.5k ±  6%
TableDelete/ipv6/10000       564.4k ± 13%
TableDelete/ipv6/100000      853.6k ± 53%

                     │   addrs/s    │
TableGet/ipv4/10       31.11M ± 10%
TableGet/ipv4/100      25.92M ±  2%
TableGet/ipv4/1000     22.21M ±  2%
TableGet/ipv4/10000    18.91M ±  8%
TableGet/ipv4/100000   7.397M ± 12%
TableGet/ipv6/10       24.07M ±  1%
TableGet/ipv6/100      22.33M ±  2%
TableGet/ipv6/1000     20.40M ±  2%
TableGet/ipv6/10000    15.30M ±  5%
TableGet/ipv6/100000   1.905M ± 28%

                     │    B/op    │
TableGet/ipv4/10       4.000 ± 0%
TableGet/ipv4/100      4.000 ± 0%
TableGet/ipv4/1000     4.000 ± 0%
TableGet/ipv4/10000    4.000 ± 0%
TableGet/ipv4/100000   4.000 ± 0%
TableGet/ipv6/10       16.00 ± 0%
TableGet/ipv6/100      16.00 ± 0%
TableGet/ipv6/1000     16.00 ± 0%
TableGet/ipv6/10000    16.00 ± 0%
TableGet/ipv6/100000   16.00 ± 0%

                     │ allocs/op  │
TableGet/ipv4/10       1.000 ± 0%
TableGet/ipv4/100      1.000 ± 0%
TableGet/ipv4/1000     1.000 ± 0%
TableGet/ipv4/10000    1.000 ± 0%
TableGet/ipv4/100000   1.000 ± 0%
TableGet/ipv6/10       1.000 ± 0%
TableGet/ipv6/100      1.000 ± 0%
TableGet/ipv6/1000     1.000 ± 0%
TableGet/ipv6/10000    1.000 ± 0%
TableGet/ipv6/100000   1.000 ± 0%

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Mihai Parparita edb02b63f8 net/sockstats: pass in logger to sockstats.WithSockStats
Using log.Printf may end up being printed out to the console, which
is not desirable. I noticed this when I was investigating some client
logs with `sockstats: trace "NetcheckClient" was overwritten by another`.
That turns to be harmless/expected (the netcheck client will fall back
to the DERP client in some cases, which does its own sockstats trace).

However, the log output could be visible to users if running the
`tailscale netcheck` CLI command, which would be needlessly confusing.

Updates tailscale/corp#9230

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Mihai Parparita 782ccb5655 .github/workflows: run one set of tests with the tailscale_go build tag
We use it to gate code that depends on custom Go toolchain, but it's
currently only passed in the corp runners. Add a set on OSS so that we
can catch regressions earlier.

To specifically test sockstats this required adding a build tag to
explicitly enable them -- they're normally on for iOS, macOS and Android
only, and we don't run tests on those platforms normally.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Will Norris bb34589748 log/sockstatlog: limit sockstat logs to 5 MB
Updates tailscale/corp#9230

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Brad Fitzpatrick 9e50da321b client/tailscale: dial LocalAPI at 127.0.0.1 on macOS
Updates #7851

Change-Id: Ib53cf53cdfee277ef42f7833352bc51ecb5db959
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Mihai Parparita bdc7a61c24 tool/gocross: add ts_macext build tag for Xcode builds
It's used to control various opt-in functionality for the macOS and iOS
apps, and was lost in the migration to gocross.

Updates tailscale/tailscale#7769

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
License Updater 33b006cacf licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
License Updater e5d272f445 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Flakes Updater 7c95734907 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Anton Tolchanov 8546ff98fb tsweb: move varz handler(s) into separate modules
This splits Prometheus metric handlers exposed by tsweb into two
modules:
- `varz.Handler` exposes Prometheus metrics generated by our expvar
  converter;
- `promvarz.Handler` combines our expvar-converted metrics and native
  Prometheus metrics.

By default, tsweb will use the promvarz handler, however users can keep
using only the expvar converter. Specifically, `tailscaled` now uses
`varz.Handler` explicitly, which avoids a dependency on the
(heavyweight) Prometheus client.

Updates https://github.com/tailscale/corp/issues/10205

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Anton Tolchanov c153e6ae2f prober: migrate to Prometheus metric library
This provides an example of using native Prometheus metrics with tsweb.

Prober library seems to be the only user of PrometheusVar, so I am
removing support for it in tsweb.

Updates https://github.com/tailscale/corp/issues/10205

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Anton Tolchanov 11e6247d2a tsweb: expose native Prometheus metrics in /debug/varz
The handler will expose built-in process and Go metrics by default,
which currently duplicate some of the expvar-proxied metrics
(`goroutines` vs `go_goroutines`, `memstats` vs `go_memstats`), but as
long as their names are different, Prometheus server will just scrape
both.

This will change /debug/varz behaviour for most tsweb binaries, but
notably not for control, which configures a `tsweb.VarzHandler`
[explicitly](a5b5d5167f/cmd/tailcontrol/tailcontrol.go (L779))

Updates https://github.com/tailscale/corp/issues/10205

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
License Updater 690446c784 licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Mihai Parparita cef0a474f8 ipn/ipnlocal: check that sockstatLogger is available in c2n endpoint
Otherwise there may be a panic if it's nil (and the control side of
the c2n call will just time out).

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Mihai Parparita 03b2c44a21 ipn/ipnlocal: more explicitly say if sockstats are not available
Makes it more apparent in the PeerAPI endpoint that the client was
not built with the appropriate toolchain or build tags.

Updates tailscale/corp#9230

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Flakes Updater 1bec2cbbd5 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Jordan Whited f571536598
go.mod: bump wireguard-go (#7836)
This pulls in a synchronization optimization, see
tailscale/wireguard-go@af17262.

Updates tailscale/corp#8734

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
James Tucker e09c434e5d wgengine/magicsock: remove locking sync requirements on conn disco keys
The lazy initialization of the disco key is not necessary, and
contributes to unnecessary locking and state checking.

Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
James Tucker e1b71c83ac wgengine/magicsock: remove unused fields on discoInfo
Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
James Tucker a257b2f88b wgengine/magicsock: add immutability documentation to endpointDisco
Updates #7825

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
James Tucker fb18af5564 wgengine/netstack: fix data-race on startup
Running tailscaled with the race detector enabled immediately fires on
this field, as it is updated after first read.

Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn c573bef0aa tailcfg,wgengine: add initial support for WireGuard only peers
A peer can have IsWireGuardOnly, which means it will not support DERP or
Disco, and it must have Endpoints filled in order to be usable.

In the present implementation only the first Endpoint will be used as
the bestAddr.

Updates tailscale/corp#10351

Co-authored-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
Co-authored-by: James Tucker <james@tailscale.com>
Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
James Tucker 6cfcb3cae4 wgengine/magicsock: fix synchronization of endpoint disco fields
Identified in review in #7821 endpoint.discoKey and endpoint.discoShort
are often accessed without first taking endpoint.mu. The arrangement
with endpoint.mu is inconvenient for a good number of those call-sites,
so it is instead replaced with an atomic pointer to carry both pieces of
disco info. This will also help with #7821 that wants to add explicit
checks/guards to disable disco behaviors when disco keys are missing
which is necessarily implicitly mostly covered by this change.

Updates #7821

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Mihai Parparita e978299bf0 net/sockstats: disable deltas for the cell radio power state metric
Updates tailscale/corp#9230

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Will Norris 22680a11ae net/sockstats: return early if no radio period length
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris 75784e10e2 sockstats: add client metrics for radio power state
power state is very roughly approximated based on observed network
activity and AT&T's state transition timings for a typical 3G radio.

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Tom DNetto 6a627e5a33 net, wgengine/capture: encode NAT addresses in pcap stream
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
License Updater 92459a9248 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
License Updater 7012bf7981 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
License Updater 07b29f13dc licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Mihai Parparita f49b9f75b8 util/clientmetric: allow client metric values to be provided by a function
Adds NewGaugeFunc and NewCounterFunc (inspired by expvar.Func) which
change the current value to be reported by a function. This allows
some client metric values to be computed on-demand during uploading (at
most every 15 seconds), instead of being continuously updated.

clientmetric uploading had a bunch of micro-optimizations for memory
access (#3331) which are not possible with this approach. However, any
performance hit from function-based metrics is contained to those metrics
only, and we expect to have very few.

Also adds a DisableDeltas() option for client metrics, so that absolute
values are always reported. This makes server-side processing of some
metrics easier to reason about.

Updates tailscale/corp#9230

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
phirework c0e0a5458f
cmd/tailscale: show reauth etc. links even if no login name (#7803)
Signed-off-by: Jenny Zhang <jz@tailscale.com>
1 year ago
shayne 81fd00a6b7
cmd/tailscale/cli: [serve] add support for proxy paths (#7800) 1 year ago
Maisem Ali d42d570066
ssh/tailssh: handle output matching better in tests (#7799) 1 year ago
Brad Fitzpatrick 2c0bda6e2e ssh/tailssh: make Tailscale SSH work on gokrazy
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Flakes Updater 3d29da105c go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Jordan Whited 765d3253f3
go.mod: bump wireguard-go (#7792)
Pull in TUN checksum optimizations and crypto channel changes.

Updates tailscale/corp#8734

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
shayne ba4e58f429
cmd/tailscale/cli: do not allow turning Funnel on while shields-up (#7770) 1 year ago
valscale 7bfb7744b7
derp,magicsock: add debug envknobs for HTTP and derp server name (#7744)
Make developing derp easier by:

1. Creating an envknob telling clients to use HTTP to connect to derp
servers, so devs don't have to acquire a valid TLS cert.

2. Creating an envknob telling clients which derp server to connect
to, so devs don't have to edit the ACLs in the admin console to add a
custom DERP map.

3. Explaining how the -dev and -a command lines args to derper
interact.

To use this:

1. Run derper with -dev.

2. Run tailscaled with TS_DEBUG_USE_DERP_HTTP=1 and
TS_DEBUG_USE_DERP_ADDR=localhost

This will result in the client connecting to derp via HTTP on port
3340.

Fixes #7700

Signed-off-by: Val <valerie@tailscale.com>
1 year ago
Jordan Whited f475e5550c
net/neterror, wgengine/magicsock: use UDP GSO and GRO on Linux (#7791)
This commit implements UDP offloading for Linux. GSO size is passed to
and from the kernel via socket control messages. Support is probed at
runtime.

UDP GSO is dependent on checksum offload support on the egress netdev.
UDP GSO will be disabled in the event sendmmsg() returns EIO, which is
a strong signal that the egress netdev does not support checksum
offload.

Updates tailscale/corp#8734

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
David Anderson 45138fcfba go.toolchain.rev: update for go 1.20.3
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
James Tucker b0ed863d55 atomicfile: use /tmp for socket path on macOS
macOS does not allow unix socket creation in private temp directories,
but global /tmp is ok, so swap out for global temp for now.

Updates #7658
Updates #7785

Signed-off-by: James Tucker <jftucker@gmail.com>
1 year ago
David Anderson 4d1b3bc26f net/art: implement the stride table building block of ART
A stride table is an 8-bit routing table implemented as an array binary
tree, with a special tree updating function (allot) that enables lightning
fast address lookups and reasonably fast insertion and deletion.

Insertion, deletion and lookup are all allocation-free.

Updates #7781

                                        │    sec/op    │
StrideTableInsertion/10/random_order       16.79n ± 2%
StrideTableInsertion/10/largest_first      16.83n ± 1%
StrideTableInsertion/10/smallest_first     16.83n ± 0%
StrideTableInsertion/50/random_order       17.84n ± 1%
StrideTableInsertion/50/largest_first      20.04n ± 1%
StrideTableInsertion/50/smallest_first     16.39n ± 0%
StrideTableInsertion/100/random_order      14.63n ± 0%
StrideTableInsertion/100/largest_first     17.45n ± 4%
StrideTableInsertion/100/smallest_first    12.98n ± 0%
StrideTableInsertion/200/random_order      12.51n ± 4%
StrideTableInsertion/200/largest_first     18.36n ± 3%
StrideTableInsertion/200/smallest_first    9.609n ± 3%
StrideTableDeletion/10/random_order        19.50n ± 1%
StrideTableDeletion/10/largest_first       19.34n ± 0%
StrideTableDeletion/10/smallest_first      19.43n ± 0%
StrideTableDeletion/50/random_order        14.58n ± 1%
StrideTableDeletion/50/largest_first       14.27n ± 2%
StrideTableDeletion/50/smallest_first      15.51n ± 0%
StrideTableDeletion/100/random_order       12.02n ± 3%
StrideTableDeletion/100/largest_first      10.64n ± 0%
StrideTableDeletion/100/smallest_first     13.21n ± 3%
StrideTableDeletion/200/random_order       14.05n ± 4%
StrideTableDeletion/200/largest_first      9.288n ± 5%
StrideTableDeletion/200/smallest_first     18.51n ± 1%
StrideTableGet                            0.5010n ± 0%

                                        │  routes/s   │
StrideTableInsertion/10/random_order      59.55M ± 2%
StrideTableInsertion/10/largest_first     59.42M ± 1%
StrideTableInsertion/10/smallest_first    59.43M ± 0%
StrideTableInsertion/50/random_order      56.04M ± 1%
StrideTableInsertion/50/largest_first     49.91M ± 1%
StrideTableInsertion/50/smallest_first    61.00M ± 0%
StrideTableInsertion/100/random_order     68.35M ± 0%
StrideTableInsertion/100/largest_first    57.32M ± 3%
StrideTableInsertion/100/smallest_first   77.06M ± 0%
StrideTableInsertion/200/random_order     79.93M ± 4%
StrideTableInsertion/200/largest_first    54.47M ± 3%
StrideTableInsertion/200/smallest_first   104.1M ± 3%
StrideTableDeletion/10/random_order       51.28M ± 1%
StrideTableDeletion/10/largest_first      51.70M ± 0%
StrideTableDeletion/10/smallest_first     51.48M ± 0%
StrideTableDeletion/50/random_order       68.60M ± 1%
StrideTableDeletion/50/largest_first      70.09M ± 2%
StrideTableDeletion/50/smallest_first     64.45M ± 0%
StrideTableDeletion/100/random_order      83.21M ± 3%
StrideTableDeletion/100/largest_first     94.03M ± 0%
StrideTableDeletion/100/smallest_first    75.69M ± 3%
StrideTableDeletion/200/random_order      71.20M ± 5%
StrideTableDeletion/200/largest_first     107.7M ± 5%
StrideTableDeletion/200/smallest_first    54.02M ± 1%
StrideTableGet                            1.996G ± 0%

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Will Norris 6d5c3c1637 ipn: prefer allow/denylist terminology
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris 5a3da3cd7f ipn: add sockstat logger to stable builds
This makes the sockstat logger available on all builds, but only enables
it by default for unstable.  For stable builds, the logger must be
explicitly enabled via C2N component logger.

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Aaron Klotz 90fd04cbde ipn/ipnlocal, util/winutil/policy: modify Windows profile migration to load legacy prefs from within tailscaled
I realized that a lot of the problems that we're seeing around migration and
LocalBackend state can be avoided if we drive Windows pref migration entirely
from within tailscaled. By doing it this way, tailscaled can automatically
perform the migration as soon as the connection with the client frontend is
established.

Since tailscaled is already running as LocalSystem, it already has access to
the user's local AppData directory. The profile manager already knows which
user is connected, so we simply need to resolve the user's prefs file and read
it from there.

Of course, to properly migrate this information we need to also check system
policies. I moved a bunch of policy resolution code out of the GUI and into
a new package in util/winutil/policy.

Updates #7626

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 year ago
Mihai Parparita e3cb8cc88d ipn/ipnlocal: automatically upload sockstats logs when the period ends
Avoids needing a separate c2n call to get the logs uploaded.

Updates tailscale/corp#9230

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Andrew Dunham 8d3acc9235 util/sysresources, magicsock: scale DERP buffer based on system memory
This adds the util/sysresources package, which currently only contains a
function to return the total memory size of the current system.

Then, we modify magicsock to scale the number of buffered DERP messages
based on the system's available memory, ensuring that we never use a
value lower than the previous constant of 32.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ib763c877de4d0d4ee88869078e7d512f6a3a148d
1 year ago
Tom DNetto 483109b8fc client/tailscale: Fix NPE caused by erroneous close in error case
Fixes https://github.com/tailscale/tailscale/issues/7572

When handling an error during `StreamDebugCapture`, the response body
is closed, even though the response struct is always nil. Thanks
to https://github.com/darkrain42 for debugging this!!

Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
shayne 59879e5770
cmd/tailscale/cli: make serve and funnel visible in list (#7737) 1 year ago
Flakes Updater 1bf65e4760 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Mihai Parparita 38bbb30aaf .github/workflows: remove tsconnect-pkg-publish.yml
Moved to the corp repo with tailscale/corp#7990

Updates tailscale/corp#10165

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
James Tucker f4da995940 atomicfile: reject overwriting irregular files
The intent of atomicfile is to overwrite regular files. Most use cases
that would overwrite irregular files, unix sockets, named pipes,
devices, and so on are more than likely misuse, so disallow them.

Fixes #7658

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Mihai Parparita 02582083d5 cmd/tsconnect: allow root directory to be passed in
#7339 changed the root directory logic to find the ancestor of the cwd
with a go.mod file. This works when running the the binary from this
repo directly, but breaks when we're a dependency in another repo.

Allow the directory to be passed in via a -rootdir flag (the repo that
depends on it can then use `go list -m -f '{{.Dir}}' tailscale.com`
or similar to pass in the value).

Updates tailscale/corp#10165

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
James Tucker 40fa2a420c envknob,net/tstun,wgengine: use TS_DEBUG_MTU consistently
Noted on #5915 TS_DEBUG_MTU was not used consistently everywhere.
Extract the default into a function that can apply this centrally and
use it everywhere.

Added envknob.Lookup{Int,Uint}Sized to make it easier to keep CodeQL
happy when using converted values.

Updates #5915

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Andrew Dunham 8ed4fd1dbc envknob/logknob: add package for configurable logging
A LogKnob allows enabling logs with an envknob, netmap capability, and
manually, and calling a logging function when logs are enabled.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Id66c608d4e488bfd4eaa5e867a8d9289686748be
1 year ago
Andrew Dunham 3b39ca9017 ipn/ipnlocal: update comment in SetComponentDebugLogging
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8c36a62079dce77fc81b9cdfb5fe723b007218ba
1 year ago
Maisem Ali e0d291ab8a ipn/store: add support for stores to hook into a custom dialer
For stores like k8s secrets we need to dial out to the k8s API as though Tailscale
wasn't running. The issue currently only manifests when you try to use an exit node
while running inside a k8s cluster and are trying to use Kubernetes secrets as the
backing store.

This doesn't address cmd/containerboot, which I'll do in a follow up.

Updates #7695

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
License Updater 2b00d6922f licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
License Updater 7b4e85aa78 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Will Norris e99c7c3ee5 sockstats: add labels for netlog and sockstatlog packages
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Andrew Dunham 38e4d303a2 net/tshttpproxy: don't proxy through ourselves
When running a SOCKS or HTTP proxy, configure the tshttpproxy package to
drop those addresses from any HTTP_PROXY or HTTPS_PROXY environment
variables.

Fixes #7407

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I6cd7cad7a609c639780484bad521c7514841764b
1 year ago
Will Norris 62a1e9a44f log/sockstatlog: add delay before writing logs to disk
Split apart polling of sockstats and logging them to disk.  Add a 3
second delay before writing logs to disk to prevent an infinite upload
loop when uploading stats to logcatcher.

Fixes #7719

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Maisem Ali 985535aebc net/tstun,wgengine/*: add support for NAT to routes
This adds support to make exit nodes and subnet routers work
when in scenarios where NAT is required.

It also updates the NATConfig to be generated from a `wgcfg.Config` as
that handles merging prefs with the netmap, so it has the required information
about whether an exit node is already configured and whether routes are accepted.

Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali d1d5d52b2c net/tstun/table: add initial RoutingTable implementation
It is based on `*tempfork/device.AllowedIPs`.

Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 2522b0615f tempfork/device: add a temp fork of golang.zx2c4.com/wireguard/device
This will allow us to reuse the AllowedIPs for NAT decisions in a follow on commit.

The files `allowedips_*.go` are as-is, `peer.go` only keeps the `Peer` declaration with a
single element required for AllowedIPs.

Upstream commit https://git.zx2c4.com/wireguard-go/commit/?id=052af4a8072bbbd3bfe7edf46fe3c1b350f71f08

Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Andrew Dunham c98652c333 doctor/permissions: add new check to print process permissions
Since users can run tailscaled in a variety of ways (root, non-root,
non-root with process capabilities on Linux), this check will print the
current process permissions to the log to aid in debugging.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ida93a206123f98271a0c664775d0baba98b330c7
1 year ago
License Updater 524f53de89 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
James Tucker 8c2b755b2e tool/gocross: use grep -E over egrep to avoid warning
Recent egrep builds produce a warning:

```
egrep: warning: egrep is obsolescent; using grep -E
```

Updates #cleanup

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
James Tucker a31e43f760 go.mod: bump gvisor to 20230320 for dispatcher locking
Upstream improved code around an issue showing up in CI, where sometimes
shutdown will race on endpoint.dispatcher being nil'd, causing a panic
down stack of injectInbound. The upstream patch makes some usage more
safe, but it does not itself fix the local issue.

See panic in https://github.com/tailscale/tailscale/actions/runs/4548299564/jobs/8019187385#step:7:843

See fix in google/gvisor@13d7bf69d8

Updates #7715

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
James Tucker c628132b34 wgengine/netstack: do not send packets to netstack after close
Use the local context on Impl to check for shut down state in order to
drop rather than inject packets after close has begun.

Netstack sets endpoint.dispatcher to nil during shutdown. After the
recent adjustment in 920ec69241 we now
wait for netstack to fully shutdown before we release tests. This means
that we may continue to accept packets and attempt to inject them, which
we must prevent in order to avoid nil pointer panic.

References google/gvisor#8765
Fixes #7715

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Maisem Ali e04acabfde ssh/tailssh: fix race in errors returned when starting recorder
There were two code paths that could fail depending on how fast
the recorder responses. This fixes that by returning the correct
error from both paths.

Fixes #7707

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Flakes Updater cb960d6cdd go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Jordan Whited 27e37cf9b3
go.mod, net/tstun, wgengine/magicsock: update wireguard-go (#7712)
This commit updates the wireguard-go dependency to pull in fixes for
the tun package, specifically 052af4a and aad7fca.

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
License Updater 946451b43e licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
License Updater 840d69e1eb licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Josh Bleecher Snyder 3ba9f8dd04 util/codegen: add -copyright to control presence of copyright headers
Fixes #7702

Signed-off-by: Josh Bleecher Snyder <josharian@gmail.com>
1 year ago
Will Norris 7c99210e68 log: allow toggling sockstat logs via c2n component logging
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Maisem Ali 920ec69241 tsnet,wgenegine/netstack: add test and fix resource leaks
We were not closing the http.Server and were also not waiting for
netstack to fully close.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Anton Tolchanov 2a933c1903
cmd/tailscale: extend hostname validation (#7678)
In addition to checking the total hostname length, validate characters used in each DNS label and label length.

Updates https://github.com/tailscale/corp/issues/10012

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
shayne 43f7ec48ca
funnel: change references from alpha to beta (#7613)
Updates CLI and docs to reference Funnel as beta

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
shayne 3177ccabe5
ipn/ipnlocal: [serve/funnel] use actual SrcAddr as X-Forwarded-For (#7600)
The reverse proxy was sending the ingressd IPv6 down as the
X-Forwarded-For. This update uses the actual remote addr.

Updates tailscale/corp#9914

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
shayne 7908b6d616
ipn/ipnlocal: [serve] Trim mountPoint prefix from proxy path (#7334)
This change trims the mountPoint from the request URL path before
sending the request to the reverse proxy.

Today if you mount a proxy at `/foo` and request to
`/foo/bar/baz`, we leak the `mountPoint` `/foo` as part of the request
URL's path.

This fix makes removed the `mountPoint` prefix from the path so
proxied services receive requests as if they were running at the root
(`/`) path.

This could be an issue if the app generates URLs (in HTML or otherwise)
and assumes `/path`. In this case, those URLs will 404.

With that, I still think we should trim by default and not leak the
`mountPoint` (specific to Tailscale) into whatever app is hosted.
If it causes an issue with URL generation, I'd suggest looking at configuring
an app-specific path prefix or running Caddy as a more advanced
solution.

Fixes: #6571

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
Denton Gentry ed10a1769b scripts/installer.sh: check Photon OS version with pkg server.
Photon OS support crossed streams with using pkgserve to check
for supported versions 6f9aed1656.
Make Photon OS also rely on pkgserve.

Updates https://github.com/tailscale/tailscale/issues/7651
Updates https://github.com/tailscale/corp/issues/8952

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Maisem Ali 5ba57e4661 ssh/tailssh: add tests for recording failure
Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Denton Gentry d5abdd915e scripts/installer: add VMWare PhotonOS.
Fixes https://github.com/tailscale/tailscale/issues/7651

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
valscale 74eb99aed1
derp, derphttp, magicsock: send new unknown peer frame when destination is unknown (#7552)
* wgengine/magicsock: add envknob to send CallMeMaybe to non-existent peer

For testing older client version responses to the PeerGone packet format change.

Updates #4326

Signed-off-by: Val <valerie@tailscale.com>

* derp: remove dead sclient struct member replaceLimiter

Leftover from an previous solution to the duplicate client problem.

Updates #2751

Signed-off-by: Val <valerie@tailscale.com>

* derp, derp/derphttp, wgengine/magicsock: add new PeerGone message type Not Here

Extend the PeerGone message type by adding a reason byte. Send a
PeerGone "Not Here" message when an endpoint sends a disco message to
a peer that this server has no record of.

Fixes #4326

Signed-off-by: Val <valerie@tailscale.com>

---------

Signed-off-by: Val <valerie@tailscale.com>
1 year ago
Maisem Ali 09d0b632d4 ssh/tailssh: add session recording test for non-pty sessions
Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali d39a5e4417 tsnet: support TS_AUTH_KEY variant too
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali d2fd101eb4 net/tstun: only log natConfig on changes
Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 8ac5976897 logpolicy: do not upload logs in tests
Fixes tailscale/corp#10030

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 7300b908fb logpolicy: split out DialContext into a func
Updates tailscale/corp#10030

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali ca19cf13e9 log/sockstatlog: add resource cleanup test
Updates tailscale/corp#10030

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Andrew Dunham 33b359642e net/dns: don't send on closed channel in resolvedManager
Fixes #7686

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ibffb05539ab876b12407d77dcf2201d467895981
1 year ago
Anton Tolchanov 6f9aed1656 scripts: use pkg server to determine supported deb/rpm distros
Fixes https://github.com/tailscale/corp/issues/8952

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Andrew Dunham 4cb1bfee44 net/netcheck: improve determinism in hairpinning test
If multiple Go channels have a value (or are closed), receiving from
them all in a select will nondeterministically return one of the two
arms. In this case, it's possible that the hairpin check timer will have
expired between when we start checking and before we check at all, but
the hairpin packet has already been received. In such cases, we'd
nondeterministically set report.HairPinning.

Instead, check if we have a value in our results channel first, then
select on the value and timeout channel after. Also, add a test that
catches this particular failure.

Fixes #1795

Change-Id: I842ab0bd38d66fabc6cabf2c2c1bb9bd32febf35
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
Maisem Ali 4a89642f7f log/sockstatlog: make shutdown close idle connections
Updates tailscale/corp#10030

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 9e81db50f6 ipn/ipnlocal: use atomicfile.WriteFile in certFileStore
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 8a11f76a0d ipn/ipnlocal: fix cert storage in Kubernetes
We were checking against the wrong directory, instead if we
have a custom store configured just use that.

Fixes #7588
Fixes #7665

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali ec90522a53 ipn/ipnlocal: also store ACME keys in the certStore
We were not storing the ACME keys in the state store, they would always
be stored on disk.

Updates #7588

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 0e203e414f net/packet: add checksum update tests
Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 0bf8c8e710 net/tstun: use p.Buffer() in more places
Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali f6ea6863de tstest/integration: add ping test w/ masquerades
Updates tailscale/corp#8020

Co-authored-by: Melanie Warrick <warrick@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali bb31fd7d1c net/tstun: add inital support for NAT v4
This adds support in tstun to utitilize the SelfNodeV4MasqAddrForThisPeer and
perform the necessary modifications to the packet as it passes through tstun.

Currently this only handles ICMP, UDP and TCP traffic.
Subnet routers and Exit Nodes are also unsupported.

Updates tailscale/corp#8020

Co-authored-by: Melanie Warrick <warrick@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 535fad16f8 net/tstun: rename filterIn/filterOut methods to be more descriptive
Updates tailscale/corp#8020

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali f61b306133 tailcfg: add Node.SelfNodeV4MasqAddrForThisPeer
This only adds the field, to be used in a future commit.

Updates tailscale/corp#8020

Co-authored-by: Melanie Warrick <warrick@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 583e86b7df ssh/tailssh: handle session recording when running in userspace mode
Previously it would dial out using the http.DefaultClient, however that doesn't work
when tailscaled is running in userspace mode (e.g. when testing).

Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali df89b7de10 cmd/k8s-operator: disable HTTP/2 for the auth proxy
Kubernetes uses SPDY/3.1 which is incompatible with HTTP/2, disable it
in the transport and server.

Fixes #7645
Fixes #7646

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 8a246487c2 ssh/tailssh: enable recording of non-pty sessions
Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 8765568373 ssh/tailssh: add docs to CastHeader fields
Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 9d8b7a7383 ipn/store/kubestore: handle "/" in ipn.StateKeys
Kubernetes doesn't allow slashes as keys in secrets, replace them with "__".

This shows up in the kubernetes-operator now that tsnet sets resets the ServeConfig
at startup.

Fixes #7662

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Will Norris 57a008a1e1 all: pass log IDs as the proper type rather than strings
This change focuses on the backend log ID, which is the mostly commonly
used in the client.  Tests which don't seem to make use of the log ID
just use the zero value.

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Andrew Dunham 13377e6458 ssh/tailssh: always assert our final uid/gid
Move the assertions about our post-privilege-drop UID/GID out of the
conditional if statement and always run them; I haven't been able to
find a case where this would fail. Defensively add an envknob to disable
this feature, however, which we can remove after the 1.40 release.

Updates #7616

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Iaec3dba9248131920204bd6c6d34bbc57a148185
1 year ago
Andrew Dunham 9de8287d47 ssh/tailssh: lock OS thread during incubator
This makes it less likely that we trip over bugs like golang/go#1435.

Updates #7616

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic28c03c3ad8ed5274a795c766b767fa876029f0e
1 year ago
Maisem Ali c350cd1f06 ssh/tailssh: use background context for uploading recordings
Otherwise we see errors like
```
ssh-session(sess-20230322T005655-5562985593): recording: error sending recording to <addr>:80: Post "http://<addr>:80/record": context canceled
```

The ss.ctx is closed when the session closes, but we don't want to break the upload at that time. Instead we want to wait for the session to
close the writer when it finishes, which it is already doing.

Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Will Norris f13b8bf0cf log: use logtail to log and upload sockstat logs
Switch to using logtail for logging sockstat logs. Always log locally
(on supported platforms), but disable automatic uploading.  Change
existing c2n sockstats request to trigger upload to log server and
return log ID.

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Mihai Parparita 731688e5cc ipn/localapi: add endpoint for adding debug log entries
Allows the iOS and macOS apps to include their frontend logs when
generating bug reports (tailscale/corp#9982).

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Anton Tolchanov 7083246409 prober: only record latency for successful probes
This will make it easier to track probe latency on a dashboard.

Updates https://github.com/tailscale/corp/issues/9916

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Maisem Ali d92047cc30 ssh/tailssh: allow recorders to be configured on the first or final action
Currently we only send down recorders in first action, allow the final action
to replace them but not to drop them.

Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 7a97e64ef0 ssh/tailssh: add more metadata to recording header
Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Denton Gentry cc3806056f scripts/installer.sh: Add Ubuntu Lunar Lobster 23.04.
pkgs.tailscale.com added support in January, need to
add it to the installer script.

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Maisem Ali 916aa782af ssh/tailssh: stream SSH recordings to configured recorders
Updates tailscale/corp#9967

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Tom DNetto 60cd4ac08d cmd/tailscale/cli: move tskey-wrap functionality under lock sign
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn 1b78dc1f33 tailcfg: move recorders field from SSHRule to SSHAction
Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn 3efd83555f tailcfg: add recorders field to SSHRule struct
This change introduces the Recorders field to the SSHRule struct. The
field is used to store and define addresses where the ssh recorder is
located.

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Sam Linville 812025a39c
words: what?! a llama?! he's supposed to be dead! (#7623)
pull the lever, kronk

Signed-off-by: Sam Linville <samlinville@protonmail.com>
1 year ago
Andrew Dunham 39b289578e ssh/tailssh: make uid an int instead of uint64
Follow-up to #7615

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ib4256bff276f6d5cf95838d8e39c87b3643bde37
1 year ago
David Anderson c9a4dbe383 tool/gocross: correctly embed the git commit into gocross
Previously, the build ended up embedding an empty string, which made
the shell wrapper rebuild gocross on every invocation. This is still
reasonably fast, but fixing the bypass shaves 80% off gocross's overhead
when no rebuild is needed.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Brad Fitzpatrick f11c270c6b go.toolchain.rev: bump Go toolchain
For tailscale/go#60

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Mihai Parparita d2dec13392 net/sockstats: export cellular-only clientmetrics
Followup to #7518 to also export client metrics when the active interface
is cellular.

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
David Anderson e7a78bc28f tool/gocross: support running from outside the repo dir
A bunch of us invoke tool/go from outside the repo that hosts gocross,
as a way of accessing our version-controlled toolchain. This removes
assumptions from gocross that it's being invoked within the repository
that contains its source code and toolchain configuration.

Fixes tailscale/corp#9627

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson df02bb013a tool/gocross: fail if the toolchain revision isn't findable
This used to make sense, but after a refactor somewhere along the line
this results in trying to download from a malformed URL and generally
confusing failures.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Denton Gentry ebc630c6c0 net/interfaces: also allow link-local for AzureAppServices.
In May 2021, Azure App Services used 172.16.x.x addresses:
```
10: eth0@if11: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP
    link/ether 02:42:ac:10:01:03 brd ff:ff:ff:ff:ff:ff
    inet 172.16.1.3/24 brd 172.16.1.255 scope global eth0
       valid_lft forever preferred_lft forever
```

Now it uses link-local:
```
2: eth0@if6: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP
    link/ether 8a:30:1f:50:1d:23 brd ff:ff:ff:ff:ff:ff
    inet 169.254.129.3/24 brd 169.254.129.255 scope global eth0
       valid_lft forever preferred_lft forever
```

This is reasonable for them to choose to do, it just broke the handling in net/interfaces.

This PR proposes to:
1. Always allow link-local in LocalAddresses() if we have no better
   address available.
2. Continue to make isUsableV4() conditional on an environment we know
   requires it.

I don't love the idea of having to discover these environments one by
one, but I don't understand the consequences of making isUsableV4()
return true unconditionally. It makes isUsableV4() essentially always
return true and perform no function.

Fixes https://github.com/tailscale/tailscale/issues/7603

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Andrew Dunham ccace1f7df ssh/tailssh: fix privilege dropping on FreeBSD; add tests
On FreeBSD and Darwin, changing a process's supplementary groups with
setgroups(2) will also change the egid of the process, setting it to the
first entry in the provided list. This is distinct from the behaviour on
other platforms (and possibly a violation of the POSIX standard).

Because of this, on FreeBSD with no TTY, our incubator code would
previously not change the process's gid, because it would read the
newly-changed egid, compare it against the expected egid, and since they
matched, not change the gid. Because we didn't use the 'login' program
on FreeBSD without a TTY, this would propagate to a child process.

This could be observed by running "id -p" in two contexts. The expected
output, and the output returned when running from a SSH shell, is:

    andrew@freebsd:~ $ id -p
    uid         andrew
    groups      andrew

However, when run via "ssh andrew@freebsd id -p", the output would be:

    $ ssh andrew@freebsd id -p
    login       root
    uid         andrew
    rgid        wheel
    groups      andrew

(this could also be observed via "id -g -r" to print just the gid)

We fix this by pulling the details of privilege dropping out into their
own function and prepending the expected gid to the start of the list on
Darwin and FreeBSD.

Finally, we add some tests that run a child process, drop privileges,
and assert that the final UID/GID/additional groups are what we expect.

More information can be found in the following article:
    https://www.usenix.org/system/files/login/articles/325-tsafrir.pdf

Updates #7616
Alternative to #7609

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I0e6513c31b121108b50fe561c89e5816d84a45b9
1 year ago
Mihai Parparita e1fb687104 cmd/tailscale/cli: fix inconsistency between serve text and example command
Use the same local port number in both, and be more precise about what
is being forwarded

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Anton Tolchanov 654b5a0616 derp: add optional debug logging for prober clients
This allows tracking packet flow via logs for prober clients. Note that
the new sclient.debug() function is called on every received packet, but
will do nothing for most clients.

I have adjusted sclient logging to print public keys in short format
rather than full. This takes effect even for existing non-debug logging
(mostly client disconnect messages).

Example logs for a packet being sent from client [SbsJn] (connected to
derper [dM2E3]) to client [10WOo] (connected to derper [AVxvv]):

```
derper [dM2E3]:
derp client 10.0.0.1:35470[SbsJn]: register single client mesh("10.0.1.1"): 4 peers
derp client 10.0.0.1:35470[SbsJn]: read frame type 4 len 40 err <nil>
derp client 10.0.0.1:35470[SbsJn]: SendPacket for [10WOo], forwarding via <derphttp_client.Client [AVxvv] url=https://10.0.1.1/derp>: <nil>
derp client 10.0.0.1:35470[SbsJn]: read frame type 0 len 0 err EOF
derp client 10.0.0.1:35470[SbsJn]: read EOF
derp client 10.0.0.1:35470[SbsJn]: sender failed: context canceled
derp client 10.0.0.1:35470[SbsJn]: removing connection

derper [AVxvv]:
derp client 10.0.1.1:50650[10WOo]: register single client
derp client 10.0.1.1:50650[10WOo]: received forwarded packet from [SbsJn] via [dM2E3]
derp client 10.0.1.1:50650[10WOo]: sendPkt attempt 0 enqueued
derp client 10.0.1.1:50650[10WOo]: sendPacket from [SbsJn]: <nil>
derp client 10.0.1.1:50650[10WOo]: read frame type 0 len 0 err EOF
derp client 10.0.1.1:50650[10WOo]: read EOF
derp client 10.0.1.1:50650[10WOo]: sender failed: context canceled
derp client 10.0.1.1:50650[10WOo]: removing connection
```

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Anton Tolchanov 50d211d1a4 cmd/derpprobe: allow running all probes at the same time
This allows disabling spread mode, which is helpful if you are manually
running derpprobe in `--once` mode against a small number of DERP
machines.

Updates https://github.com/tailscale/corp/issues/9916

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Anton Tolchanov e59dc29a55 prober: log client pubkeys on derp mesh probe failures
Updates https://github.com/tailscale/corp/issues/9916

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
dependabot[bot] 60a028a4f6 .github: Bump peter-evans/create-pull-request from 4.1.4 to 4.2.4
Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 4.1.4 to 4.2.4.
- [Release notes](https://github.com/peter-evans/create-pull-request/releases)
- [Commits](ad43dccb4d...38e0b6e68b)

---
updated-dependencies:
- dependency-name: peter-evans/create-pull-request
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
1 year ago
dependabot[bot] 927e2e3e7c .github: Bump actions/setup-go from 3 to 4
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
1 year ago
Nahum Shalman 82e067e0ff build_dist.sh: make cross-compilation friendly
Signed-off-by: Nahum Shalman <nahamu@gmail.com>
1 year ago
Maisem Ali 95494a155e .github: use unique names for jobs
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
James 'zofrex' Sanderson 9534783758
tailscale/cmd: Warn for up --force-reauth over SSH without accepting the risk (#7575)
Fixes #6377

Signed-off-by: James Sanderson <jsanderson@tailscale.com>
1 year ago
Maisem Ali f34590d9ed tsnet: add test for Funnel connections
For the logic added in b797f77.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali c6d96a2b61 tsnet: do not start logtail in tests
It was trying to upload logs in tests.

skip-issuebot

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
David Anderson 0498d5ea86 tool/gocross: delete bootstrap tarball downloads after use
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 1f95bfedf7 tool/gocross: adjust Xcode flags to match new Xcode env
Xcode changed how/what data it exports to build steps at some point
recently, so our old way of figuring out the minimum support version
for clang stopped working.

Updates tailscale/corp#4095

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Kurnia D Win 9526858b1e control/controlclient: fix accidental backoff reset
Signed-off-by: Kurnia D Win <kurnia.d.win@gmail.com>
1 year ago
David Anderson df3996cae3 tool/gocross: bootstrap correctly on an older toolchain
Sometimes, our cached toolchain ends up being an older version of
Go, older than our go.mod allows. In that scenario, gocross-wrapper.sh
would find a usable toolchain, but then fail to compile gocross.

This change makes the wrapper script check that the cached toolchain's
minor version is good enough to build tailscale.com, and re-bootstraps
in shell if not.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Mihai Parparita 97b6d3e917 sockstats: remove per-interface stats from Get
They're not needed for the sockstats logger, and they're somewhat
expensive to return (since they involve the creation of a map per
label). We now have a separate GetInterfaces() method that returns
them instead (which we can still use in the PeerAPI debug endpoint).

If changing sockstatlog to sample at 10,000 Hz (instead of the default
of 10Hz), the CPU usage would go up to 59% on a iPhone XS. Removing the
per-interface stats drops it to 20% (a no-op implementation of Get that
returns a fixed value is 16%).

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
David Anderson 9ebab961c9 version/mkversion: don't break on tagged go.mod entries
I thought our versioning scheme would make go.mod include a commit hash
even on stable builds. I was wrong. Fortunately, the rest of this code
wants anything that 'git rev-parse' understands (to convert it into a full
git hash), and tags qualify.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Denton Gentry 6d3490f399 VERSION.txt: this is 1.39
Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
License Updater 51b0169b10 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply+license-updater@tailscale.com>
1 year ago
Maisem Ali b4d3e2928b tsnet: avoid deadlock on close
tsnet.Server.Close was calling listener.Close with the server mutex
held, but the listener close method tries to grab that mutex, resulting
in a deadlock.

Co-authored-by: David Crawshaw <crawshaw@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
shayne 2b892ad6e7
cmd/tailscale/cli: [serve] rework commands based on feedback (#6521)
```
$ tailscale serve https:<port> <mount-point> <source> [off]
$ tailscale serve tcp:<port> tcp://localhost:<local-port> [off]
$ tailscale serve tls-terminated-tcp:<port> tcp://localhost:<local-port> [off]
$ tailscale serve status [--json]

$ tailscale funnel <serve-port> {on|off}
$ tailscale funnel status [--json]
```

Fixes: #6674

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
Will Norris 6ef2105a8e log/sockstatlog: only start once; don't copy ticker
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Maisem Ali 8c4adde083 log/sockstatlog: also shutdown the poll goroutine
Co-authored-by: Will Norris <will@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali c87782ba9d cmd/k8s-operator: drop trailing dot in tagged node name
Also update tailcfg docs.

Updates #5055

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Will Norris 09e0ccf4c2 ipn: add c2n endpoint for sockstats logs
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris a1d9f65354 ipn,log: add logger for sockstat deltas
Signed-off-by: Will Norris <will@tailscale.com>
Co-authored-by: Melanie Warrick <warrick@tailscale.com>
1 year ago
Maisem Ali 5e8a80b845 all: replace /kb/ links with /s/ equivalents
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 558735bc63 cmd/k8s-operator: require HTTPS to be enabled for AuthProxy
Updates #5055

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 489e27f085 cmd/k8s-operator: make auth proxy pass tags as Impersonate-Group
We were not handling tags at all, pass them through as Impersonate-Group headers.
And use the FQDN for tagged nodes as Impersonate-User.

Updates #5055

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 56526ff57f tailcfg: bump capver for 1.38
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 09aed46d44 cmd/tailscale/cli: update docs and unhide configure
Also call out Alpha.

Updates #7220

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 223713d4a1 tailcfg,all: add and use Node.IsTagged()
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Andrew Dunham 83fa17d26c various: pass logger.Logf through to more places
Updates #7537

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Id89acab70ea678c8c7ff0f44792d54c7223337c6
1 year ago
Maisem Ali 958c89470b
tsnet: add CertDomains helper (#7533)
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
shayne e109cf9fdd
tsnet/tsnet: clear ipn.ServeConfig on Up for tsnet apps (#7534)
We persist the ServeConfig, even for tsnet apps. It's quite possible for
the ServeConfig to be out of step with the code. Example: If you run
`ListenFunnel` then later turn it off, the ServeConfig will still show
it enabled, the admin console will show it enabled, but the packet
handler will reject the packets.

Workaround by clearing the ServeConfig in `tsnet.Up`

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
Maisem Ali 3ff44b2307 ipn: add Funnel port check from nodeAttr
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali ccdd534e81 tsnet: add ListenFunnel
This lets a tsnet binary share a server out over Tailscale Funnel.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
Denton Gentry 047b324933 scripts/installer: add PureOS and Amazon Linux Next
Fixes https://github.com/tailscale/tailscale/issues/7410

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Andrew Dunham f0d6228c52 ipn/localapi: flesh out the 'debug derp' checks
Updates #6526

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic18d9ff288b9c7b8d5ab1bd77dd59693cd776cc4
1 year ago
License Updater 920de86cee licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Mihai Parparita b64d78d58f sockstats: refactor validation to be opt-in
Followup to #7499 to make validation a separate function (
GetWithValidation vs. Get). This way callers that don't need it don't
pay the cost of a syscall per active TCP socket.

Also clears the conn on close, so that we don't double-count the stats.

Also more consistently uses Go doc comments for the exported API of the
sockstats package.

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Mihai Parparita ea81bffdeb sockstats: export as client metrics
Though not fine-grained enough to be useful for detailed analysis, we
might as well export that we gather as client metrics too, since we have
an upload/analysis pipeline for them.

clientmetric.Metric.Add is an atomic add, so it's pretty cheap to also
do per-packet.

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Maisem Ali 1e72de6b72 ipn/ipnlocal: remove WIP restriction for Tailscale SSH on macOS
It kinda works fine now on macOS with the recent fixes in 0582829 and
 5787989d.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Tom DNetto 92fc243755 cmd/tailscale: annotate tailnet-lock keys which wrap pre-auth keys
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Tom DNetto 3471fbf8dc cmd/tailscale: surface node-key for locked out tailnet-lock peers
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Maisem Ali b797f773c7 ipn/ipnlocal: add support for funnel in tsnet
Previously the part that handled Funnel connections was not
aware of any listeners that tsnet.Servers might have had open
so it would check against the ServeConfig and fail.

Adding a ServeConfig for a TCP proxy was also not suitable in this
scenario as that would mean creating two different listeners and have
one forward to the other, which really meant that you could not have
funnel and tailnet-only listeners on the same port.

This also introduces the ipn.FunnelConn as a way for users to identify
whether the call is coming over funnel or not. Currently it only holds
the underlying conn and the target as presented in the "Tailscale-Ingress-Target"
header.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Joe Tsai dad78f31f3
syncs: add WaitGroup wrapper (#7481)
The addition of WaitGroup.Go in the standard library has been
repeatedly proposed and rejected.
See golang/go#18022, golang/go#23538, and golang/go#39863

In summary, the argument for WaitGroup.Go is that it avoids bugs like:

	go func() {
		wg.Add(1)
		defer wg.Done()
		...
	}()

where the increment happens after execution (not before)
and also (to a lesser degree) because:

	wg.Go(func() {
		...
	})

is shorter and more readble.

The argument against WaitGroup.Go is that the provided function
takes no arguments and so inputs and outputs must closed over
by the provided function. The most common race bug for goroutines
is that the caller forgot to capture the loop iteration variable,
so this pattern may make it easier to be accidentally racy.
However, that is changing with golang/go#57969.

In my experience the probability of race bugs due to the former
still outwighs the latter, but I have no concrete evidence to prove it.

The existence of errgroup.Group.Go and frequent utility of the method
at least proves that this is a workable pattern and
the possibility of accidental races do not appear to
manifest as frequently as feared.

A reason *not* to use errgroup.Group everywhere is that there are many
situations where it doesn't make sense for the goroutine to return an error
since the error is handled in a different mechanism
(e.g., logged and ignored, formatted and printed to the frontend, etc.).
While you can use errgroup.Group by always returning nil,
the fact that you *can* return nil makes it easy to accidentally return
an error when nothing is checking the return of group.Wait.
This is not a hypothetical problem, but something that has bitten us
in usages that was only using errgroup.Group without intending to use
the error reporting part of it.

Thus, add a (yet another) variant of WaitGroup here that
is identical to sync.WaitGroup, but with an extra method.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Maisem Ali be027a9899 control/controlclient: improve handling of concurrent lite map requests
This reverts commit 6eca47b16c and fixes forward.

Previously the first ever streaming MapRequest that a client sent would also
set ReadOnly to true as it didn't have any endpoints and expected/relied on the
map poll to restart as soon as it got endpoints. However with 48f6c1eba4,
we would no longer restart MapRequests as frequently as we used to, so control
would only ever get the first streaming MapRequest which had ReadOnly=true.

Control would treat this as an uninteresting request and would not send it
any further netmaps, while the client would happily stay in the map poll forever
while litemap updates happened in parallel.

This makes it so that we never set `ReadOnly=true` when we are doing a streaming
MapRequest. This is no longer necessary either as most endpoint discovery happens
over disco anyway.

Co-authored-by: Andrew Dunham <andrew@du.nham.ca>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Joe Tsai 87b4bbb94f
tstime/rate: add Value (#7491)
Add Value, which measures the rate at which an event occurs,
exponentially weighted towards recent activity.
It is guaranteed to occupy O(1) memory, operate in O(1) runtime,
and is safe for concurrent use.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Mihai Parparita 4c2f67a1d0 net/sockstat: fix per-interface statistics not always being available
withSockStats may be called before setLinkMonitor, in which case we
don't have a populated knownInterfaces map. Since we pre-populate the
per-interface counters at creation time, we would end up with an
empty map. To mitigate this, we do an on-demand request for the list of
interfaces.

This would most often happen with the logtail instrumentation, since we
initialize it very early on.

Updates tailscale/corp#9230

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Maisem Ali e69682678f ssh/tailssh: use context.WithCancelCause
It was using a custom implmentation of the context.WithCancelCause,
replace usage with stdlib.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Mihai Parparita a2be1aabfa logtail: remove unncessary response read
Effectively reverts #249, since the server side was fixed (with #251?)
to send a 200 OK/content-length 0 response.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Tom DNetto ce99474317 all: implement preauth-key support with tailnet lock
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Mihai Parparita f4f8ed98d9 sockstats: add validation for TCP socket stats
We can use the TCP_CONNECTION_INFO getsockopt() on Darwin to get
OS-collected tx/rx bytes for TCP sockets. Since this API is not available
for UDP sockets (or on Linux/Android), we can't rely on it for actual
stats gathering.

However, we can use it to validate the stats that we collect ourselves
using read/write hooks, so that we can be more confident in them. We
do need additional hooks from the Go standard library (added in
tailscale/go#59) to be able to collect them.

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Tom DNetto 6eca47b16c Revert "control/controlclient: improve handling of concurrent lite map requests"
This reverts commit 48f6c1eba4.

It unfortunately breaks mapresponse wakeups.

Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Andrew Dunham 48f6c1eba4 control/controlclient: improve handling of concurrent lite map requests
Prior to this change, if we were in the middle of a lite map update we'd
tear down the entire map session and restart it. With this change, we'll
cancel an in-flight lite map request up to 10 times and restart before
we tear down the streaming map request. We tear down everything after 10
retries to ensure that a steady stream of calls to sendNewMapRequest
doesn't fail to make progress by repeatedly canceling and restarting.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Change-Id: I9392bf8cf674e7a58ccd1e476039300a359ef3b1
1 year ago
Maisem Ali b0cb39cda1 tsnet: only intercept TCP flows that have listeners
Previously, it would accept all TCP connections and then close the ones
it did not care about. Make it only ever accept the connections that it
cares about.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
M. J. Fromberger c09578d060
.github: update tibdex/github-app-token to release v1.8.0 (#7495)
The main motivation for this change is to stop using the deprecated
set-output function which triggers deprecation warnings in the action.

Change-Id: I80496c44ea1166b9c40d5cd9e450129778ad4aaf
Signed-off-by: M. J. Fromberger <fromberger@tailscale.com>
1 year ago
M. J. Fromberger a75360ccd6
util: add truncate package (#7490)
This package handles cases where we need to truncate human-readable text to fit
a length constraint without leaving "ragged" multi-byte rune fragments at the
end of the truncated value.

Change-Id: Id972135d1880485f41b1fedfb65c2b8cc012d416
Signed-off-by: M. J. Fromberger <fromberger@tailscale.com>
1 year ago
David Anderson 5b68dcc8c1 go.mod.sri: update for toolchain change.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Kyle Carberry 3862a1e1d5 derp/derphttp: cleanup WebSocket connection on close
This was causing a leak in our CI!

Signed-off-by: Kyle Carberry <kyle@carberry.com>
1 year ago
Andrew Dunham be107f92d3 wgengine/magicsock: track per-endpoint changes in ringbuffer
This change adds a ringbuffer to each magicsock endpoint that keeps a
fixed set of "changes"–debug information about what updates have been
made to that endpoint.

Additionally, this adds a LocalAPI endpoint and associated
"debug peer-status" CLI subcommand to fetch the set of changes for a given
IP or hostname.

Updates tailscale/corp#9364

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I34f726a71bddd0dfa36ec05ebafffb24f6e0516a
1 year ago
David Crawshaw 9245d813c6 tsnet: explicit message for panic seen in CI
Updates #7488

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
shayne f7a7957a11
sniproxy: add promote-https (#7487)
Adds support for an HTTP server that promotes all requests to HTTPS.
The flag is `-promote-https` and defaults to true.

Updates #1748
1 year ago
Brad Fitzpatrick 49e2d3a7bd words: add word we forgot
I explained this tails/scales list to my 5yo and he looked at me like
it was the most obvious idea ever. Of course we'd make such lists at
work!  What else do grown-ups do all day? And then he wouldn't stop
talking about coelacanths and I had no clue what he was saying or how
to spell it until I asked my phone and the phone apparently understood
me and I realized it was a fish and he was helping me? I think?

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Denton Gentry b46c5ae82a cmd/sniproxy: draw the rest of the DNS owl.
Add a DNS server which always responds as its own IP addresses.

Additionally add a tsnet TailscaleIPs() function to return the
IP addresses, both IPv4 and IPv6.

Updates https://github.com/tailscale/tailscale/issues/1748

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Joe Tsai 7e6c5a2db4
tstime: rely on stdlib parse functionality (#7482)
The time.Parse function has been optimized to the point
where it is faster than our custom implementation.
See upstream changes in:

* https://go.dev/cl/429862
* https://go.dev/cl/425197
* https://go.dev/cl/425116

Performance:

	BenchmarkGoParse3339/Z     38.75 ns/op    0 B/op    0 allocs/op
	BenchmarkGoParse3339/TZ    54.02 ns/op    0 B/op    0 allocs/op
	BenchmarkParse3339/Z       40.17 ns/op    0 B/op    0 allocs/op
	BenchmarkParse3339/TZ      87.06 ns/op    0 B/op    0 allocs/op

We can see that the stdlib implementation is now faster.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Joe Tsai 9112e78925
tstime: add Sleep (#7480)
Sleep is an interruptible sleep variation.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
License Updater 3b18e65c6a licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Mihai Parparita 6ac6ddbb47 sockstats: switch label to enum
Makes it cheaper/simpler to persist values, and encourages reuse of
labels as opposed to generating an arbitrary number.

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Aaron Klotz 9687f3700d net/dns: deal with Windows wsl.exe hangs
Despite the fact that WSL configuration is still disabled by default, we
continue to log the machine's list of WSL distros as a diagnostic measure.

Unfortunately I have seen the "wsl.exe -l" command hang indefinitely. This patch
adds a (more than reasonable) 10s timeout to ensure that tailscaled does not get
stuck while executing this operation.

I also modified the Windows implementation of NewOSConfigurator to do the
logging asynchronously, since that information is not required in order to
continue starting up.

Fixes #7476

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 year ago
Tom DNetto 2263d9c44b cmd/tsconnect: pop CTA to make everything work with tailnet lock
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
David Crawshaw 387b68fe11 tsnet: generalize loopback listener to include SOCKS5
Some languages do not give you any useful access to the sockets
underlying their networking packages. E.g. java.net.http.HttpClient
provides no official access to its dialing logic.

...but everyone supports proxies. So add a SOCKS5 proxy on the listener
we are already running.

(The function being revamped is very new,
I only added it in the last week and it wasn't part of any release,
so I believe it is fine to redo its function signature.)

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
Andrew Dunham df2561f6a2 ipn/ipnlocal: stop netmap expiry timer when resetting control client
This prevents a panic where we synthesize a new netmap in
setClientStatus after we've shut down and nil'd out the controlclient,
since that function expects to be called while connected to control.

Fixes #7392

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ib631eb90f34f6afa008d69bbb386f70da145e102
1 year ago
David Crawshaw 96a555fc5a net/socks5: add password auth support
Conforms to RFC 1929.

To support Java HTTP clients via libtailscale, who offer no other
reliable hooks into their sockets.

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
Brad Fitzpatrick 0f4359116e tsnet: add UDP support to Server.Listen
No ListenPacket support yet, but Listen with a udp network type fit
easier into netstack's model to start.

Then added an example of using it to cmd/sniproxy with a little udp
:53 handler.

No tests in tsnet yet because we don't have support for dialing over
UDP in tsnet yet. When that's done, a new test can test both sides.

Updates #5871
Updates #1748

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 9ff51ca17f wgengine/netstack: add support for custom UDP flow handlers
To be used by tsnet and sniproxy later.

Updates #5871
Updates #1748

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 045f995203 ipn/localapi: close portmapper after debug
This ensures that any mappings that are created are correctly cleaned
up, instead of waiting for them to expire in the router.

Updates #7377

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I436248ee7740eded6d8adae5df525e785a8f7ccb
1 year ago
Andrew Dunham f6cd24499b net/portmapper: relax source port check for UPnP responses
Per a packet capture provided, some gateways will reply to a UPnP
discovery packet with a UDP packet with a source port that does not come
from the UPnP port. Accept these packets with a log message.

Updates #7377

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I5d4d5b2a0275009ed60f15c20b484fe2025d094b
1 year ago
Andrew Dunham 51eb0b2cb7 net/portmapper: send UPnP protocol in upper-case
We were previously sending a lower-case "udp" protocol, whereas other
implementations like miniupnp send an upper-case "UDP" protocol. For
compatibility, use an upper-case protocol instead.

Updates #7377

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I4aed204f94e4d51b7a256d29917af1536cb1b70f
1 year ago
Andrew Dunham d379a25ae4 net/portmapper: don't pick external ports below 1024
Some devices don't let you UPnP portmap a port below 1024, so let's just
avoid that range of ports entirely.

Updates #7377

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ib7603b1c9a019162cdc4fa21744a2cae48bb1d86
1 year ago
Andrew Dunham 69f9c17555 ipn/localapi: fix panic after handler returns
Change-Id: I612f9ebf78d962e094bff908670b3ffd89f756e5
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
Maisem Ali 1a30b2d73f all: use tstest.Replace more
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
License Updater 57a44846ae licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Andrew Dunham a9c17dbf93 ipn/ipnlocal: reject unmasked routes
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic804efd24f5f536de1f2c910de3a24372d48d54d
1 year ago
Andrew Dunham 2d3ae485e3 net/interfaces: add better test for LikelyHomeRouterIP
Return a mock set of interfaces and a mock gateway during this test and
verify that LikelyHomeRouterIP returns the outcome we expect. Also
verify that we return an error if there are no IPv4 addresses available.

Follow-up to #7447

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8f06989e7f1f0bebd108861cbff17b820ed2e6e4
1 year ago
Maisem Ali b9ebf7cf14 tstest: add method to Replace values for tests
We have many function pointers that we replace for the duration of test and
restore it on test completion, add method to do that.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Andrew Dunham 12100320d2 net/interfaces: always return an IPv4 LikelyHomeRouterIP
We weren't filtering out IPv6 addresses from this function, so we could
be returning an IPv4 gateway IP and an IPv6 self IP. Per the function
comments, only return IPv4 addresses for the self IP.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: If19a4aadc343fbd4383fc5290befa0eff006799e
1 year ago
Andrew Dunham 73fa7dd7af util/slicesx: add package for generic slice functions, use
Now that we're using rand.Shuffle in a few locations, create a generic
shuffle function and use it instead. While we're at it, move the
interleaveSlices function to the same package for use.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I0b00920e5b3eea846b6cedc30bd34d978a049fd3
1 year ago
Tom DNetto 88c7d19d54 tka: compact TKA storage on startup
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Tom DNetto e2d652ec4d ipn,cmd/tailscale: implement resigning nodes on tka key removal
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Andrew Dunham 3f8e8b04fd cmd/tailscale, cmd/tailscaled: move portmapper debugging into tailscale CLI
The debug flag on tailscaled isn't available in the macOS App Store
build, since we don't have a tailscaled binary; move it to the
'tailscale debug' CLI that is available on all platforms instead,
accessed over LocalAPI.

Updates #7377

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I47bffe4461e036fab577c2e51e173f4003592ff7
1 year ago
Mihai Parparita 3e71e0ef68
net/sockstats: remove explicit dependency on wgengine/monitor
Followup to #7177 to avoid adding extra dependencies to the CLI. We
instead declare an interface for the link monitor.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
James Tucker 7b73c9628d version/distro,wgengine/router: raise WSL eth0 MTU when too low
WSL has started to set the eth0 default route interface default to 1280
MTU, which is too low to carry 1280 byte packets from tailscale0 once
wrapped in WireGuard. The change down to 1280 is very likely smaller
than necessary for almost all users. We can not easily determine the
ideal MTU, but if all the preconditions match, we raise the MTU to 1360,
which is just enough for Tailscale traffic to work.

Updates #4833
Updates #7346

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
shayne d92ef4c215
cmd/derper: randomize IPs on refreshBootstrapDNS (#7440)
This is to address a possible DNS failure on startup. Before this
change IPv6 addresses would be listed first, and the client dialer would
fail for hosts without IPv6 connectivity.
1 year ago
Andrew Dunham 27575cd52d net/dnsfallback: shuffle returned IPs
This ensures that we're trying multiple returned IPs, since the DERP
servers return the same response to all queries. This should increase
the chances that we eventually reach a working IP.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ie8d4fb93df96da910fae49ae71bf3e402b9fdecc
1 year ago
Julia at Tailscale ef6f66bb9a
api.md: refresh of API docs
Update API documentation to include explanation of resources, a cleaner and more consistent structure, updated terminology, and fixes to a few errors and omissions.

Signed-off-by: Julia Stein <julia@tailscale.com>
Signed-off-by: Will Norris <will@tailscale.com>
Co-authored-by: Will Norris <will@tailscale.com>
1 year ago
Brad Fitzpatrick 1410682fb6 cmd/sniproxy: add start of a tsnet-based SNI proxy
$ curl https://canhazip.com/
    170.173.0.21
    $ curl --resolve canhazip.com:443:100.85.165.81 https://canhazip.com/
    34.223.127.151

Updates #1748

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Joe Tsai 283a84724f
types/logid: simplify implementation (#7415)
Share the same underlying implementation for both PrivateID and PublicID.
For the shared methods, declare them in the same order.
Only keep documentation on methods without obvious meaning.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Maisem Ali e1530cdfcc cmd/containerboot,kube: consolidate the two kube clients
We had two implemenetations of the kube client, merge them.

containerboot was also using a raw http.Transport, this also has
the side effect of making it use a http.Client

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Flakes Updater 5eb8a2a86a go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Andrew Dunham d8286d0dc2 go.mod: bump golang.org/x/image to latest version
This resolves a dependabot alert, though the alert does not affect us:
    https://github.com/tailscale/tailscale/security/dependabot/6

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I087de6f22fb4821d0035fc16b603f9692581b9bd
1 year ago
Denton Gentry 51288221ce cmd/tailscale: use request Schema+Host for QNAP authLogin.cgi
QNAP allows users to set the port number for the management WebUI,
which includes authLogin.cgi. If they do, then connecting to
localhost:8080 fails.

https://github.com/tailscale/tailscale-qpkg/issues/74#issuecomment-1407486911

Fixes https://github.com/tailscale/tailscale/issues/7108

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
tailscale-license-updater[bot] 06302e30ae
licenses: update win/apple licenses (#7423)
Signed-off-by: License Updater <noreply@tailscale.com>
Co-authored-by: License Updater <noreply@tailscale.com>
1 year ago
David Anderson 311352d195 release/dist/cli: add --verbose to print subcommand output
By default, cmd/dist only prints the output of failed commands.
With this, you can turn all the noisy output back on.

Updates tailscale/corp#9045

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 0df11253ec release/dist: add a helper to run commands
The helper suppresses output if the command runs successfully. If the
command fails, it dumps the buffered output to stdout before returning
the error. This means the happy path isn't swamped by debug noise or
xcode being intensely verbose about what kind of day it's having,
but you still get debug output when something goes wrong.

Updates tailscale/corp#9045

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Aaron Klotz f18beaa1e4 cmd/mkmanifest, cmd/tailscale, cmd/tailscaled: remove Windows arm32 resources from OSS
Given recent changes in corp, I originally thought we could remove all of the
syso files, but then I realized that we still need them so that binaries built
purely from OSS (without going through corp) will still receive a manifest.

We can remove the arm32 one though, since we don't support 32-bit ARM on Windows.

Updates https://github.com/tailscale/corp/issues/9576

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 year ago
Sonia Appasamy 7985f5243a cmd/k8s-operator: update device authorization copy
"Device Authorization" was recently renamed to "Device Approval"
on the control side. This change updates the k8s operator to match.

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
1 year ago
Tom DNetto ff168a806e tka: implement compaction logic
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Sonia Appasamy bb7033174c cmd/tsconnect: update device authorization copy
"Device Authorization" was recently renamed to "Device Approval"
on the control side. This change updates tsconnect to match.

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
1 year ago
Joe Tsai 7e4788e383
logtail: delete ID types and functions (#7412)
These have been moved to the types/logid package.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Mihai Parparita 9cb332f0e2 sockstats: instrument networking code paths
Uses the hooks added by tailscale/go#45 to instrument the reads and
writes on the major code paths that do network I/O in the client. The
convention is to use "<package>.<type>:<label>" as the annotation for
the responsible code path.

Enabled on iOS, macOS and Android only, since mobile platforms are the
ones we're most interested in, and we are less sensitive to any
throughput degradation due to the per-I/O callback overhead (macOS is
also enabled for ease of testing during development).

For now just exposed as counters on a /v0/sockstats PeerAPI endpoint.

We also keep track of the current interface so that we can break out
the stats by interface.

Updates tailscale/corp#9230
Updates #3363

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Sonia Appasamy 0c1510739c cmd/tailscale/cli: update device authorization copy
"Device Authorization" was recently renamed to "Device Approval"
on the control side. This change updates the linux cli to match.

Signed-off-by: Sonia Appasamy <sonia@tailscale.com>
1 year ago
Joe Tsai 06134e9521
types/logid: remove MustParsePublicID (#7405)
Ever since the introduction of the "must" package,
most MustXXX functions are no longer necessary.
Remove this as it is no longer depended upon
from within this repository and by the internal private repository.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Joe Tsai 0d19f5d421
all: replace logtail.{Public,Private}ID with logid.{Public,Private}ID (#7404)
The log ID types were moved to a separate package so that
code that only depend on log ID types do not need to link
in the logic for the logtail client itself.
Not all code need the logtail client.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
David Crawshaw d41f6a8752 tsnet: do not error on NeedsMachineAuth for Up
It turns out even with an AuthKey that pre-approves devices on a tailnet
with machine auth turned on, we still temporarily see the
NeedsMachineAuth state. So remove that error (for now).

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
David Crawshaw 768df4ff7a tsnet: add a LocalAPI listener on loopback, with basic auth
This is for use by LocalAPI clients written in other languages that
don't appear to be able to talk HTTP over a socket (e.g.
java.net.http.HttpClient).

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
Vladimir Pouzanov e3211ff88b
Add support for OAuth tokens #7394 (#7393)
Signed-off-by: Vladimir Pouzanov <farcaller@gmail.com>
1 year ago
Maisem Ali 49c206fe1e tailcfg,hostinfo: add App field to identify tsnet uses
This allows us to differentiate between the various tsnet apps that
we have like `golinks` and `k8s-operator`.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Mihai Parparita 780c56e119 ipn/ipnlocal: add delegated interface information to /interfaces PeerAPI handler
Exposes the delegated interface data added by #7248 in the debug
endpoint. I would have found it useful when working on that PR, and
it may be handy in the future as well.

Also makes the interfaces table slightly easier to parse by adding
borders to it. To make then nicer-looking, the CSP was relaxed to allow
inline styles.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn e484e1c0fc
words: just words, nothing but words (#7384)
nothing in relation to fish at all.

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
Denton Gentry bf7573c9ee cmd/nginx-auth: build for arm64
Fixes https://github.com/tailscale/tailscale/issues/6978

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Denton Gentry 9ab992e7a1 syncs: re-enable TestWatchMultipleValues
We've updated to a different set of CI machines since this test
was disabled.

Fixes https://github.com/tailscale/tailscale/issues/1513

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Maisem Ali 0582829e00 ssh/tailssh: try launching commands with /usr/bin/login on macOS
Updates #4939

Co-authored-by: Adam Eijdenberg <adam@continusec.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Charlotte Brandhorst-Satzkorn e851d134cf
words: grasping at straws... wait, do straws have tails? (#7376)
One might argue they have two, but until that hypothesis can be proven
these tails and scales will have to do!

Signed-off-by: Charlotte Brandhorst-Satzkorn <charlotte@tailscale.com>
1 year ago
David Anderson 04be5ea725 release/dist/cli: default to "all" for list if no filters given
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Jordan Whited d4122c9f0a
cmd/tailscale/cli: fix TestUpdatePrefs over Tailscale SSH (#7374)
Fixes #7373

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
David Anderson b0eba129e6 .github/workflows: add a pass/fail verdict job to the test workflow
Github requires explicitly listing every single job within a workflow
that is required for status checks, instead of letting you list entire
workflows. This is ludicrous, and apparently this nonsense is the
workaround.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 0ab6a7e7f5 .github/workflows: try to make the merge queue actually run CI
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 587eb32a83 release/dist: add forgotten license headers
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson cf74ee49ee release/dist/cli: factor out the CLI boilerplace from cmd/dist
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson fc4b25d9fd release: open-source release build logic for unix packages
Updates tailscale/corp#9221

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Crawshaw 44e027abca tsnet: add data transfer test
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
David Crawshaw 46467e39c2 logtail: allow multiple calls to Shutdown
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
David Crawshaw daa2f1c66e tsnet: add Up method to block until ready
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
David Anderson 64181e17c8 tool/gocross: support local toolchain for development
This makes gocross and its bootstrap script understand an absolute
path in go.toolchain.rev to mean "use the given toolchain directly".

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 66621ab38e tool/gocross: embed the version explicitly with linker flags
We need to build gocross from multiple repos, but Go's innate
git hash embedding only works when you build gocross from this repo,
not when you build it from elsewhere via 'go build
tailscale.com/tool/gocross'. Instead, explicitly embed the version
found with 'git rev-parse HEAD', which will work from any git repo.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 7444dabb68 tool/gocross: do all the bootstrap steps in a subshell
This avoids accidentally overwriting variables from the input
environment, which might non-deterministically change the behavior
of gocross.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Tom DNetto abc874b04e tka: add public API on NodeKeySignature key information
This is needed in the coordination server.

Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
License Updater 61a345c8e1 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Maisem Ali 06a10125fc cmd/k8s-operator: set hostinfo.Package
This allows identifying the operator.

Updates #5055

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
David Anderson 7e65a11df5 tool/gocross: write the wrapper script directly, rather than printing
Turns out directing the printed script into the bootstrap location leads
to irritating "text file busy" problems and then having to muck about with
tempfiles and chmod and all that. Instead, have gocross write everything
with the right values.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 499d82af8a tool/gocross: add command to print the wrapper shell script
So that when importing and using gocross from other repos, there's
an easy way to get at the right wrapper script that's in sync with
the gocross binary.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 860734aed9 tool/gocross: a tool for building Tailscale binaries
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 0b8f89c79c cmd/tsconnect: find the build dir independently of -trimpath
trimmed builds don't have absolute path information in executable
metadata, which leads the runtime.Caller approach failing
mysteriously in yarn with complaints about relative package paths.

So, instead of using embedded package metadata to find paths,
expect that we're being invoked within the tailscale repo, and
locate the tsconnect directory that way.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Tom DNetto f9b746846f tailcfg: add RPC structs for /tka/affected-sigs
These RPCs will be used to power the future 'tailscale lock remove' default behavior
of resigning signatures for which trust is about to be removed.

Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Andrew Dunham e220fa65dd util/ringbuffer: move generic ringbuffer from corp repo
Also add some basic tests for this implementation.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I307ebb6db91d0c172657befb276b38ccb638f828
1 year ago
Shayne Sweeney cd18bb68a4 gitignore: Add personal .gopath and nix build /result
Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
License Updater d38abe90be licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
David Anderson 5a2fa3aa95 .github/workflows: add armv5 and armv7 cross tests
armv5 because that's what we ship to most downstreams right now,
armv7 becuase that's what we want to ship more of.

Fixes https://github.com/tailscale/tailscale/issues/7269

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Maisem Ali 5787989d74 ssh/tailssh: detect user shell correctly on darwin
Updates #6213

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Denton Gentry 6dabb34c7f scripts/installer.sh: add GalliumOS and Sangoma Linux
Fixes https://github.com/tailscale/tailscale/issues/6541
Fixes https://github.com/tailscale/tailscale/issues/6555

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
David Anderson 093139fafd .github/workflows: fix non-collapsing CI status in PRs
CI status doesn't collapse into "everything OK" if a job gets
skipped. Instead, always run the job, but skip its only step in PRs.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Nicolas BERNARD 3db894b78c client/tailscale: add tags field to Device struct
Fixes #7302

Signed-off-by: Nicolas BERNARD <nikkau@nikkau.net>
1 year ago
David Anderson 306c8a713c .github/workflows: run CI and CodeQL in the merge queue
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 149de5e6d6 build_dist.sh: use cmd/mkversion to get version data
Replaces the former shell goop, which was a shell reimplementation
of a subset of version/mkversion.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 45d9784f9d version/mkversion: allow collecting version only from this repo
With this change, you can collect version info from either a git
checkout of the tailscale.com Go module (this repo), or a git
checkout of a repo that imports the tailscale.com Go module.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Flakes Updater 303048a7d5 go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick e8a028cf82 go.mod: bump x/crypto
No particular reason. Just good point of our release cycle for some #cleanup.

It also makes dependabot happy about something we're not using?

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Maisem Ali a7eab788e4 metrics: add SetInt64 to ease using LabelMap for gauge metrics
Set is provided by the underlying Map.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Denton Gentry 1ba0b7fd79 scripts/installer.sh: add postmarketos support.
Fixes https://github.com/tailscale/tailscale/issues/7300

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
David Anderson 7ca54c890e version/mkversion: add exports for major/minor/patch
build_dist.sh needs the minor version by itself, for some reason.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 8ed27d65ef version/mkversion: add documentation, rename internal terminology
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 1dadbbb72a version/mkversion: open-source version generation logic
In preparation for moving more of the release building here too.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Maisem Ali d811c5a7f0 cmd/tailscale/cli: handle home dir correctly on macOS for kubeconfig
This ensures that we put the kubeconfig in the correct directory from within the macOS Sandbox when
paired with tailscale/corp@3035ef7

Updates #7220

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 4a99481a11 .github/workflows: set TS_FUZZ_CURRENTLY_BROKEN to false
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Will Norris 8b9ee7a558 Makefile: add help text to Makefile
https://rosszurowski.com/log/2022/makefiles#self-documenting-makefiles
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
License Updater 300664f8ae licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
License Updater 4531be4406 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Flakes Updater 390db46aad go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick 607c3eb813 go.toolchain.rev: update to Go 1.20.1
And bump x/net for the HTTP/2 fixes.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
James Tucker ee471ca1c8 tstest/integration: enable go lookups from $PATH
Fixes tailscale/corp#9261

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Maisem Ali c01c84ea8e cmd/tailscale/cli: add "configure kubeconfig" subcommand
It takes in a node hostname and configures the local kubeconfig file to
point to that.

Updates #7220

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 181a3da513 cmd/tailscale/cli: add a hidden configure subcommand
Also make `tailscale configure-host` an alias to `tailscale configure synology`

Updates #7220

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Andrew Dunham 6927a844b1 util/linuxfw: add build constraints excluding GOARCH=arm
This isn't currently supported due to missing support in upstream
dependencies, and also we don't use this package anywhere right now.
Just conditionally skip this for now.

Fixes #7268

Change-Id: Ie7389c2c0816b39b410c02a7276051a4c18b6450
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
David Anderson 6de3459bc8 .github/workflows: fix typo
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson f145c2b65b .github/workflows: add workflow to update go.mod Nix SRI hash
So that I just get a quick PR to approve and merge instead of
periodically discovering that the SRI hash has bitrotted.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson f9667e4946 Dockerfile: fix docker build
The stamp vars got renamed and I forgot to update these scripts.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Denton Gentry fdc2018d67 wgengine/magicsock: remove superfluous "discokey" from log
The stringification of the discokey type now prepends "discokey:"
Fixes https://github.com/tailscale/tailscale/issues/3074

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
License Updater 10b20fd1c7 licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
David Anderson 2eb25686d7 .github/workflows: simplify build-only go test invocation
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 253333b8a3 .github/workflows: support disabling fuzz testing safely
OSS-Fuzz doesn't update their version of Go as quickly as we do, so
we sometimes end up with OSS-Fuzz being unable to build our code for
a few weeks. We don't want CI to be red for that entire time, but
we also don't want to forget to reenable fuzzing when OSS-Fuzz does
start working again.

This change makes two configurations worthy of a CI pass:
 - Fuzzing works, and we expected it to work. This is a normal
   happy state.
 - Fuzzing didn't compile, and we expected it to not compile. This
   is the "OSS-Fuzz temporarily broken" state.

If fuzzing is unexpectedly broken, or unexpectedly not broken, that's
a CI failure because we need to either address a fuzz finding, or
update TS_FUZZ_CURRENTLY_BROKEN to reflect the state of OSS-Fuzz.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 5e186f9fbf .github/workflows: pin version of Windows we run on
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 471053a054 .github/workflows: pin version of Ubuntu we run on
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 2a43fa4421 .github/workflows: use variant=race instead of race=true for race test
Github's matrix runner formats the race variant as '(amd64, true)' if we
use race=true. So, change the way the variable is defined so that it says
'(amd64, race)' even if that makes the if statements a bit more complex.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 9fc3d00c17 .github/workflows: add back forgotten android CI job
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 4022796484 .github/workflows: unify and matrixify all our CI steps
Instead of having a dozen files that contribute CI steps with
inconsistent configs, this one file lists out everything that,
for us, constitutes "a CI run". It also enables the slack
notification webhook to notify us exactly once on a mass breakage,
rather than once for every sub-job that fails.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson afe19d1d81 tool/go: don't use the names GOOS/GOARCH in script
The use of GOOS to mean "the compiler's host architecture" ends up
overriding whatever GOOS the user passed in, resulting in befuddling
errors like "unsupported GOOS/GOARCH pair linux/wasm" when the caller
requests js/wasm.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Jenny Zhang fe5558094c cmd/tailscale/cli: add logout and debug info to web
Fixes #7238

Signed-off-by: Jenny Zhang <jz@tailscale.com>
1 year ago
David Anderson ea8b896c6c .github/workflows: remove 'ci skip' boilerplate
We've never used the "[ci skip]" magic commit header in our history,
across all our repos. This seems to be boilerplate we imported years
ago and have since been copying around our CI configs.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
License Updater 11fafdac8f licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Denton Gentry 01d58c9b61 scripts/installer.sh: add Mendel OS and OpenMandriva.
Fixes https://github.com/tailscale/tailscale/issues/6926
Fixes https://github.com/tailscale/tailscale/issues/7076

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
David Anderson bd81d520ab cmd/printdep: print correct toolchain URL
In the switch to static toolchains, we removed a legacy oddity from the
toolchain URL structure, but forgot to update printdep.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson b64d900f0f version: fix version output for "go run"
Before (note attempted use of absent date and commit hash):

"short": "1.37.0-dev",
"long": "1.37.0-dev-t",

After:

"short": "1.37.0-ERR-BuildInfo",
"long": "1.37.0-ERR-BuildInfo",

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 70a2929a12 version: make all exported funcs compile-time constant or lazy
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 8b2ae47c31 version: unexport all vars, turn Short/Long into funcs
The other formerly exported values aren't used outside the package,
so just unexport them.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 9e6b4d7ad8 types/lazy: helpers for lazily computed values
Co-authored-by: Maisem Ali <maisem@tailscale.com>
Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Denton Gentry 5bca44d572 cmd/sync-containers: update latest and stable tags
Fixes https://github.com/tailscale/tailscale/issues/7251

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Mihai Parparita fa932fefe7 net/interfaces: redo how we get the default interface on macOS and iOS
With #6566 we added an external mechanism for getting the default
interface, and used it on macOS and iOS (see tailscale/corp#8201).
The goal was to be able to get the default physical interface even when
using an exit node (in which case the routing table would say that the
Tailscale utun* interface is the default).

However, the external mechanism turns out to be unreliable in some
cases, e.g. when multiple cellular interfaces are present/toggled (I
have occasionally gotten my phone into a state where it reports the pdp_ip1
interface as the default, even though it can't actually route traffic).

It was observed that `ifconfig -v` on macOS reports an "effective interface"
for the Tailscale utn* interface, which seems promising. By examining
the ifconfig source code, it turns out that this is done via a
SIOCGIFDELEGATE ioctl syscall. Though this is a private API, it appears
to have been around for a long time (e.g. it's in the 10.13 xnu release
at https://opensource.apple.com/source/xnu/xnu-4570.41.2/bsd/net/if_types.h.auto.html)
and thus is unlikely to go away.

We can thus use this ioctl if the routing table says that a utun*
interface is the default, and go back to the simpler mechanism that
we had before #6566.

Updates #7184
Updates #7188

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Mihai Parparita 21fda7f670 net/routetable: include unknown flags in the routetable doctor output
As part of the work on #7248 I wanted to know all of the flags on the
RouteMessage struct that we get back from macOS. Though it doesn't turn
out to be useful (when using an exit node/Tailscale is the default route,
the flags for the physical interface routes are the same), it still seems
useful from a debugging/comprehensiveness perspective.

Adds additional Darwin flags that were output once I enabled this mode.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Mihai Parparita 7d204d89c2 ipn/ipnlocal: fix passthrough of formatting arguments in PeerAPI doctor output
Followup to #7235, we were not treating the formatting arguments as
variadic. This worked OK for single values, but stopped working when
we started passing multiple values (noticed while trying out #7244).

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
David Anderson 9ad36d17a3 version: undo previous "optimization", do more work lazily
Commit 59c254579e moved a lot of work
from functions that could be eliminated at compile time (because
tests against runtime.GOOS are compile-time constant), into code
that must always run before main().

So, revert that, and instead optimize the package only by moving the
remaining string processing code behind sync.Onces.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Tom DNetto 2ca6dd1f1d wgengine: start logging DISCO frames to pcap stream
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
David Anderson da75e49223 version: return correct Meta.MajorMinorPatch in non-dev builds
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
License Updater 78980a4ccf licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Mihai Parparita 6799ef838f ipn/ipnlocal: add PeerAPI endpoint for doctor output
Useful when debugging issues (e.g. to see the full routing table), and
easier to refer to the output via a browser than trying to read it from
the logs generated by `bugreport --diagnose`.

Behind a canDebug() check, similar to the /magicsock and /interfaces
endpoints.

Updates #7184

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Brad Fitzpatrick 9e4d99305b go.toolchain.rev: bump Go toolchain
For tailscale/go#55 experimentation in another repo primarily,
but this is our source of truth, so we bump here.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
David Anderson 0e4f2bdd0c pull-toolchain.sh: don't run update-flake.sh
We no longer carry an SRI hash for the toolchain, so flake
updating is no longer needed for toolchain changes.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 33f29a1532 go.toolchain.rev: update toolchain to test iOS Go fix
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Andrew Dunham ba48ec5e39 util/linuxfw: initial implementation of package
This package is an initial implementation of something that can read
netfilter and iptables rules from the Linux kernel without needing to
shell out to an external utility; it speaks directly to the kernel using
syscalls and parses the data returned.

Currently this is read-only since it only knows how to parse a subset of
the available data.

Signed-off-by: Andrew Dunham <andrew@tailscale.com>
Change-Id: Iccadf5dcc081b73268d8ccf8884c24eb6a6f1ff5
1 year ago
Colin Adler 3c107ff301
net/connstats: fix ticker in NewStatistics (#7225)
`:=` was accidentally used, so `maxPeriod` never worked.

Signed-off-by: Colin Adler <colin1adler@gmail.com>
1 year ago
Will Norris 6ef834a6b7 get-authkey: require tags to be specified
Tailnet-owned auth keys (which all OAuth-created keys are) must include tags, since there is no user to own the registered devices.

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Maisem Ali 89bd414be6 ipn/ipnstate: update field docs on PeerStatus.
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Mihai Parparita 2f4df30c75 .github/workflows: re-enable CIFuzz job
Having an empty `on` spec results in the job still running, but it
immediately fails with a "No jobs were run" message.

Go back to the original `on: [pull_request]` spec, and disable the
workflow in the GitHub UI instead.

This reverts commit f7b3156f16.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Mihai Parparita 62f4df3257 net/interfaces, net/netns: add node attributes to control default interface getting and binding
With #6566 we started to more aggressively bind to the default interface
on Darwin. We are seeing some reports of the wrong cellular interface
being chosen on iOS. To help with the investigation, this adds to knobs
to control the behavior changes:
- CapabilityDebugDisableAlternateDefaultRouteInterface disables the
  alternate function that we use to get the default interface on macOS
  and iOS (implemented in tailscale/corp#8201). We still log what it
  would have returned so we can see if it gets things wrong.
- CapabilityDebugDisableBindConnToInterface is a bigger hammer that
  disables binding of connections to the default interface altogether.

Updates #7184
Updates #7188

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Brad Fitzpatrick fb84ccd82d control/controlhttp: don't require valid TLS cert for Noise connection
We don't require any cert at all for Noise-over-plaintext-port-80-HTTP,
so why require a valid cert chain for Noise-over-HTTPS? The reason we use
HTTPS at all is to get through firewalls that allow tcp/443 but not tcp/80,
not because we need the security properties of TLS.

Updates #3198

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 2477fc4952 net/netutil: only check Linux sysctls w/ procfs, assume absent means false
Fixes #7217

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Maisem Ali 05adf22383 cmd/k8s-operator: add support for running an auth proxy
Updates #5055

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Mihai Parparita 31e2e9a300 ipn: remove unused NLKeyStateKey constant
We stopped writing network lock keys as separate items with #6315,
the constant is no longer used.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Mihai Parparita f0f2b2e22b logtail: increase maximum log line size in low memory mode
The 255 byte limit was chosen more than 3 years ago (tailscale/corp@929635c9d9),
when iOS was operating under much more significant memory constraints.
With iOS 15 the network extension has an increased limit, so increasing
it to 4K should be fine.

The motivating factor was that the network interfaces being logged
by linkChange in wgengine/userspace.go were getting truncated, and it
would be useful to know why in some cases we're choosing the pdp_ip1
cell interface instead of the pdp_ip0 one.

Updates #7184
Updates #7188

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
M. J. Fromberger 9be47f789c
ipn/ipnlocal: fix the path for writing cert files (#7203)
Fixes #7202.

Change-Id: I1f8e9c59d5e42e7df7a3fbbd82ae2b4293845916
Signed-off-by: M. J. Fromberger <fromberger@tailscale.com>
1 year ago
Andrew Dunham cab2b2b59e ipn/localapi: print envknobs on bugreport
Previously, we only printed these at startup; print those when the user
generates a bugreport as we so we don't have to go spelunking through
the logs.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: If5b0970f09fcb4cf8839958af5d37f84e0ba6ed2
1 year ago
David Anderson 59c254579e version: unify and optimize the various not-version funcs
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Maisem Ali 0fd2f71a1e ipn/ipnlocal: use presence of NodeID to identify logins
The profileManager was using the LoginName as a proxy to figure out if the profile
had logged in, however the LoginName is not present if the node was created with an
Auth Key that does not have an associated user.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 2a094181df .github/workflows: use ./tool/go in go mod tidy
Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Andrew Dunham 6d84f3409b ipn/ipnlocal: handle more edge cases in netmap expiry timer
We now handle the case where the NetworkMap.SelfNode has already expired
and do not return an expiry time in the past (which causes an ~infinite
loop of timers to fire).

Additionally, we now add an explicit check to ensure that the next
expiry time is never before the current local-to-the-system time, to
ensure that we don't end up in a similar situation due to clock skew.

Finally, we add more tests for this logic to ensure that we don't
regress on these edge cases.

Fixes #7193

Change-Id: Iaf8e3d83be1d133a7aab7f8d62939e508cc53f9c
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
Tom DNetto 99b9d7a621 all: implement pcap streaming for datapath debugging
Updates: tailscale/corp#8470

Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
David Anderson 1acdcff63e go.toolchain.rev: update toolchain to test ios workaround
Updates tailscale/corp#9061

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Denton Gentry 4daba23cd4 cmd/get-authkey: add an OAuth API client to produce an authkey
Updates https://github.com/tailscale/tailscale/issues/3243

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Maisem Ali 6bae55e351 ipn/ipnlocal: add support to store certs in k8s secrets
Fixes #5676

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Mihai Parparita 0e3fb91a39 net/dns/resolver: remove maxDoHInFlight
It was originally added to control memory use on iOS (#2490), but then
was relaxed conditionally when running on iOS 15 (#3098). Now that we
require iOS 15, there's no need for the limit at all, so simplify back
to the original state.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Mihai Parparita b6908181ff net/tshttpproxy: more directly use Transport proxy CONNECT hooks
GetProxyConnectHeader (golang/go#41048) was upstreamed in Go 1.16 and
OnProxyConnectResponse (golang/go#54299) in Go 1.20, thus we no longer
need to guard their use by the tailscale_go build tag.

Updates #7123

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
License Updater 0e1403ec39 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
David Crawshaw 8cf2805cca tailcfg, localapi: plumb device token to server
Updates tailscale/corp#8940

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
Brad Fitzpatrick 38b32be926 tailcfg: add wire fields/docs for resuming streaming map sessions
No implementation yet.

Updates #7175

Change-Id: Id242d47cdd83afe4d254c8c5826f058fe39c8bfd
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 880a41bfcc net/dns/resolver: add envknob to debug exit node DNS queries on on Windows
Add the envknob TS_DEBUG_EXIT_NODE_DNS_NET_PKG, which enables more
verbose debug logging when calling the handleExitNodeDNSQueryWithNetPkg
function. This function is currently only called on Windows and Android.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ieb3ca7b98837d7dc69cd9ca47609c1c52e3afd7b
1 year ago
Andrew Dunham d2301db49c ipn/localapi: print node IDs, pubkeys, and expiry on bugreport
Having this information near the "user bugreport" line makes it easier
to identify the node and expiry without spelunking through the rest of
the logs.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I1597c783efc06574fa4c8f211e68d835f20b6ccb
1 year ago
License Updater 0aa7b495d5 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
David Anderson 02a2dcfc86 go.toolchain.rev: use new statically built toolchain
Also removes the toolchain builds from flake.nix. For now the flake
build uses upstream Go 1.20, a followup change will switch it back to
our custom toolchain.

Updates tailscale/corp#9005

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Andrew Dunham 2dc3dc21a8 util/multierr: implement Go 1.20+'s multiple error Unwrap
Now that Go 1.20 is released, multierr.Error can implement
Unwrap() []error

Updates #7123

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic28c2579de6799801836c447afbca8cdcba732cf
1 year ago
Andrew Dunham 5ba2543828 ipn/ipnlocal: print warning about DNS servers in bugreport --diagnose
If the user passes the --diagnose flag, print a warning if any of the
default or fallback DNS resolvers are Tailscale IPs. This can interfere
with the ability to connect to the controlplane, and is typically
something to pay attention to if there's a connectivity issue.

Change-Id: Ib14bf6228c037877fbdcd22b069212b1a4b2c456
Signed-off-by: Andrew Dunham <andrew@tailscale.com>
1 year ago
License Updater c4eb857405 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick 03645f0c27 net/{netns,netstat}: use new x/sys/cpu.IsBigEndian
See golang/go#57237

Change-Id: If47ab6de7c1610998a5808e945c4177c561eab45
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 2755f3843c health, net/tlsdial: add healthcheck for self-signed cert
When we make a connection to a server, we previously would verify with
the system roots, and then fall back to verifying with our baked-in
Let's Encrypt root if the system root cert verification failed.

We now explicitly check for, and log a health error on, self-signed
certificates. Additionally, we now always verify against our baked-in
Let's Encrypt root certificate and log an error if that isn't
successful. We don't consider this a health failure, since if we ever
change our server certificate issuer in the future older non-updated
versions of Tailscale will no longer be healthy despite being able to
connect.

Updates #3198

Change-Id: I00be5ceb8afee544ee795e3c7a2815476abc4abf
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
Andrew Dunham 7393ce5e4f wgengine/magicsock: add envknob to print information about port selection
To aid in debugging where a customer has static port-forwards set up and
there are issues establishing a connection through that port.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic5558bcdb40c9119b83f79dcacf2233b07777f2a
1 year ago
Brad Fitzpatrick cf8dd7aa09 all: use Go 1.20's bytes.Clone
Updates #7123
Updates #6257 (more to do in other repos)

Change-Id: I073e2a6d81a5d7fbecc29caddb7e057ff65239d0
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick f7b3156f16 .github/workflows: delete CIFuzz job
It doesn't yet support Go 1.20. We can bring it back later.

Updates #7123

Change-Id: I6c4a4090e910d06f34c3f4d612e737989fe85812
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick b1248442c3 all: update to Go 1.20, use strings.CutPrefix/Suffix instead of our fork
Updates #7123
Updates #5309

Change-Id: I90bcd87a2fb85a91834a0dd4be6e03db08438672
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 623176ebc9 go.toolchain.branch: update to Go 1.20
Updates #7123

Change-Id: I64f6d8de5bb511a23318118b4ea1146247f1ad7c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Will Norris 10085063fb util/vizerror: add As function to get wrapped Error
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris 51e1ab5560 fixup! util/vizerror: add new package for visible errors
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris 648aa00a28 fixup! util/vizerror: add new package for visible errors
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris a6c6979b85 fixup! util/vizerror: add new package for visible errors
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris 598ec463bc fixup! util/vizerror: add new package for visible errors
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris 8e6a1ab175 util/vizerror: add new package for visible errors
Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Brad Fitzpatrick 27d146d4f8 .github/ISSUE_TEMPLATE: add link to wiki/OtherSoftwareInterop
Add question about https://github.com/tailscale/tailscale/wiki/OtherSoftwareInterop
in the issue template.

Change-Id: I6ca374654e9f67be9cb447bb5d5f66a9087fd945
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick ca45fe2d46 cmd/tailscale/cli: delete ActLikeCLI
It's since been rewritten in Swift.

 #cleanup

Change-Id: I0860d681e8728697804ce565f63c5613b8b1088c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
shayne 30e0156430
nix: update nixpkgs flake, override go_1_20 for tailscale_go (#7139)
Bleeding edge Tailscale Nix flake broke after updating to go1.20rc3.

Go 1.20 moved to Go 1.17 as a bootstarp toolchain. Fortunately nixpkgs
nixos-unstable already had a 1.20.nix with bootstrap117.nix.

```
❯ ./result/bin/tailscale version
1.37.0-dev
  track: unstable (dev); frequent updates and bugs are likely
  go version: go1.20rc3-ts6a17f14c05
```

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
David Anderson f8fc3db59c flake.nix: update SRI hash.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Crawshaw 4136f27f35 ipn/localapi: fix validHost parsing logic
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
1 year ago
Mihai Parparita 0039993359 cmd/tsconnect: update to xterm.js 5.1
It includes xtermjs/xterm.js#4216, which improves handling of some
escape sequences. Unfortunately it's not enough to fix the issue
with `ponysay`, but it does not hurt to be up to date.

Updates #6090

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
License Updater d560a4697a licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Andrew Dunham d1146dc701 ipn/ipnlocal: rate-limit diagnose logs in bugreport
We can log too quickly for logtail to catch up, even when we opt out of
log rate-limiting. When the user passes the --diagnose flag to
bugreport, we use a token bucket to control how many logs per second are
printed and sleep until we're able to write more.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: If27672d66b621b589280bd0fe228de367ffcbd8f
1 year ago
M. J. Fromberger 3eae75b1b8
ci: make gofmt check fail for a non-empty diff (#7131)
Fixes #7130.

Change-Id: If47eb472ea98a8d8b250c5c681c7862d252645fb
Signed-off-by: M. J. Fromberger <fromberger@tailscale.com>
1 year ago
Anton Tolchanov 100d8e909e cmd/derpprobe: migrate to the prober framework
`prober.DERP` was created in #5988 based on derpprobe. Having used it
instead of derpprobe for a few months, I think we have enough confidence
that it works and can now migrate derpprobe to use the prober framework
and get rid of code duplication.

A few notable changes in behaviour:
- results of STUN probes over IPv4 and IPv6 are now reported separately;
- TLS probing now includes OCSP verification;
- probe names in the output have changed;
- ability to send Slack notification from the prober has been removed.
  Instead, the prober now exports metrics in Expvar (/debug/vars) and
  Prometheus (/debug/varz) formats.

Fixes https://github.com/tailscale/corp/issues/8497

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Nick Kirby fac1632ed9 Update CodeQL action to v2
There's an error in the `Perform CodeQL Analysis` step saying to upgrade to v2 as v1 was deprecated on 18th January.

Signed-off-by: Nick Kirby <nrkirb@gmail.com>
1 year ago
Jordan Whited 39e52c4b0a
wgengine/magicsock: fix de-dup disco ping handling for netmap endpoints (#7118)
Fixes #7116

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
Brad Fitzpatrick 01e736e1d5 go.toolchain.rev: update to Go 1.20rc3
Updates #7123

Change-Id: Ibdf53530251c120e7e20c24abcf4a05f2ff7ac97
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Maisem Ali 04b57a371e ipn/ipnlocal: drop not required StateKey parameter
This is #cleanup now that #7121 is merged.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Mihai Parparita 73d33e3f20 cmd/tsconnect: use empty string as the default state store key
Makes the Wasm client more similar to the others, and allows the default
profile to be correctly picked up when restarting the client in dev
mode (where we persist the state in sessionStorage).

Also update README to reflect that Go wasm changes can be picked up
with just a reload (as of #5383)

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Maisem Ali 5bba65e978 net/memnet: rename from net/nettest
This is just #cleanup to resolve a TODO

Also add a package doc.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Maisem Ali 4441609d8f safesocket: remove the now unused WindowsLocalPort
Also drop the port param from safesocket.Listen. #cleanup

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
David Anderson fede3cd704 flake.nix: update SRI hash for Go modules.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson e51cf1b09d cmd/k8s-operator: use unstable tailscale image as well
We need a post-1.36 tailscale image to handle custom hostnames correctly.

Updates #502

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Jordan Whited 7921198c05
wgengine/magicsock: de-dup disco pings (#7093)
Fixes #7078

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
David Anderson 0dc9cbc9ab cmd/k8s-operator: use the unstable operator image
There is no stable release yet, and for alpha we want people on the
unstable build while we iterate.

Updates #502

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 4950e6117e build_docker.sh: use docker hub for base image hosting.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 969b9ed91f build_docker.sh: set good repo defaults based on the target.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
License Updater 5242e0f291 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
David Anderson f991288ceb build_docker.sh: don't push to ghcr by default.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Mihai Parparita 4973956419 ipn/ipnlocal: add /reset-auth LocalAPI endpoint
The iOS has a command to reset the persisted state of the app, but it
was doing its own direct keychain manipulation. This proved to be
brittle (since we changed how preferences are stored with #6022), so
we instead add a LocalAPI endpoint to do do this, which can be updated
in tandem.

This clears the same state as the iOS implementation (tailscale/corp#3186),
that is the machine key and preferences (which includes the node key).
Notably this does not clear the logtail ID, so that logs from the device
still end up in the same place.

Updates tailscale/corp#8923

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Will Norris 947c14793a all: update tools that manage copyright headers
Update all code generation tools, and those that check for license
headers to use the new standard header.

Also update copyright statement in LICENSE file.

Fixes #6865

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Will Norris 71029cea2d all: update copyright and license headers
This updates all source files to use a new standard header for copyright
and license declaration.  Notably, copyright no longer includes a date,
and we now use the standard SPDX-License-Identifier header.

This commit was done almost entirely mechanically with perl, and then
some minimal manual fixes.

Updates #6865

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Walter Poupore 11f7f7d4a0
docs/k8s: Use TS_AUTHKEY instead of TS_AUTH_KEY (#7092)
Updates https://github.com/tailscale/tailscale-www/issues/2199.

Signed-off-by: Walter Poupore <walterp@tailscale.com>
1 year ago
Andrew Dunham 50da265608 net/netns: add post-review comments
Follow-up to #7065 with some comments from Brad's review.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ia1219f4fa25479b2dada38ffe421065b408c5954
1 year ago
Brad Fitzpatrick 2fc8de485c net/netstat: document the Windows netstat code a bit more
And defensively bound allocation.

Updates tailscale/corp#8878

Change-Id: Iaa07479ea2ea28ee1ac3326ab025046d6d785b00
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Mihai Parparita 8c20da2568 util/httpm: add another HTTP method
Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Aaron Klotz 4a869048bf net/netstat: add nil checks to Windows OSMetadata implementation
The API documentation does claim to output empty strings under certain
conditions, but we're sometimes seeing nil pointers in the wild, not empty
strings.

Fixes https://github.com/tailscale/corp/issues/8878

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 year ago
License Updater 8c03a31d10 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick 0d794a10ff go.mod: bump wintun-go
For https://git.zx2c4.com/wintun-go/commit/?id=0fa3db229ce2036ae779de8ba03d336b7aa826bd

Updates #6647

Change-Id: I1686b2c77df331fcb9fa4fae88e08232bb95f10b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick a1b4ab34e6 util/httpm: add new package for prettier HTTP method constants
See package doc.

Change-Id: Ibbfc8e1f98294217c56f3a9452bd93ffa3103572
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 2703d6916f net/netns: add functionality to bind outgoing sockets based on route table
When turned on via environment variable (off by default), this will use
the BSD routing APIs to query what interface index a socket should be
bound to, rather than binding to the default interface in all cases.

Updates #5719
Updates #5940

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ib4c919471f377b7a08cd3413f8e8caacb29fee0b
1 year ago
Denton Gentry 7439bc7ba6 cmd/sync-containers: add github.Keychain
Running sync-containers in a GitHub workflow will be
simpler if we check github.Keychain, which uses the
GITHUB_TOKEN if present.

Updates https://github.com/tailscale/corp/issues/8461

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
David Anderson 9bd6a2fb8d cmd/k8s-operator: support setting a custom hostname.
Updates #502

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Kris Brandow d5cb016cef tailcfg: add caps and SSH action for SSH hauling
Add capabilities and an SSH action for SSH session hauling.

Updates #7069

Signed-off-by: Kris Brandow <kris@tailscale.com>
1 year ago
shayne 6f992909f0
hostinfo: [windows] check if running via Scoop (#7068)
You can now install Tailscale on Windows via [Scoop](https://scoop.sh).

This change adds a check to `packageTypeWindows()`, looking at the exe's path, and
checking if it starts with: `C:\User\<NAME>\scoop\apps\tailscale`. If so, it
returns `"scoop"` as the package type.

Fixes: #6988

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
Xe Iaso 038d25bd04
cmd/nginx-auth: update Expected-Tailnet documentation (#6055)
Signed-off-by: Xe Iaso <xe@tailscale.com>
1 year ago
phirework 2d29f77b24
cmd/tailscale/cli: fix TUNmode display on synology web page (#7064)
Fixes #7059

Signed-off-by: Jenny Zhang <jz@tailscale.com>

Signed-off-by: Jenny Zhang <jz@tailscale.com>
1 year ago
License Updater 2adbb48632 licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Denton Gentry 9af7e8a0ff VERSION.txt: this is 1.37
Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Andrew Dunham 44d73ce932 ipn/ipnlocal, net/dnscache: allow configuring dnscache logging via capability
This allows users to temporarily enable/disable dnscache logging via a
new node capability, to aid in debugging strange connectivity issues.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I46cf2596a8ae4c1913880a78d0033f8b668edc08
1 year ago
Brad Fitzpatrick d8feeeee4c wgengine/magicsock: fix buggy fast path in Conn.SetNetworkMap
Spotted by Maisem.

Fixes #6680

Change-Id: I5fdc01de8b006a1c43a2a4848f69397f54b4453a
Co-authored-By: Maisem Ali <maisem@tailscale.com>
Co-authored-By: Andrew Dunham <andrew@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Vince Prignano 30380403d0 cmd/k8s-operator: remove use of InjectClient (deprecated)
The dependency injection functionality has been deprecated a while back
and it'll be removed in the 0.15 release of Controller Runtime. This
changeset sets the Client after creating the Manager, instead of using
InjectClient.

Signed-off-by: Vince Prignano <vince@prigna.com>
1 year ago
Anton Tolchanov b49aa6ac31 scripts: explicitly install tailscale-archive-keyring
This will ensure that the `tailscale-archive-keyring` Debian package
gets installed by the installer script.

Updates #3151

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Anton Tolchanov 586a88c710 hostinfo: add an environment type for Replit
Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Anton Tolchanov e8b695626e cmd/mkpkg: allow specifying recommended dependencies
Updates #3151

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
Harry Bowron c1daa42c24
client/tailscale/keys: fix client.Keys unmarshalling
Signed-off-by: Author Name hbowron@gmail.com
Signed-off-by: Harry Bowron <harry@bolt.com>

Fixes #7020
1 year ago
Brad Fitzpatrick 6e5faff51e ipn/ipnlocal: add health warning for Tailscale SSH + SELinux
Updates #4908

Change-Id: If46be5045b13dd5c3068c334642f89b5917ec861
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick c8db70fd73 cmd/tailscale/cli: add debug set-expire command for testing
Updates tailscale/corp#8811
Updates tailscale/corp#8613

Change-Id: I1c87806ca3ccc5c43e7ddbd6b4d521f73f7d29f1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 140b9aad5c ipn/ipnlocal: fire expiry timer when the current node expires
The current node isn't in NetMap.Peers, so without this we would not
have fired this timer on self expiry.

Updates #6932

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Id57f96985397e372f9226802d63b42ff92c95093
1 year ago
James Tucker e002260b62 wgengine/wglog: add a prefix for all wireguard logs
Fixes #7041

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Brad Fitzpatrick 06fff461dc ipn/ipnstate: add PeerStatus.KeyExpiry for tailscale status --json
Fixes #6712

Change-Id: I817cd5342fac8a956fcefda2d63158fa488f3395
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick b6aa1c1f22 envknob, hostinfo, ipn/ipnlocal: add start of opt-in remote update support
Updates #6907

Change-Id: I85db4f6f831dd5ff7a9ef4bfa25902607e0c1558
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham b74db24149 tstest/integration: mark all integration tests as flaky
Updates #7036

Change-Id: I3aec5ad680078199ba984bf8afc20b2f2eb37257
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
License Updater 65c9ce5a1b licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick 64547b2b86 tailcfg,hostinfo: add Hostinfo.Machine and Hostinfo.GoArchVar
For detecting a non-ideal binary running on the current CPU.

And for helping detect the best Synology package to update to.

Updates #6995

Change-Id: I722f806675b60ce95364471b11c388150c0d4aea
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick fd92fbd69e cmd/tailscale/cli: only give systemctl hint on systemd systems
Per recent user confusion on a QNAP issue.

Change-Id: Ibda00013df793fb831f4088b40be8a04dfad17c2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick d5100e0910 net/connstats: mark TestConcurrent as flaky
Updates #7030

Change-Id: Ic46da5e5690b90b95028a68a3cf967ad86881e28
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick ba5aa2c486 version, cmd/tailscale: add version.Meta, tailscale version --json
Add `tailscale version --json` JSON output mode. This will be used
later for a double-opt-in (per node consent like Tailscale SSH +
control config) to let admins do remote upgrades via `tailscale
update` via a c2n call, which would then need to verify the
cmd/tailscale found on disk for running tailscale update corresponds
to the running tailscaled, refusing if anything looks amiss.

Plus JSON output modes are just nice to have, rather than parsing
unstable/fragile/obscure text formats.

Updates #6995
Updates #6907

Change-Id: I7821ab7fbea4612f4b9b7bdc1be1ad1095aca71b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 5ca22a0068 cmd/tailscale/cli: make 'tailscale update' support Debian/Ubuntu apt
Updates #6995

Change-Id: I3355435db583755e0fc73d76347f6423b8939dfb
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
shayne 4471e403aa
ipn/ipnlocal: [serve] listen on all-interfaces for macOS sandboxed (#6771)
On macOS (AppStore and macsys), we need to bind to ""/all-interfaces
due to the network sandbox. Ideally we would only bind to the
Tailscale interface, but macOS errors out if we try to
to listen on privileged ports binding only to a specific
interface.

We also implement the lc.Control hook, same as we do for
peerapi. It doesn't solve our problem but it's better that
we do and would likely be required when Apple gets around to
fixing per-interface priviliged port binding.

Fixes: #6364

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
Brad Fitzpatrick 6793685bba go.mod: bump AWS SDK past a breaking API change of theirs
They changed a type in their SDK which meant others using the AWS APIs
in their Go programs (with newer AWS modules in their caller go.mod)
and then depending on Tailscale (for e.g. tsnet) then couldn't compile
ipn/store/awsstore.

Thanks to @thisisaaronland for bringing this up.

Fixes #7019

Change-Id: I8d2919183dabd6045a96120bb52940a9bb27193b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
shayne 73399f784b
cmd/tailscale/cli: use mock impl of LocalClient for serve cmd (#6422)
Create an interface and mock implementation of tailscale.LocalClient for
serve command tests.

Updates #6304
Closes #6372

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
1 year ago
Jordan Whited fec888581a
wgengine/magicsock: retry failed single packet ops across rebinds (#6990)
The single packet WriteTo() through RebindingUDPConn.WriteBatch() was
not checking for a rebind between loading the PacketConn and writing to
it. Same with ReadFrom()/ReadBatch().

Fixes #6989

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
Brad Fitzpatrick 6edf357b96 all: start groundwork for using capver for localapi & peerapi
Updates #7015

Change-Id: I3d4c11b42a727a62eaac3262a879f29bb4ce82dd
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick c129bf1da1 cmd/tailscale/cli: un-alpha login+switch in ShortUsage docs
Change-Id: I580d4417cf03833dfa8f6a295fb416faa667c477
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 71a7b8581d cmd/tailscale/cli: make "update" work on Windows
Updates #6995

Co-authored-by: Aaron Klotz <aaron@tailscale.com>
Change-Id: I16622f43156a70b6fbc8205239fd489d7378d57b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 4fb663fbd2 various: mark more tests as flaky
Updates #2855
Updates #3598
Updates #7008

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I2b849e04646456b9f0c8a01563f2add752f4b2a4
1 year ago
Andrew Dunham 58ad21b252 wgengine/netstack: fix data race in tests
This uses the helper function added in #6173 to avoid flakes like:
    https://github.com/tailscale/tailscale/actions/runs/3826912237/jobs/6511078024

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: If3f1d3b9c0f64ffcb4ba9a30d3522ec49484f993
1 year ago
Andrew Dunham dd7057682c tailcfg: bump capver for Node.Expired
Updates #6932

Change-Id: I96c2467fa49201eb3d8df5cb36486370f598928c
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
Andrew Dunham aea251d42a cmd/testwrapper: move from corp; mark magicsock test as flaky
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ibab5860f5797b3db151d3c27855333e43a9088a4
1 year ago
Brad Fitzpatrick 2df38b1feb wgengine/magicsock: quiet log flood at tailscaled shutdown
When you hit control-C on a tailscaled (notably in dev mode, but
also on any systemctl stop/restart), there is a flood of messages like:

magicsock: doing cleanup for discovery key d:aa9c92321db0807f
magicsock: doing cleanup for discovery key d:bb0f16aacadbfd46
magicsock: doing cleanup for discovery key d:b5b2d386296536f2
magicsock: doing cleanup for discovery key d:3b640649f6796c91
magicsock: doing cleanup for discovery key d:71d7b1afbcce52cd
magicsock: doing cleanup for discovery key d:315b61d7e0111377
magicsock: doing cleanup for discovery key d:9301f63dce69bf45
magicsock: doing cleanup for discovery key d:376141884d6fe072
....

It can be hundreds or even tens of thousands.

So don't do that. Not a useful log message during shutdown.

Change-Id: I029a8510741023f740877df28adff778246c18e5
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 3addcacfe9 net/dns: fix recently added URL scheme from http to https
I typoed/brainoed in the earlier 3582628691

Change-Id: Ic198a6f9911f195d9da9fc5259b5784a4b15e5e3
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
salman eec734a578 ipn/{ipnlocal,localapi}: ensure watcher is installed before /watch-ipn-bus/ responds with 200
This change delays the first flush in the /watch-ipn-bus/ handler
until after the watcher has been successfully installed on the IPN
bus. It does this by adding a new onWatchAdded callback to
LocalBackend.WatchNotifications().

Without this, the endpoint returns a 200 almost immediatly, and
only then installs a watcher for IPN events.  This means there's a
small window where events could be missed by clients after calling
WatchIPNBus().

Fixes tailscale/corp#8594.

Signed-off-by: salman <salman@tailscale.com>
1 year ago
Brad Fitzpatrick 3eb986fe05 control/controlhttp: add TS_FORCE_NOISE_443, TS_DEBUG_NOISE_DIAL envknobs
Updates tailscale/docker-extension#49

Change-Id: I99a154c16c92228bfdf4d2cf6c58cda00e22d72f
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Tom DNetto ee6d18e35f cmd/tailscale/cli: implement --json for lock status and lock log cmds
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
License Updater 287fe83f91 licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
License Updater ef1c902c21 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick b657187a69 cmd/tailscale, logtail: add 'tailscale debug daemon-logs' logtail mechanism
Fixes #6836

Change-Id: Ia6eb39ff8972e1aa149aeeb63844a97497c2cf04
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
andig 5f96d6211a Remove redundant type declaration
Signed-off-by: andig <cpuidle@gmx.de>
1 year ago
David Anderson 72cc70ebfc flake.nix: update vendor hash.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Brad Fitzpatrick 3582628691 net/dns/resolvconffile: link to FAQ about resolv.conf being overwritten
Add link to new http://tailscale.com/s/resolvconf-overwrite page,
added in tailscale/tailscale-www#2243

Change-Id: I9718399487f2ed18bf1a112581fd168aea30f232
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 3a018e51bb ipn/ipnlocal: move handling of expired nodes to LocalBackend
In order to be able to synthesize a new NetMap when a node expires, have
LocalBackend start a timer when receiving a new NetMap that fires
slightly after the next node expires. Additionally, move the logic that
updates expired nodes into LocalBackend so it runs on every netmap
(whether received from controlclient or self-triggered).

Updates #6932

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I833390e16ad188983eac29eb34cc7574f555f2f3
1 year ago
Brad Fitzpatrick 6d85a94767 net/{packet,tstun}: fix typo in test helper docs
Change-Id: Ifc1684fe77c7d2585e049e0dfd7340910c47a67a
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick c1a2e2c380 net/{packet,tstun},wgengine/filter: fix unknown IP protocol handling
01b90df2fa added SCTP support before
(with explicit parsing for ports) and
69de3bf7bf tried to add support for
arbitrary IP protocols (as long as the ACL permited a port of "*",
since we might not know how to find ports from an arbitrary IP
protocol, if it even has such a concept). But apparently that latter
commit wasn't tested end-to-end enough. It had a lot of tests, but the
tests made assumptions about layering that either weren't true, or
regressed since 1.20. Notably, it didn't remove the (*Filter).pre
bidirectional filter that dropped all "unknown" protocol packets both
leaving and entering, even if there were explicit protocol matches
allowing them in.

Also, don't map all unknown protocols to 0. Keep their IP protocol
number parsed so it's matchable by later layers. Only reject illegal
things.

Fixes #6423
Updates #2162
Updates #2163

Change-Id: I9659b3ece86f4db51d644f9b34df78821758842c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 3386a59cf1 wgengine/filter: include IP proto number in unknown protocol errors
Updates #6423

Change-Id: I9e363922e2c24fdc42687707c069af5bba68b93e
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 006ec659e6 wgengine/filter: reorder RunOut disjunctive cases to match RunIn above
Change-Id: Ia422121cde1687044b18be7bea9e7bf51a4183b9
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick d9144c73a8 cmd/tailscale: add start of "tailscale update" command
Goal: one way for users to update Tailscale, downgrade, switch tracks,
regardless of platform (Windows, most Linux distros, macOS, Synology).

This is a start.

Updates #755, etc

Change-Id: I23466da1ba41b45f0029ca79a17f5796c2eedd92
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Mihai Parparita 67f82e62a1 ipn/ipnlocal: add Expired to PeerStatus
Needed for clients that get information via the /v0/status LocalAPI
endpoint (e.g. to not offer expired exit nodes as options).

Updates tailscale/corp#8702

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
phirework f011a0923a
cmd/tailscale/cli: style synology outgoing access info (#6959)
Follow-up to #6957.

Updates #4015

Signed-off-by: Jenny Zhang <jz@tailscale.com>
1 year ago
Andrew Dunham 11ce5b7e57 ipn/ipnlocal, wgengine/magicsock: check Expired bool on Node; print error in Ping
Change-Id: Ic5f533f175a6e1bb73d4957d8c3f970add42e82e
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
Brad Fitzpatrick 5eded58924 cmd/tailscale/cli: make web show/link Synology outgoing connection mode/docs
Fixes #4015

Change-Id: I8230bb0cc3d621b6fa02ab2462cea104fa1e9cf9
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Matthias Gabriel 355c3b2be7 control/controlhttp: fix header case-sensitivity
Change-Id: I49269bc969a80382997ec5c9de33c4f56d9dc787
Signed-off-by: Matthias Gabriel <matthias.gabriel@etit.tu-chemnitz.de>
1 year ago
Brad Fitzpatrick 61dfbc0a6e cmd/tailscale/cli: plumb TUN mode into tailscale web template
UI works remains, but data is there now.

Updates #4015

Change-Id: Ib91e94718b655ad60a63596e59468f3b3b102306
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
salman 8a1201ac42 cmd/tailscale: correct order for -terminate-tls flag in serve tcp usage
The -terminate-tls flag is for the tcp subsubcommand, not the serve
subcommand like the usage example suggests.

Signed-off-by: salman <salman@tailscale.com>
1 year ago
Brad Fitzpatrick faf2d30439 version: advertise unstable track in CLI, daemon start-up
Fixes #865

Change-Id: I166e56c3744b0a113973682b9a5327d7aec189f1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Jordan Whited 25a0091f69
net/portmapper: relax handling of UPnP resp (#6946)
Gateway devices operating as an HA pair w/VRRP or CARP may send UPnP
replies from static addresses rather than the floating gateway address.
This commit relaxes our source address verification such that we parse
responses from non-gateway IPs, and re-point the UPnP root desc
URL to the gateway IP. This ensures we are still interfacing with the
gateway device (assuming L2 security intact), even though we got a
root desc from a non-gateway address.

This relaxed handling is required for ANY port mapping to work on certain
OPNsense/pfsense distributions using CARP at the time of writing, as
miniupnpd may only listen on the static, non-gateway interface address
for PCP and PMP.

Fixes #5502

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
License Updater b76dffa594 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Andrew Dunham 6f18fbce8d tailcfg: document zero value for KeyExpiry
Change-Id: I50889f0205ecf66c415f50f9019c190448c991fc
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
Tom DNetto 2ac5474be1 net/flowtrack,wgengine/filter: refactor Cache to use generics
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Will Norris 3becf82dd3 types/views: add SliceEqualAnyOrder func
This is based on the tagsEqual func from corp/control/control.go, moved
here so that it can be reused in other places.

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
Andrew Dunham 1e67947cfa control/controlclient, tailcfg: add Node.Expired field, set for expired nodes
Nodes that are expired, taking into account the time delta calculated
from MapResponse.ControlTime have the newly-added Expired boolean set.
For additional defense-in-depth, also replicate what control does and
clear the Endpoints and DERP fields, and additionally set the node key
to a bogus value.

Updates #6932

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ia2bd6b56064416feee28aef5699ca7090940662a
1 year ago
Denton Gentry 22ebb25e83 cmd/tailscale: disable HTTPS verification for QNAP auth.
QNAP's "Force HTTPS" mode redirects even localhost HTTP to
HTTPS, but uses a self-signed certificate which fails
verification. We accommodate this by disabling checking
of the cert.

Fixes https://github.com/tailscale/tailscale/issues/6903

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
James Tucker 2afa1672ac ipn/ipnlocal: disallow unsigned peers from WoL
Unsigned peers should not be allowed to generate Wake-on-Lan packets,
only access Funnel.

Updates #6934
Updates #7515
Updates #6475

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
License Updater 237b1108b3 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Will Norris fff617c988 go.mod: bump golang.org/x/net and dependencies
I don't think CVE-2022-41717 necessarily impacts us (maybe as part of
funnel?), but it came up in a recent security scan so worth updating
anyway.

Signed-off-by: Will Norris <will@tailscale.com>
1 year ago
License Updater c684ca7a0c licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick 1116602d4c ssh/tailssh: add OpenBSD support for Tailscale SSH
And bump go.mod for https://github.com/u-root/u-root/pull/2593

Change-Id: I36ec94c5b2b76d671cb739f1e9a1a43ca1d9d1b1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick be67b8e75b ssh/tailssh: fix Tailscale SSH to non-root tailscaled
Fix regression from 337c77964b where
tailscaled started calling Setgroups. Prior to that, SSH to a non-root
tailscaled was working.

Instead, ignore any failure calling Setgroups if the groups are
already correct.

Fixes #6888

Change-Id: I561991ddb37eaf2620759c6bcaabd36e0fb2a22d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 8047dfa2dc ssh/tailssh: unify some of the incubator_* GOOS files into incubator.go
In prep for fix for #6888

Change-Id: I79f780c6467a9b7ac03017b27d412d6b0d2f7e6b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick ebbf5c57b3 README.md: update with some new links, refresh
And remove Darwin from the list, as macOS was already there.

Change-Id: I76bdcad97c926771f44a67140af21f07a8334796
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
David Anderson 39efba528f cmd/containerboot: use TS_AUTHKEY as the parameter for auth keys
We still accept the previous TS_AUTH_KEY for backwards compatibility, but the documented option name is the spelling we use everywhere else.

Updates #6321

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Brad Fitzpatrick 69c0b7e712 ipn/ipnlocal: add c2n handler to flush logtail for support debugging
Updates tailscale/corp#8564

Change-Id: I0c619d4007069f90cffd319fba66bd034d63e84d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Tom DNetto 673b3d8dbd net/dns,userspace: remove unused DNS paths, normalize query limit on iOS
With a42a594bb3, iOS uses netstack and
hence there are no longer any platforms which use the legacy MagicDNS path. As such, we remove it.

We also normalize the limit for max in-flight DNS queries on iOS (it was 64, now its 256 as per other platforms).
It was 64 for the sake of being cautious about memory, but now we have 50Mb (iOS-15 and greater) instead of 15Mb
so we have the spare headroom.

Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Brad Fitzpatrick 10eec37cd9 scripts: permit 2023 in license headers
Change-Id: Ia018cb8491871c8bf756c454d085780b75512962
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Mihai Parparita 8f2bc0708b logtail: make logs flush delay dynamic
Instead of a static FlushDelay configuration value, use a FlushDelayFn
function that we invoke every time we decide send logs. This will allow
mobile clients to be more dynamic about when to send logs.

Updates #6768

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Tom DNetto 0088c5ddc0 health,ipn/ipnlocal: report the node being locked out as a health issue
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Tom DNetto 907f85cd67 cmd/tailscale,tka: make KeyID return an error instead of panicking
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Tom DNetto 8724aa254f cmd/tailscale,tka: implement compat for TKA messages, minor UX tweaks
Signed-off-by: Tom DNetto <tom@tailscale.com>
1 year ago
Kristoffer Dalby c4e262a0fc
ipn/profiles: set default prefs based on Windows registry (#6803)
Co-authored-by: Maisem Ali maisem@tailscale.com
1 year ago
Brad Fitzpatrick eafbf8886d ipn/localapi: add localapi debug endpoints for packet filter/matches
For debugging #6423. This is easier than TS_DEBUG_MAP, as this means I
can pipe things into jq, etc.

Updates #6423

Change-Id: Ib3e7496b2eb3f47d4bed42e9b8045a441424b23c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick b2b8e62476 util/codegen: permit running in directories without copyright headers
It broke in our corp repo that lacks copyright headers.

Change-Id: Iafc433e6b6affe83b45477899455527658dc4f12
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
David Anderson 91e64ca74f cmd/tailscale/cli: redact private key in debug netmap output by default
This makes `tailscale debug watch-ipn` safe to use for troubleshooting
user issues, in addition to local debugging during development.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
License Updater d72575eaaa licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
James Tucker b2c55e62c8 net/tlsdial,tstest,version: use go command from $PATH
Go now includes the GOROOT bin directory in $PATH while running tests
and generate, so it is no longer necessary to construct a path using
runtime.GOROOT().

Fixes #6689

Signed-off-by: James Tucker <james@tailscale.com>
1 year ago
Denton Gentry 467ace7d0c cmd/tailscale: use localhost for QNAP authLogin.cgi
When the user clicks on the Tailscale app in the QNAP App Center,
we do a GET from /cgi-bin/authLogin.cgi to look up their SID.

If the user clicked "secure login" on the QNAP login page to use
HTTPS, then our access to authLogin.cgi will also use HTTPS
but the certiciate is self-signed. Our GET fails with:
    Get "https://10.1.10.41/cgi-bin/authLogin.cgi?sid=abcd0123":
    x509: cannot validate certificate for 10.1.10.41 because it
    doesn't contain any IP SANs
or similar errors.

Instead, access QNAP authentication via http://localhost:8080/
as documented in
https://download.qnap.com/dev/API_QNAP_QTS_Authentication.pdf

Fixes https://github.com/tailscale/tailscale-qpkg/issues/62

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
Brad Fitzpatrick aad6830df0 util/codegen, all: use latest year, not time.Now, in generated files
Updates #6865

Change-Id: I6b86c646968ebbd4553cf37df5e5612fbf5c5f7d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick ea70aa3d98 net/dns/resolvconffile: fix handling of multiple search domains
Fixes #6875

Change-Id: I57eb9312c9a1c81792ce2b5a0a0f254213b05df2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
License Updater 692eac23ad licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
David Anderson c86d9f2ab1 flake.nix: rename package to just "tailscale".
There is no unstability inherent in this package, it's just
unstable if you choose to import the flake at the main branch.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 7bfb9999ee cmd/printdep: support printing the toolchain SRI hash.
Updates #6845.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson d2beaea523 update-flake.sh: tooling to keep Nix SRI hashes in sync.
Also fixes the Go toolchain SRI hash from a7f05c6bb0,
it turns out I initialized the file with an SRI hash for an older
toolchain version, and because of the unique way fixed-output derivations
work in nix, nix didn't tell me about the mismatch because it just
cache-hit on the older toolchain and moved on. Sigh.

Updates #6845.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Brad Fitzpatrick 3599364312 cmd/nardump: Go tool to build Nix NARs and compute their hashes.
Updates #6845.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson a7f05c6bb0 flake.nix: init to ship unstable tailscale packages.
With this, you can import "github:tailscale/tailscale" as a nix flake,
and get access to the "tailscale-unstable" package.

Updates #6845.

Signed-off-by: David Anderson <dave@natulte.net>
1 year ago
David Anderson eb682d2a0b version: construct short hash in dev mode if GitCommit is given.
Allows a dev built to provide GitCommit and have the short hash
computed correctly, even if the Go embedded build info lacks a
git commit.

Signed-off-by: David Anderson <dave@natulte.net>
1 year ago
Denton Gentry 2a1f1c79ca scripts/installer.sh: add SUSE Enterprise Server.
Fixes https://github.com/tailscale/tailscale/issues/6840

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
License Updater 6107c65f1e licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Claire Wang a45c9f982a wgengine/netstack: change netstack API to require LocalBackend
The macOS client was forgetting to call netstack.Impl.SetLocalBackend.
Change the API so that it can't be started without one, eliminating this
class of bug. Then update all the callers.

Updates #6764

Change-Id: I2b3a4f31fdfd9fdbbbbfe25a42db0c505373562f
Signed-off-by: Claire Wang <claire@tailscale.com>
Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 84eaef0bbb ssh/tailssh: don't swallow process exit code in be-child
Thanks to @nshalman and @Soypete for debugging!

Updates #6054

Change-Id: I74550cc31f8a257b37351b8152634c768e1e0a8a
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
License Updater f3c83a06ff licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
License Updater 011f661d5b licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick caa2fe394f wgengine/netstack: delete some dead code, old comment, use atomic int types
Noticed while looking at something else; #cleanup.

Change-Id: Icde7749363014eab9bebe1dd80708f5491f933d1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Anton Tolchanov 82b9689e25
ipn/ipnlocal: maintain a proxy handler per backend (#6804)
By default, `http.Transport` keeps idle connections open hoping to re-use them in the future. Combined with a separate transport per request in HTTP proxy this results in idle connection leak.

Fixes #6773
1 year ago
Andrew Dunham 1011e64ad7 wgengine/monitor: don't log unhandled RTM_{NEW,DEL}LINK messages
These aren't handled, but it's not an error to get one.

Fixes #6806

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I1fcb9032ac36420aa72a048bf26f58360b9461f9
1 year ago
Brad Fitzpatrick be10b529ec wgengine/magicsock: add TS_DISCO_PONG_IPV4_DELAY knob to bias IPv6 paths
Fixes #6818

Change-Id: I71597a045c5b4117af69fba869cb616271c0dfe1
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick e36cdacf70 envknob: add time.Duration knob support
Updates #6818

Change-Id: I9c8147c02fb514f9f6f1f272bdb0f974c8b3ccbb
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
andig 14e8afe444 go.mod, etc: bump gvisor
Fixes #6554

Change-Id: Ia04ae37a47b67fa57091c9bfe1d45a1842589aa8
Signed-off-by: andig <cpuidle@gmx.de>
1 year ago
Brad Fitzpatrick 8aac77aa19 cmd/tailscale: fix "up" warning about netfilter-mode on Synology
Fixes #6811

Change-Id: Ia43723e6ebedc9b01729897cec271c462b16e9ae
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick f837d179b9 ssh/tailssh: fix typo in error message
"look up" is the verb. "lookup" is a noun.

Change-Id: I81c99e12c236488690758fb5c121e7e4e1622a36
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 2eff9c8277 wgengine/magicsock: avoid ReadBatch/WriteBatch on old Linux kernels
Fixes #6807

Change-Id: I161424ef8a7338e1941d5e43d72dc6529993a0e3
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 0372e14d79 net/dns: bump DNS-over-TCP size limit to 4k
We saw a few cases where we hit this limit; bumping to 4k seems
relatively uncontroversial.

Change-Id: I218fee3bc0d2fa5fde16eddc36497a73ebd7cbda
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
License Updater 98daf99775 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick 7c77c48bd4 go.toolchain.rev: bump Go
For:
dc0ce6324d
and
2cf198bc80

Updates #6792
Updates #6799

Change-Id: I58f022b5fb790e968938f90eb76e9dfdb74041fc
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 243490f932 go.mod: bump x/sys for linux/arm64 cpu SIGILL fix
Bump to get 2204b6615f

Updates #5793

Change-Id: I6ab78824047cb2c8d042f3f3bf47368ec6da5a34
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
David Anderson a1ded4c166 cmd/sync-containers: add a dry-run option.
Updates tailscale/corp#8461

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson e5fe205c31 cmd/sync-containers: program to sync tags between container registries.
Updates tailscale/corp#8461

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
License Updater 237f030cd9 licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Aaron Klotz 296f53524c netstat, portlist: update Windows implementation to disambiguate svchost processes
We change our invocations of GetExtendedTcpTable to request additional
information about the "module" responsible for the port. In addition to pid,
this output also includes sufficient metadata to enable Windows to resolve
process names and disambiguate svchost processes.

We store the OS-specific output in an OSMetadata field in netstat.Entry, which
portlist may then use as necessary to actually resolve the process/module name.

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 year ago
Brad Fitzpatrick a06217a8bd cmd/tailscale/cli: hide Windows named pipe default name in flag help
It's long & distracting for how low value it is.

Fixes #6766

Change-Id: I51364f25c0088d9e63deb9f692ba44031f12251b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 5caf609d7b go.toolchain.rev: bump Go to 1.19.4
Updates tailscale/go#36

Change-Id: I0b741c18ef0286b511a79ec39b1e91464c7ce77b
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 0f604923d3 ipn/ipnlocal: fix StatusWithoutPeers not populating parts of Status
Fixes #4311

Change-Id: Iaae0615148fa7154f4ef8f66b455e3a6c2fa9df3
Co-authored-by: Claire Wang <claire@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Aaron Klotz 3c452b9880 util/winutil: fix erroneous condition in implementation of getRegIntegerInternal
We only want to log when err != registry.ErrNotExist. The condition was backward.

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 year ago
License Updater 14d07b7b20 licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Jordan Whited 914d115f65
go.mod: bump tailscale/wireguard-go for big-endian fix (#6785)
Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
David Anderson af3127711a cmd/containerboot: allow disabling secret storage in k8s.
In some configurations, user explicitly do not want to store
tailscale state in k8s secrets, because doing that leads to
some annoying permission issues with sidecar containers.
With this change, TS_KUBE_SECRET="" and TS_STATE_DIR=/foo
will force storage to file when running in kubernetes.

Fixes #6704.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
License Updater 6d5527e4b3 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Joe Tsai d9df023e6f
net/connstats: enforce maximum number of connections (#6760)
The Tailscale logging service has a hard limit on the maximum
log message size that can be accepted.
We want to ensure that netlog messages never exceed
this limit otherwise a client cannot transmit logs.

Move the goroutine for periodically dumping netlog messages
from wgengine/netlog to net/connstats.
This allows net/connstats to manage when it dumps messages,
either based on time or by size.

Updates tailscale/corp#8427

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Brad Fitzpatrick 651e0d8aad ssh/tailssh: add envknob for default PATH
As backup plan, just in case the earlier fix's logic wasn't correct
and we want to experiment in the field or have users have a quicker
fix.

Updates #5285

Change-Id: I7447466374d11f8f609de6dfbc4d9a944770826d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
License Updater fc0fe99edf licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Brad Fitzpatrick c02ccf6424 go.mod: bump dhcp dep to remove another endian package from our tree
To pull in insomniacslk/dhcp#484 to pull in u-root/uio#8

Updates golang/go#57237

Change-Id: I1e56656e0dc9ec0b870f799fe3bc18b3caac1ee4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
License Updater 97c615889d licenses: update tailscale{,d} licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
License Updater a8f07153a6 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Anton Tolchanov 53c4892841 ipn/ipnserver: propagate http.Serve error
This ensures that we capture error returned by `Serve` and exit with a
non-zero exit code if it happens.

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
1 year ago
David Anderson 8171eb600c cmd/k8s-operator: move the operator into its own namespace.
The operator creates a fair bit of internal cluster state to manage proxying,
dumping it all in the default namespace is handy for development but rude
for production.

Updates #502

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Brad Fitzpatrick 56f7da0cfd
ssh/tailssh: set default Tailscale SSH $PATH for non-interactive commands
Fixes #5285

Co-authored-by: Andrew Dunham <andrew@tailscale.com>
Change-Id: Ic7e967bf6a53b056cac5f21dd39565d9c31563af
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Joe Tsai 350aab05e5
util/multierr: optimize New for nil cases (#6750)
Consider the following pattern:

	err1 := foo()
	err2 := bar()
	err3 := baz()
	return multierr.New(err1, err2, err3)

If err1, err2, and err3 are all nil, then multierr.New should not allocate.
Thus, modify the logic of New to count the number of distinct error values
and allocate the exactly needed slice. This also speeds up non-empty error
situation since repeatedly growing with append is slow.

Performance:

	name         old time/op    new time/op    delta
	Empty-24       41.8ns ± 2%     6.4ns ± 1%   -84.73%  (p=0.000 n=10+10)
	NonEmpty-24     120ns ± 3%      69ns ± 1%   -42.01%  (p=0.000 n=9+10)

	name         old alloc/op   new alloc/op   delta
	Empty-24        64.0B ± 0%      0.0B       -100.00%  (p=0.000 n=10+10)
	NonEmpty-24      168B ± 0%       88B ± 0%   -47.62%  (p=0.000 n=10+10)

	name         old allocs/op  new allocs/op  delta
	Empty-24         1.00 ± 0%      0.00       -100.00%  (p=0.000 n=10+10)
	NonEmpty-24      3.00 ± 0%      2.00 ± 0%   -33.33%  (p=0.000 n=10+10)

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Jordan Whited 55b24009f7
net/tstun: don't return early from a partial tun.Read() (#6745)
Fixes #6730

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
David Anderson 3a5fc233aa cmd/k8s-operator: use oauth credentials for API access.
This automates both the operator's initial login, and
provisioning/deprovisioning of proxies.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson a7ab3429b6 cmd/k8s-operator: refactor reconcile loop, un-plumbing reconcile.Result.
We used to need to do timed requeues in a few places in the reconcile logic,
and the easiest way to do that was to plumb reconcile.Result return values
around. But now we're purely event-driven, so the only thing we care about
is whether or not an error occurred.

Incidentally also fix a very minor bug where headless services would get
completely ignored, rather than reconciled into the correct state. This
shouldn't matter in practice because you can't transition from a headful
to a headless service without a deletion, but for consistency let's avoid
having a path that takes no definite action if a service of interest does
exist.

Updates #502.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Denton Gentry da53b1347b cmd/gitops-pusher: support alternate api-server URLs
Fixes https://github.com/tailscale/coral/issues/90

Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 year ago
David Anderson 835a73cc1f cmd/k8s-operator: remove unnecessary timed requeue.
Previously, we had to do blind timed requeues while waiting for
the tailscale hostname, because we looked up the hostname through
the API. But now the proxy container image writes back its hostname
to the k8s secret, so we get an event-triggered reconcile automatically
when the time is right.

Updates #502

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson d857fd00b3 cmd/k8s-operator: sprinkle debug logging throughout.
As is convention in the k8s world, use zap for structured logging. For
development, OPERATOR_LOGGING=dev switches to a more human-readable output
than JSON.

Updates #502

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 8ccd707218 cmd/k8s-operator: remove times requeues in proxy deletion path.
Our reconcile loop gets triggered again when the StatefulSet object
finally disappears (in addition to when its deletion starts, as indicated
by DeletionTimestamp != 0). So, we don't need to queue additional
reconciliations to proceed with the remainder of the cleanup, that
happens organically.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson c0fcab01ac client/tailscale: fix request object for key creation.
The request takes key capabilities as an argument, but wrapped in a parent
object.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Andrew Dunham 3f4d51c588 net/dns: don't send on closed channel when message too large
Previously, if a DNS-over-TCP message was received while there were
existing queries in-flight, and it was over the size limit, we'd close
the 'responses' channel. This would cause those in-flight queries to
send on the closed channel and panic.

Instead, don't close the channel at all and rely on s.ctx being
canceled, which will ensure that in-flight queries don't hang.

Fixes #6725

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I8267728ac37ed7ae38ddd09ce2633a5824320097
1 year ago
Brad Fitzpatrick 44be59c15a wgengine/magicsock: fix panic in wireguard-go rate limiting path
Fixes #6686

Change-Id: I1055a87141b07261afed8e36c963a69f3be26088
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Andrew Dunham 0d47cd2284 wgengine/monitor: fix panic due to race on Windows
It's possible for the 'somethingChanged' callback to be registered and
then trigger before the ctx field is assigned; move the assignment
earlier so this can't happen.

Change-Id: Ia7ee8b937299014a083ab40adf31a8b3e0db4ec5
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
1 year ago
David Anderson d81a2b2ce2 Makefile: add a target for doing dev builds of the k8s operator.
Updates #502.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 9c77205ba1 cmd/k8s-operator: add more tests for "normal" paths.
Tests cover configuring a proxy through an annotation rather than a
LoadBalancerClass, and converting between those two modes at runtime.

Updates #502.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson c902190e67 cmd/k8s-operator: factor out some of the larger expected test outputs.
For other test cases, the operator is going to produce similar generated
objects in several codepaths, and those objects are large. Move them out
to helpers so that the main test code stays a bit more intelligible.

The top-level Service that we start and end with remains in the main test
body, because its shape at the start and end is one of the main things that
varies a lot between test cases.

Updates #502.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 8dbb3b8bbe cmd/k8s-operator: remove unused structs. Cleanup missed in #6718.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 53a9cc76c7 cmd/k8s-operator: rename main.go -> operator.go.
Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson bc8f5a7734 cmd/k8s-operator: add a basic unit test.
The test verifies one of the successful reconcile paths, where
a client requests an exposed service via a LoadBalancer class.

Updates #502.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson 3b7ae39a06 cmd/k8s-operator: use the client's authkey method to create auth keys.
Also introduces an intermediary interface for the tailscale client, in
preparation for operator tests that fake out the Tailscale API interaction.

Updates #502.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Brad Fitzpatrick ca08e316af util/endian: delete package; use updated josharian/native instead
See josharian/native#3

Updates golang/go#57237

Change-Id: I238c04c6654e5b9e7d9cfb81a7bbc5e1043a84a2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Joe Tsai bd2995c14b
ipn/ipnlocal: simplify redactErr (#6716)
Use multierr.Range to iterate through an error tree
instead of multiple invocations of errors.As.
This scales better as we add more Go error types to the switch.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Joe Tsai c47578b528
util/multierr: add Range (#6643)
Errors in Go are no longer viewed as a linear chain, but a tree.
See golang/go#53435.

Add a Range function that iterates through an error
in a pre-order, depth-first order.
This matches the iteration order of errors.As in Go 1.20.

This adds the logic (but currently commented out) for having
Error implement the multi-error version of Unwrap in Go 1.20.
It is commented out currently since it causes "go vet"
to complain about having the "wrong" signature.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
1 year ago
Dave Anderson 041a0e3c27
client/tailscale: add APIs for auth key management. (#6715)
client/tailscale: add APIs for key management.

Updates #502.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
David Anderson b2d4abf25a cmd/k8s-operator: add a kubernetes operator.
This was initially developed in a separate repo, but for build/release
reasons and because go module management limits the damage of importing
k8s things now, moving it into this repo.

At time of commit, the operator enables exposing services over tailscale,
with the 'tailscale' loadBalancerClass. It also currently requires an
unreleased feature to access the Tailscale API, so is not usable yet.

Updates #502.

Signed-off-by: David Anderson <danderson@tailscale.com>
1 year ago
Mihai Parparita 47002d93a3 ipn/ipnlocal: add a few metrics for PeerAPI and LocalAPI
Mainly motivated by wanting to know how much Taildrop is used, but
also useful when tracking down how many invalid requests are
generated.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
1 year ago
Aaron Klotz 53e2010b8a cmd/tailscaled: change Windows implementation to shut down subprocess via closing its stdin
We've been doing a hard kill of the subprocess, which is only safe as long as
both the cli and gui are not running and the subprocess has had the opportunity
to clean up DNS settings etc. If unattended mode is turned on, this is definitely
unsafe.

I changed babysitProc to close the subprocess's stdin to make it shut down, and
then I plumbed a cancel function into the stdin reader on the subprocess side.

Fixes https://github.com/tailscale/corp/issues/5621

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
1 year ago
缘生 9c67395334
feat(build): add support on Loongnix-Server (loong64) (#6233)
Makefile, .github/workflow: add tests, targets for GOARCH=loong64 (Loongnix)

Signed-off-by: ysicing <i@ysicing.me>
1 year ago
Brad Fitzpatrick 7b65b7f85c go.mod: bump tailscale/wireguard-go for loong64
Updates tailscale/tailscale#6233

Change-Id: I5ba1826e79be51c03b19f2b31d73024410be4970
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
Brad Fitzpatrick 5a523fdc7f go.mod: update deps to add support for GOARCH=loong64
Updates tailscale/tailscale#6233

Change-Id: Ibbc8e42607342e4ab4fc0b365ed628d82b56864d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
1 year ago
shayne 9d335aabb2
cmd/tailscale/cli: [ssh] fix typo in help text (#6694)
arugments => arguments

Signed-off-by: shayne <79330+shayne@users.noreply.github.com>
1 year ago
License Updater ab4992e10d licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
1 year ago
Jordan Whited ea5ee6f87c
all: update golang.zx2c4.com/wireguard to github.com/tailscale/wireguard-go (#6692)
This is temporary while we work to upstream performance work in
https://github.com/WireGuard/wireguard-go/pull/64. A replace directive
is less ideal as it breaks dependent code without duplication of the
directive.

Signed-off-by: Jordan Whited <jordan@tailscale.com>
1 year ago
Andrew Dunham b63094431b wgengine/router: fix tests on systems with older Busybox 'ip' binary
Adjust the expected system output by removing the unsupported mask
component including and after the slash in expected output like:
  fwmask 0xabc/0xdef

This package's tests now pass in an Alpine container when the 'go' and
'iptables' packages are installed (and run as privileged so /dev/net/tun
exists).

Fixes #5928

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Id1a3896282bfa36b64afaec7a47205e63ad88542
1 year ago
Maisem Ali eb1adf629f net/tstun: reuse buffered packet from pool
We would call parsedPacketPool.Get() for all packets received in Read/Write.
This was wasteful and not necessary, fetch a single *packet.Parsed for
all packets.

Signed-off-by: Maisem Ali <maisem@tailscale.com>
1 year ago
Walter Poupore 383e203fd2
cmd/tailscale/cli: update lock status help strings (#6675)
Signed-off-by: Walter Poupore <walterp@tailscale.com>

Signed-off-by: Walter Poupore <walterp@tailscale.com>
1 year ago
Jordan Whited 76389d8baf
net/tstun, wgengine/magicsock: enable vectorized I/O on Linux (#6663)
This commit updates the wireguard-go dependency and implements the
necessary changes to the tun.Device and conn.Bind implementations to
support passing vectors of packets in tailscaled. This significantly
improves throughput performance on Linux.

Updates #414

Signed-off-by: Jordan Whited <jordan@tailscale.com>
Signed-off-by: James Tucker <james@tailscale.com>
Co-authored-by: James Tucker <james@tailscale.com>
2 years ago
James Tucker 389238fe4a cmd/tailscale/cli: add workaround for improper named socket quoting in ssh command
This avoids the issue in the common case where the socket path is the
default path, avoiding the immediate need for a Windows shell quote
implementation.

Updates #6639

Signed-off-by: James Tucker <james@tailscale.com>
2 years ago
Mihai Parparita bdc45b9066 wgengine/magicsock: fix panic when rebinding fails
We would replace the existing real implementation of nettype.PacketConn
with a blockForeverConn, but that violates the contract of atomic.Value
(where the type cannot change). Fix by switching to a pointer value
(atomic.Pointer[nettype.PacketConn]).

A longstanding issue, but became more prevalent when we started binding
connections to interfaces on macOS and iOS (#6566), which could lead to
the bind call failing if the interface was no longer available.

Fixes #6641

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
2 years ago
Tom DNetto e27f4f022e cmd/tailscale/cli: add progress to tailscale file cp
Signed-off-by: Tom DNetto <tom@tailscale.com>
2 years ago
Xe Iaso d1a5757639
tsnet: add HTTP client method to tsnet.Server (#6669)
This allows tsnet services to make requests to other services in the
tailnet with the tsnet service identity instead of the identity of the
host machine. This also enables tsnet services to make requests to other
tailnet services without having to have the host machine join the
tailnet.

Signed-off-by: Xe Iaso <xe@tailscale.com>

Signed-off-by: Xe Iaso <xe@tailscale.com>
2 years ago
salman 2d271f3bd1 ipn/ipnlocal: disallow exit nodes from using exit nodes
Nodes which have both -advertise-exit-node and -exit-node in prefs
should continue have them until the next invocation of `tailscale up`.

Updates #3569.

Signed-off-by: salman <salman@tailscale.com>
2 years ago
License Updater 5f68763cb2 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
2 years ago
shayne 98114bf608
cmd/tailscale/cli, ipn/localapi: add funnel status to status command (#6402)
Fixes #6400

open up GETs for localapi serve-config to allow read-only access to
ServeConfig

`tailscale status` will include "Funnel on" status when Funnel is
configured. Prints nothing if Funnel is not running.

Example:

 $ tailscale status
 <nodes redacted>

 # Funnel on:
 #     - https://node-name.corp.ts.net
 #     - https://node-name.corp.ts.net:8443
 #     - tcp://node-name.corp.ts.net:10000

Signed-off-by: Shayne Sweeney <shayne@tailscale.com>
2 years ago
David Anderson 1b65630e83 cmd/containerboot: switch to IPN bus monitoring instead of polling.
We still have to shell out to `tailscale up` because the container image's
API includes "arbitrary flags to tailscale up", unfortunately. But this
should still speed up startup a little, and also enables k8s-bound containers
to update their device information as new netmap updates come in.

Fixes #6657

Signed-off-by: David Anderson <danderson@tailscale.com>
2 years ago
Tom DNetto 55e0512a05 ipn/ipnlocal,cmd/tailscale: minor improvements to lock modify command
* Do not print the status at the end of a successful operation
 * Ensure the key of the current node is actually trusted to make these changes

Signed-off-by: Tom DNetto <tom@tailscale.com>
2 years ago
Aaron Klotz 98f21354c6 cmd/tailscaled: add a special command to tailscaled's Windows service for removing WinTun
WinTun is installed lazily by tailscaled while it is running as LocalSystem.
Based upon what we're seeing in bug reports and support requests, removing
WinTun as a lesser user may fail under certain Windows versions, even when that
user is an Administrator.

By adding a user-defined command code to tailscaled, we can ask the service to
do the removal on our behalf while it is still running as LocalSystem.

* The uninstall code is basically the same as it is in corp;
* The command code will be sent as a service control request and is protected by
  the SERVICE_USER_DEFINED_CONTROL access right, which requires Administrator.

I'll be adding follow-up patches in corp to engage this functionality.

Updates https://github.com/tailscale/tailscale/issues/6433

Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2 years ago
David Anderson 367228ef82 cmd/containerboot: gracefully degrade if missing patch permissions in k8s.
Fixes #6629.

Signed-off-by: David Anderson <danderson@tailscale.com>
2 years ago
Andrew Dunham a887ca7efe ipn/ipnlocal: improve redactErr to handle more cases
This handles the case where the inner *os.PathError is wrapped in
another error type, and additionally will redact errors of type
*os.LinkError. Finally, add tests to verify that redaction works.

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ie83424ff6c85cdb29fb48b641330c495107aab7c
2 years ago
David Anderson e36c27bcd1 cmd/containerboot: check that k8s secret permissions are correct.
Updates #6629.

Signed-off-by: David Anderson <danderson@tailscale.com>
2 years ago
David Anderson e79a1eb24a cmd/containerboot: refactor tests to have more explicit phases.
In preparation for making startup more complex with IPN bus watches.

Signed-off-by: David Anderson <danderson@tailscale.com>
2 years ago
David Anderson e04aaa7575 cmd/containerboot: split tailscaled bringup and auth phases.
In preparation for reworking auth to use IPN bus watch.

Signed-off-by: David Anderson <danderson@tailscale.com>
2 years ago
David Anderson a469ec8ff6 cmd/containerboot: fix some lint.
Signed-off-by: David Anderson <danderson@tailscale.com>
2 years ago
License Updater c084c7d7ed licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
2 years ago
Anton Tolchanov 5ff946a9e6 cmd/containerboot: fix TS_STATE_DIR environment variable
It's supposed to set `--statedir` rather than `--state` file.

Fixes #6634.

Signed-off-by: Anton Tolchanov <anton@tailscale.com>
2 years ago
License Updater 7048024e04 licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
2 years ago
Brad Fitzpatrick 1598cd0361 net/tsaddr: remove ContainsFunc helpers (they're now in x/exp/slices)
x/exp/slices now has ContainsFunc (golang/go#53983) so we can delete
our versions.

Change-Id: I5157a403bfc1b30e243bf31c8b611da25e995078
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2 years ago
License Updater 4b34c88426 licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
2 years ago
Mihai Parparita 79f3a5d753 net/netns, net/interfaces: explicitly bind sockets to the default interface on all Darwin variants
We were previously only doing this for tailscaled-on-Darwin, but it also
appears to help on iOS. Otherwise, when we rebind magicsock UDP
connections after a cellular -> WiFi interface change they still keep
using cellular one.

To do this correctly when using exit nodes, we need to exclude the
Tailscale interface when getting the default route, otherwise packets
cannot leave the tunnel. There are native macOS/iOS APIs that we can
use to do this, so we allow those clients to override the implementation
of DefaultRouteInterfaceIndex.

Updates #6565, may also help with #5156

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
2 years ago
Mihai Parparita cb525a1aad cmd/tailscaled: fix typo in netstack variable name
Signed-off-by: Mihai Parparita <mihai@tailscale.com>
2 years ago
Julia Stein 3f16dec1bb api.md: change "admin panel" to "admin console"
Signed-off-by: Julia Stein <julia@tailscale.com>
2 years ago
Tom DNetto 9c773af04c ipn/ipnlocal: fix use of stale profile while processing netmap
Signed-off-by: Tom DNetto <tom@tailscale.com>
2 years ago
Denton Gentry c933b8882c VERSION.txt: this is v1.35.0
Signed-off-by: Denton Gentry <dgentry@tailscale.com>
2 years ago

@ -12,7 +12,6 @@ body:
attributes:
label: What is the issue?
description: What happened? What did you expect to happen?
placeholder: oh no
validations:
required: true
- type: textarea
@ -61,6 +60,13 @@ body:
placeholder: e.g., 1.14.4
validations:
required: false
- type: textarea
id: other-software
attributes:
label: Other software
description: What [other software](https://github.com/tailscale/tailscale/wiki/OtherSoftwareInterop) (networking, security, etc) are you running?
validations:
required: false
- type: input
id: bug-report
attributes:

@ -0,0 +1,28 @@
name: checklocks
on:
push:
branches:
- main
pull_request:
paths:
- '**/*.go'
- '.github/workflows/checklocks.yml'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
checklocks:
runs-on: [ ubuntu-latest ]
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Build checklocks
run: ./tool/go build -o /tmp/checklocks gvisor.dev/gvisor/tools/checklocks/cmd/checklocks
- name: Run checklocks vet
# TODO: remove || true once we have applied checklocks annotations everywhere.
run: ./tool/go vet -vettool=/tmp/checklocks ./... || true

@ -1,31 +0,0 @@
name: CIFuzz
on: [pull_request]
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
Fuzzing:
runs-on: ubuntu-latest
steps:
- name: Build Fuzzers
id: build
uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
with:
oss-fuzz-project-name: 'tailscale'
dry-run: false
language: go
- name: Run Fuzzers
uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
with:
oss-fuzz-project-name: 'tailscale'
fuzz-seconds: 300
dry-run: false
language: go
- name: Upload Crash
uses: actions/upload-artifact@v3
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts
path: ./out/artifacts

@ -17,6 +17,8 @@ on:
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
merge_group:
branches: [ main ]
schedule:
- cron: '31 14 * * 5'
@ -43,11 +45,17 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v4
# Install a more recent Go that understands modern go.mod content.
- name: Install Go
uses: actions/setup-go@v4
with:
go-version-file: go.mod
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@ -58,7 +66,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@ -72,4 +80,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
uses: github/codeql-action/analyze@v2

@ -1,55 +0,0 @@
name: Android-Cross
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: Android smoke build
# Super minimal Android build that doesn't even use CGO and doesn't build everything that's needed
# and is only arm64. But it's a smoke build: it's not meant to catch everything. But it'll catch
# some Android breakages early.
# TODO(bradfitz): better; see https://github.com/tailscale/tailscale/issues/4482
env:
GOOS: android
GOARCH: arm64
run: go install ./net/netns ./ipn/ipnlocal ./wgengine/magicsock/ ./wgengine/ ./wgengine/router/ ./wgengine/netstack ./util/dnsname/ ./ipn/ ./net/interfaces ./wgengine/router/ ./tailcfg/ ./types/logger/ ./net/dns ./hostinfo ./version
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,63 +0,0 @@
name: Darwin-Cross
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: macOS build cmd
env:
GOOS: darwin
GOARCH: amd64
run: go build ./cmd/...
- name: macOS build tests
env:
GOOS: darwin
GOARCH: amd64
run: for d in $(go list -f '{{if .TestGoFiles}}{{.Dir}}{{end}}' ./... ); do (echo $d; cd $d && go test -c ); done
- name: iOS build most
env:
GOOS: ios
GOARCH: arm64
run: go install ./ipn/... ./wgengine/ ./types/... ./control/controlclient
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,57 +0,0 @@
name: FreeBSD-Cross
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: FreeBSD build cmd
env:
GOOS: freebsd
GOARCH: amd64
run: go build ./cmd/...
- name: FreeBSD build tests
env:
GOOS: freebsd
GOARCH: amd64
run: for d in $(go list -f '{{if .TestGoFiles}}{{.Dir}}{{end}}' ./... ); do (echo $d; cd $d && go test -c ); done
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,57 +0,0 @@
name: OpenBSD-Cross
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: OpenBSD build cmd
env:
GOOS: openbsd
GOARCH: amd64
run: go build ./cmd/...
- name: OpenBSD build tests
env:
GOOS: openbsd
GOARCH: amd64
run: for d in $(go list -f '{{if .TestGoFiles}}{{.Dir}}{{end}}' ./... ); do (echo $d; cd $d && go test -c ); done
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,58 +0,0 @@
name: Wasm-Cross
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: Wasm client build
env:
GOOS: js
GOARCH: wasm
run: go build ./cmd/tsconnect/wasm ./cmd/tailscale/cli
- name: tsconnect static build
# Use our custom Go toolchain, we set build tags (to control binary size)
# that depend on it.
run: |
./tool/go run ./cmd/tsconnect --fast-compression build
./tool/go run ./cmd/tsconnect --fast-compression build-pkg
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,57 +0,0 @@
name: Windows-Cross
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: Windows build cmd
env:
GOOS: windows
GOARCH: amd64
run: go build ./cmd/...
- name: Windows build tests
env:
GOOS: windows
GOARCH: amd64
run: for d in $(go list -f '{{if .TestGoFiles}}{{.Dir}}{{end}}' ./... ); do (echo $d; cd $d && go test -c ); done
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,33 +0,0 @@
name: depaware
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
- name: depaware
run: go run github.com/tailscale/depaware --check
tailscale.com/cmd/tailscaled
tailscale.com/cmd/tailscale
tailscale.com/cmd/derper

@ -0,0 +1,15 @@
name: "Dockerfile build"
on:
push:
branches:
- main
pull_request:
branches:
- "*"
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: "Build Docker image"
run: docker build .

@ -0,0 +1,27 @@
name: update-flakehub
on:
push:
tags:
- "v[0-9]+.*[02468].[0-9]+"
workflow_dispatch:
inputs:
tag:
description: "The existing tag to publish to FlakeHub"
type: "string"
required: true
jobs:
flakehub-publish:
runs-on: "ubuntu-latest"
permissions:
id-token: "write"
contents: "read"
steps:
- uses: "actions/checkout@v4"
with:
ref: "${{ (inputs.tag != null) && format('refs/tags/{0}', inputs.tag) || '' }}"
- uses: "DeterminateSystems/nix-installer-action@main"
- uses: "DeterminateSystems/flakehub-push@main"
with:
visibility: "public"
tag: "${{ inputs.tag }}"

@ -1,64 +0,0 @@
name: go-licenses
on:
# run action when a change lands in the main branch which updates go.mod or
# our license template file. Also allow manual triggering.
push:
branches:
- main
paths:
- go.mod
- .github/licenses.tmpl
- .github/workflows/go-licenses.yml
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
tailscale:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
- name: Install go-licenses
run: |
go install github.com/google/go-licenses@v1.2.2-0.20220825154955-5eedde1c6584
- name: Run go-licenses
env:
# include all build tags to include platform-specific dependencies
GOFLAGS: "-tags=android,cgo,darwin,freebsd,ios,js,linux,openbsd,wasm,windows"
run: |
[ -d licenses ] || mkdir licenses
go-licenses report tailscale.com/cmd/tailscale tailscale.com/cmd/tailscaled > licenses/tailscale.md --template .github/licenses.tmpl
- name: Get access token
uses: tibdex/github-app-token@f717b5ecd4534d3c4df4ce9b5c1c2214f0f7cd06 # v1.6.0
id: generate-token
with:
app_id: ${{ secrets.LICENSING_APP_ID }}
installation_id: ${{ secrets.LICENSING_APP_INSTALLATION_ID }}
private_key: ${{ secrets.LICENSING_APP_PRIVATE_KEY }}
- name: Send pull request
uses: peter-evans/create-pull-request@ad43dccb4d726ca8514126628bec209b8354b6dd #v4.1.4
with:
token: ${{ steps.generate-token.outputs.token }}
author: License Updater <noreply@tailscale.com>
committer: License Updater <noreply@tailscale.com>
branch: licenses/cli
commit-message: "licenses: update tailscale{,d} licenses"
title: "licenses: update tailscale{,d} licenses"
body: Triggered by ${{ github.repository }}@${{ github.sha }}
signoff: true
delete-branch: true
team-reviewers: opensource-license-reviewers

@ -1,42 +0,0 @@
name: go generate
on:
push:
branches:
- main
- "release-branch/*"
pull_request:
branches:
- "*"
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
- name: check 'go generate' is clean
run: |
if [[ "${{github.ref}}" == release-branch/* ]]
then
pkgs=$(go list ./... | grep -v dnsfallback)
else
pkgs=$(go list ./... | grep -v dnsfallback)
fi
go generate $pkgs
echo
echo
git diff --name-only --exit-code || (echo "The files above need updating. Please run 'go generate'."; exit 1)

@ -1,35 +0,0 @@
name: go mod tidy
on:
push:
branches:
- main
pull_request:
branches:
- "*"
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
- name: check 'go mod tidy' is clean
run: |
go mod tidy
echo
echo
git diff --name-only --exit-code || (echo "Please run 'go mod tidy'."; exit 1)

@ -0,0 +1,40 @@
name: golangci-lint
on:
# For now, only lint pull requests, not the main branches.
pull_request:
# TODO(andrew): enable for main branch after an initial waiting period.
#push:
# branches:
# - main
workflow_dispatch:
permissions:
contents: read
pull-requests: read
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
go-version-file: go.mod
cache: false
- name: golangci-lint
# Note: this is the 'v3' tag as of 2023-08-14
uses: golangci/golangci-lint-action@639cd343e1d3b897ff35927a75193d57cfcba299
with:
version: v1.56
# Show only new issues if it's a pull request.
only-new-issues: true

@ -0,0 +1,51 @@
name: govulncheck
on:
schedule:
- cron: "0 12 * * *" # 8am EST / 10am PST / 12pm UTC
workflow_dispatch: # allow manual trigger for testing
pull_request:
paths:
- ".github/workflows/govulncheck.yml"
jobs:
source-scan:
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
- name: Install govulncheck
run: ./tool/go install golang.org/x/vuln/cmd/govulncheck@latest
- name: Scan source code for known vulnerabilities
run: PATH=$PWD/tool/:$PATH "$(./tool/go env GOPATH)/bin/govulncheck" -test ./...
- name: Post to slack
if: failure() && github.event_name == 'schedule'
uses: slackapi/slack-github-action@v1.24.0
env:
SLACK_BOT_TOKEN: ${{ secrets.GOVULNCHECK_BOT_TOKEN }}
with:
channel-id: 'C05PXRM304B'
payload: |
{
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Govulncheck failed in ${{ github.repository }}"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "View results"
},
"url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}

@ -0,0 +1,104 @@
name: test installer.sh
on:
push:
branches:
- "main"
paths:
- scripts/installer.sh
pull_request:
branches:
- "*"
paths:
- scripts/installer.sh
jobs:
test:
strategy:
# Don't abort the entire matrix if one element fails.
fail-fast: false
# Don't start all of these at once, which could saturate Github workers.
max-parallel: 4
matrix:
image:
# This is a list of Docker images against which we test our installer.
# If you find that some of these no longer exist, please feel free
# to remove them from the list.
# When adding new images, please only use official ones.
- "debian:oldstable-slim"
- "debian:stable-slim"
- "debian:testing-slim"
- "debian:sid-slim"
- "ubuntu:18.04"
- "ubuntu:20.04"
- "ubuntu:22.04"
- "ubuntu:23.04"
- "elementary/docker:stable"
- "elementary/docker:unstable"
- "parrotsec/core:lts-amd64"
- "parrotsec/core:latest"
- "kalilinux/kali-rolling"
- "kalilinux/kali-dev"
- "oraclelinux:9"
- "oraclelinux:8"
- "fedora:latest"
- "rockylinux:8.7"
- "rockylinux:9"
- "amazonlinux:latest"
- "opensuse/leap:latest"
- "opensuse/tumbleweed:latest"
- "archlinux:latest"
- "alpine:3.14"
- "alpine:latest"
- "alpine:edge"
deps:
# Run all images installing curl as a dependency.
- curl
include:
# Check a few images with wget rather than curl.
- { image: "debian:oldstable-slim", deps: "wget" }
- { image: "debian:sid-slim", deps: "wget" }
- { image: "ubuntu:23.04", deps: "wget" }
# Ubuntu 16.04 also needs apt-transport-https installed.
- { image: "ubuntu:16.04", deps: "curl apt-transport-https" }
- { image: "ubuntu:16.04", deps: "wget apt-transport-https" }
runs-on: ubuntu-latest
container:
image: ${{ matrix.image }}
options: --user root
steps:
- name: install dependencies (yum)
# tar and gzip are needed by the actions/checkout below.
run: yum install -y --allowerasing tar gzip ${{ matrix.deps }}
if: |
contains(matrix.image, 'centos')
|| contains(matrix.image, 'oraclelinux')
|| contains(matrix.image, 'fedora')
|| contains(matrix.image, 'amazonlinux')
- name: install dependencies (zypper)
# tar and gzip are needed by the actions/checkout below.
run: zypper --non-interactive install tar gzip ${{ matrix.deps }}
if: contains(matrix.image, 'opensuse')
- name: install dependencies (apt-get)
run: |
apt-get update
apt-get install -y ${{ matrix.deps }}
if: |
contains(matrix.image, 'debian')
|| contains(matrix.image, 'ubuntu')
|| contains(matrix.image, 'elementary')
|| contains(matrix.image, 'parrotsec')
|| contains(matrix.image, 'kalilinux')
- name: checkout
# We cannot use v4, as it requires a newer glibc version than some of the
# tested images provide. See
# https://github.com/actions/checkout/issues/1487
uses: actions/checkout@v3
- name: run installer
run: scripts/installer.sh
# Package installation can fail in docker because systemd is not running
# as PID 1, so ignore errors at this step. The real check is the
# `tailscale --version` command below.
continue-on-error: true
- name: check tailscale version
run: tailscale --version

@ -0,0 +1,31 @@
name: "Kubernetes manifests"
on:
pull_request:
paths:
- 'cmd/k8s-operator/**'
- 'k8s-operator/**'
- '.github/workflows/kubemanifests.yaml'
# Cancel workflow run if there is a newer push to the same PR for which it is
# running
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
testchart:
runs-on: [ ubuntu-latest ]
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Build and lint Helm chart
run: |
eval `./tool/go run ./cmd/mkversion`
./tool/helm package --app-version="${VERSION_SHORT}" --version=${VERSION_SHORT} './cmd/k8s-operator/deploy/chart'
./tool/helm lint "tailscale-operator-${VERSION_SHORT}.tgz"
- name: Verify that static manifests are up to date
run: |
make kube-generate-all
echo
echo
git diff --name-only --exit-code || (echo "Generated files for Tailscale Kubernetes operator are out of date. Please run 'make kube-generate-all' and commit the diff."; exit 1)

@ -1,45 +0,0 @@
name: license
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
- name: Run license checker
run: ./scripts/check_license_headers.sh .
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,67 +0,0 @@
name: Linux race
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: Basic build
run: go build ./cmd/...
- name: Run tests and benchmarks with -race flag on linux
run: go test -race -bench=. -benchtime=1x ./...
- name: Check that no tracked files in the repo have been modified
run: git diff --no-ext-diff --name-only --exit-code || (echo "Build/test modified the files above."; exit 1)
- name: Check that no files have been added to the repo
run: |
# Note: The "error: pathspec..." you see below is normal!
# In the success case in which there are no new untracked files,
# git ls-files complains about the pathspec not matching anything.
# That's OK. It's not worth the effort to suppress. Please ignore it.
if git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*'
then
echo "Build/test created untracked files in the repo (file names above)."
exit 1
fi
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,77 +0,0 @@
name: Linux
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-22.04
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: Basic build
run: go build ./cmd/...
- name: Build variants
run: |
go install --tags=ts_include_cli ./cmd/tailscaled
go install --tags=ts_omit_aws ./cmd/tailscaled
- name: Get QEMU
run: |
sudo apt-get -y update
sudo apt-get -y install qemu-user
- name: Run tests on linux
run: go test -bench=. -benchtime=1x ./...
- name: Check that no tracked files in the repo have been modified
run: git diff --no-ext-diff --name-only --exit-code || (echo "Build/test modified the files above."; exit 1)
- name: Check that no files have been added to the repo
run: |
# Note: The "error: pathspec..." you see below is normal!
# In the success case in which there are no new untracked files,
# git ls-files complains about the pathspec not matching anything.
# That's OK. It's not worth the effort to suppress. Please ignore it.
if git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*'
then
echo "Build/test created untracked files in the repo (file names above)."
exit 1
fi
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,67 +0,0 @@
name: Linux 32-bit
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
id: go
- name: Basic build
run: GOARCH=386 go build ./cmd/...
- name: Run tests on linux
run: GOARCH=386 go test -bench=. -benchtime=1x ./...
- name: Check that no tracked files in the repo have been modified
run: git diff --no-ext-diff --name-only --exit-code || (echo "Build/test modified the files above."; exit 1)
- name: Check that no files have been added to the repo
run: |
# Note: The "error: pathspec..." you see below is normal!
# In the success case in which there are no new untracked files,
# git ls-files complains about the pathspec not matching anything.
# That's OK. It's not worth the effort to suppress. Please ignore it.
if git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*'
then
echo "Build/test created untracked files in the repo (file names above)."
exit 1
fi
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -1,113 +0,0 @@
name: static-analysis
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
gofmt:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
- name: Run gofmt (goimports)
run: go run golang.org/x/tools/cmd/goimports -d --format-only .
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'
vet:
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: Check out code
uses: actions/checkout@v3
- name: Run go vet
run: go vet ./...
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'
staticcheck:
runs-on: ubuntu-latest
strategy:
matrix:
goos: [linux, windows, darwin]
goarch: [amd64]
include:
- goos: windows
goarch: 386
steps:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: Check out code
uses: actions/checkout@v3
- name: Install staticcheck
run: "GOBIN=~/.local/bin go install honnef.co/go/tools/cmd/staticcheck"
- name: Print staticcheck version
run: "staticcheck -version"
- name: "Run staticcheck (${{ matrix.goos }}/${{ matrix.goarch }})"
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
run: "staticcheck -- $(go list ./... | grep -v tempfork)"
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -0,0 +1,601 @@
# This is our main "CI tests" workflow. It runs everything that should run on
# both PRs and merged commits, and for the latter reports failures to slack.
name: CI
env:
# Our fuzz job, powered by OSS-Fuzz, fails periodically because we upgrade to
# new Go versions very eagerly. OSS-Fuzz is a little more conservative, and
# ends up being unable to compile our code.
#
# When this happens, we want to disable the fuzz target until OSS-Fuzz catches
# up. However, we also don't want to forget to turn it back on when OSS-Fuzz
# can once again build our code.
#
# This variable toggles the fuzz job between two modes:
# - false: we expect fuzzing to be happy, and should report failure if it's not.
# - true: we expect fuzzing is broken, and should report failure if it start working.
TS_FUZZ_CURRENTLY_BROKEN: false
on:
push:
branches:
- "main"
- "release-branch/*"
pull_request:
# all PRs on all branches
merge_group:
branches:
- "main"
concurrency:
# For PRs, later CI runs preempt previous ones. e.g. a force push on a PR
# cancels running CI jobs and starts all new ones.
#
# For non-PR pushes, concurrency.group needs to be unique for every distinct
# CI run we want to have happen. Use run_id, which in practice means all
# non-PR CI runs will be allowed to run without preempting each other.
group: ${{ github.workflow }}-$${{ github.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
race-root-integration:
runs-on: ubuntu-22.04
strategy:
fail-fast: false # don't abort the entire matrix if one element fails
matrix:
include:
- shard: '1/4'
- shard: '2/4'
- shard: '3/4'
- shard: '4/4'
steps:
- name: checkout
uses: actions/checkout@v4
- name: build test wrapper
run: ./tool/go build -o /tmp/testwrapper ./cmd/testwrapper
- name: integration tests as root
run: PATH=$PWD/tool:$PATH /tmp/testwrapper -exec "sudo -E" -race ./tstest/integration/
env:
TS_TEST_SHARD: ${{ matrix.shard }}
test:
strategy:
fail-fast: false # don't abort the entire matrix if one element fails
matrix:
include:
- goarch: amd64
coverflags: "-coverprofile=/tmp/coverage.out"
- goarch: amd64
buildflags: "-race"
shard: '1/3'
- goarch: amd64
buildflags: "-race"
shard: '2/3'
- goarch: amd64
buildflags: "-race"
shard: '3/3'
- goarch: "386" # thanks yaml
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: Restore Cache
uses: actions/cache@v3
with:
# Note: unlike the other setups, this is only grabbing the mod download
# cache, rather than the whole mod directory, as the download cache
# contains zips that can be unpacked in parallel faster than they can be
# fetched and extracted by tar
path: |
~/.cache/go-build
~/go/pkg/mod/cache
~\AppData\Local\go-build
# The -2- here should be incremented when the scheme of data to be
# cached changes (e.g. path above changes).
key: ${{ github.job }}-${{ runner.os }}-${{ matrix.goarch }}-${{ matrix.buildflags }}-go-2-${{ hashFiles('**/go.sum') }}-${{ github.run_id }}
restore-keys: |
${{ github.job }}-${{ runner.os }}-${{ matrix.goarch }}-${{ matrix.buildflags }}-go-2-${{ hashFiles('**/go.sum') }}
${{ github.job }}-${{ runner.os }}-${{ matrix.goarch }}-${{ matrix.buildflags }}-go-2-
- name: build all
if: matrix.buildflags == '' # skip on race builder
run: ./tool/go build ${{matrix.buildflags}} ./...
env:
GOARCH: ${{ matrix.goarch }}
- name: build variant CLIs
if: matrix.buildflags == '' # skip on race builder
run: |
export TS_USE_TOOLCHAIN=1
./build_dist.sh --extra-small ./cmd/tailscaled
./build_dist.sh --box ./cmd/tailscaled
./build_dist.sh --extra-small --box ./cmd/tailscaled
rm -f tailscaled
env:
GOARCH: ${{ matrix.goarch }}
- name: get qemu # for tstest/archtest
if: matrix.goarch == 'amd64' && matrix.buildflags == ''
run: |
sudo apt-get -y update
sudo apt-get -y install qemu-user
- name: build test wrapper
run: ./tool/go build -o /tmp/testwrapper ./cmd/testwrapper
- name: test all
run: NOBASHDEBUG=true PATH=$PWD/tool:$PATH /tmp/testwrapper ${{matrix.coverflags}} ./... ${{matrix.buildflags}}
env:
GOARCH: ${{ matrix.goarch }}
TS_TEST_SHARD: ${{ matrix.shard }}
- name: Publish to coveralls.io
if: matrix.coverflags != '' # only publish results if we've tracked coverage
uses: shogo82148/actions-goveralls@v1
with:
path-to-profile: /tmp/coverage.out
- name: bench all
run: ./tool/go test ${{matrix.buildflags}} -bench=. -benchtime=1x -run=^$ $(for x in $(git grep -l "^func Benchmark" | xargs dirname | sort | uniq); do echo "./$x"; done)
env:
GOARCH: ${{ matrix.goarch }}
- name: check that no tracked files changed
run: git diff --no-ext-diff --name-only --exit-code || (echo "Build/test modified the files above."; exit 1)
- name: check that no new files were added
run: |
# Note: The "error: pathspec..." you see below is normal!
# In the success case in which there are no new untracked files,
# git ls-files complains about the pathspec not matching anything.
# That's OK. It's not worth the effort to suppress. Please ignore it.
if git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*'
then
echo "Build/test created untracked files in the repo (file names above)."
exit 1
fi
windows:
runs-on: windows-2022
steps:
- name: checkout
uses: actions/checkout@v4
- name: Install Go
uses: actions/setup-go@v4
with:
go-version-file: go.mod
cache: false
- name: Restore Cache
uses: actions/cache@v3
with:
# Note: unlike the other setups, this is only grabbing the mod download
# cache, rather than the whole mod directory, as the download cache
# contains zips that can be unpacked in parallel faster than they can be
# fetched and extracted by tar
path: |
~/.cache/go-build
~/go/pkg/mod/cache
~\AppData\Local\go-build
# The -2- here should be incremented when the scheme of data to be
# cached changes (e.g. path above changes).
key: ${{ github.job }}-${{ runner.os }}-go-2-${{ hashFiles('**/go.sum') }}-${{ github.run_id }}
restore-keys: |
${{ github.job }}-${{ runner.os }}-go-2-${{ hashFiles('**/go.sum') }}
${{ github.job }}-${{ runner.os }}-go-2-
- name: test
run: go run ./cmd/testwrapper ./...
- name: bench all
# Don't use -bench=. -benchtime=1x.
# Somewhere in the layers (powershell?)
# the equals signs cause great confusion.
run: go test ./... -bench . -benchtime 1x -run "^$"
privileged:
runs-on: ubuntu-22.04
container:
image: golang:latest
options: --privileged
steps:
- name: checkout
uses: actions/checkout@v4
- name: chown
run: chown -R $(id -u):$(id -g) $PWD
- name: privileged tests
run: ./tool/go test ./util/linuxfw
vm:
runs-on: ["self-hosted", "linux", "vm"]
# VM tests run with some privileges, don't let them run on 3p PRs.
if: github.repository == 'tailscale/tailscale'
steps:
- name: checkout
uses: actions/checkout@v4
- name: Run VM tests
run: ./tool/go test ./tstest/integration/vms -v -no-s3 -run-vm-tests -run=TestRunUbuntu2004
env:
HOME: "/var/lib/ghrunner/home"
TMPDIR: "/tmp"
XDG_CACHE_HOME: "/var/lib/ghrunner/cache"
race-build:
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: build all
run: ./tool/go install -race ./cmd/...
- name: build tests
run: ./tool/go test -race -exec=true ./...
cross: # cross-compile checks, build only.
strategy:
fail-fast: false # don't abort the entire matrix if one element fails
matrix:
include:
# Note: linux/amd64 is not in this matrix, because that goos/goarch is
# tested more exhaustively in the 'test' job above.
- goos: linux
goarch: arm64
- goos: linux
goarch: "386" # thanks yaml
- goos: linux
goarch: loong64
- goos: linux
goarch: arm
goarm: "5"
- goos: linux
goarch: arm
goarm: "7"
# macOS
- goos: darwin
goarch: amd64
- goos: darwin
goarch: arm64
# Windows
- goos: windows
goarch: amd64
- goos: windows
goarch: arm64
# BSDs
- goos: freebsd
goarch: amd64
- goos: openbsd
goarch: amd64
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: Restore Cache
uses: actions/cache@v3
with:
# Note: unlike the other setups, this is only grabbing the mod download
# cache, rather than the whole mod directory, as the download cache
# contains zips that can be unpacked in parallel faster than they can be
# fetched and extracted by tar
path: |
~/.cache/go-build
~/go/pkg/mod/cache
~\AppData\Local\go-build
# The -2- here should be incremented when the scheme of data to be
# cached changes (e.g. path above changes).
key: ${{ github.job }}-${{ runner.os }}-${{ matrix.goos }}-${{ matrix.goarch }}-go-2-${{ hashFiles('**/go.sum') }}-${{ github.run_id }}
restore-keys: |
${{ github.job }}-${{ runner.os }}-${{ matrix.goos }}-${{ matrix.goarch }}-go-2-${{ hashFiles('**/go.sum') }}
${{ github.job }}-${{ runner.os }}-${{ matrix.goos }}-${{ matrix.goarch }}-go-2-
- name: build all
run: ./tool/go build ./cmd/...
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
GOARM: ${{ matrix.goarm }}
CGO_ENABLED: "0"
- name: build tests
run: ./tool/go test -exec=true ./...
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
CGO_ENABLED: "0"
ios: # similar to cross above, but iOS can't build most of the repo. So, just
#make it build a few smoke packages.
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: build some
run: ./tool/go build ./ipn/... ./wgengine/ ./types/... ./control/controlclient
env:
GOOS: ios
GOARCH: arm64
crossmin: # cross-compile for platforms where we only check cmd/tailscale{,d}
strategy:
fail-fast: false # don't abort the entire matrix if one element fails
matrix:
include:
# Plan9
- goos: plan9
goarch: amd64
# AIX
- goos: aix
goarch: ppc64
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: Restore Cache
uses: actions/cache@v3
with:
# Note: unlike the other setups, this is only grabbing the mod download
# cache, rather than the whole mod directory, as the download cache
# contains zips that can be unpacked in parallel faster than they can be
# fetched and extracted by tar
path: |
~/.cache/go-build
~/go/pkg/mod/cache
~\AppData\Local\go-build
# The -2- here should be incremented when the scheme of data to be
# cached changes (e.g. path above changes).
key: ${{ github.job }}-${{ runner.os }}-${{ matrix.goos }}-${{ matrix.goarch }}-go-2-${{ hashFiles('**/go.sum') }}-${{ github.run_id }}
restore-keys: |
${{ github.job }}-${{ runner.os }}-${{ matrix.goos }}-${{ matrix.goarch }}-go-2-${{ hashFiles('**/go.sum') }}
${{ github.job }}-${{ runner.os }}-${{ matrix.goos }}-${{ matrix.goarch }}-go-2-
- name: build core
run: ./tool/go build ./cmd/tailscale ./cmd/tailscaled
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
GOARM: ${{ matrix.goarm }}
CGO_ENABLED: "0"
android:
# similar to cross above, but android fails to build a few pieces of the
# repo. We should fix those pieces, they're small, but as a stepping stone,
# only test the subset of android that our past smoke test checked.
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
# Super minimal Android build that doesn't even use CGO and doesn't build everything that's needed
# and is only arm64. But it's a smoke build: it's not meant to catch everything. But it'll catch
# some Android breakages early.
# TODO(bradfitz): better; see https://github.com/tailscale/tailscale/issues/4482
- name: build some
run: ./tool/go install ./net/netns ./ipn/ipnlocal ./wgengine/magicsock/ ./wgengine/ ./wgengine/router/ ./wgengine/netstack ./util/dnsname/ ./ipn/ ./net/netmon ./wgengine/router/ ./tailcfg/ ./types/logger/ ./net/dns ./hostinfo ./version
env:
GOOS: android
GOARCH: arm64
wasm: # builds tsconnect, which is the only wasm build we support
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: Restore Cache
uses: actions/cache@v3
with:
# Note: unlike the other setups, this is only grabbing the mod download
# cache, rather than the whole mod directory, as the download cache
# contains zips that can be unpacked in parallel faster than they can be
# fetched and extracted by tar
path: |
~/.cache/go-build
~/go/pkg/mod/cache
~\AppData\Local\go-build
# The -2- here should be incremented when the scheme of data to be
# cached changes (e.g. path above changes).
key: ${{ github.job }}-${{ runner.os }}-go-2-${{ hashFiles('**/go.sum') }}-${{ github.run_id }}
restore-keys: |
${{ github.job }}-${{ runner.os }}-go-2-${{ hashFiles('**/go.sum') }}
${{ github.job }}-${{ runner.os }}-go-2-
- name: build tsconnect client
run: ./tool/go build ./cmd/tsconnect/wasm ./cmd/tailscale/cli
env:
GOOS: js
GOARCH: wasm
- name: build tsconnect server
# Note, no GOOS/GOARCH in env on this build step, we're running a build
# tool that handles the build itself.
run: |
./tool/go run ./cmd/tsconnect --fast-compression build
./tool/go run ./cmd/tsconnect --fast-compression build-pkg
tailscale_go: # Subset of tests that depend on our custom Go toolchain.
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: test tailscale_go
run: ./tool/go test -tags=tailscale_go,ts_enable_sockstats ./net/sockstats/...
fuzz:
# This target periodically breaks (see TS_FUZZ_CURRENTLY_BROKEN at the top
# of the file), so it's more complex than usual: the 'build fuzzers' step
# might fail, and depending on the value of 'TS_FUZZ_CURRENTLY_BROKEN', that
# might or might not be fine. The steps after the build figure out whether
# the success/failure is expected, and appropriately pass/fail the job
# overall accordingly.
#
# Practically, this means that all steps after 'build fuzzers' must have an
# explicit 'if' condition, because the default condition for steps is
# 'success()', meaning "only run this if no previous steps failed".
if: github.event_name == 'pull_request'
runs-on: ubuntu-22.04
steps:
- name: build fuzzers
id: build
uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
# continue-on-error makes steps.build.conclusion be 'success' even if
# steps.build.outcome is 'failure'. This means this step does not
# contribute to the job's overall pass/fail evaluation.
continue-on-error: true
with:
oss-fuzz-project-name: 'tailscale'
dry-run: false
language: go
- name: report unexpectedly broken fuzz build
if: steps.build.outcome == 'failure' && env.TS_FUZZ_CURRENTLY_BROKEN != 'true'
run: |
echo "fuzzer build failed, see above for why"
echo "if the failure is due to OSS-Fuzz not being on the latest Go yet,"
echo "set TS_FUZZ_CURRENTLY_BROKEN=true in .github/workflows/test.yml"
echo "to temporarily disable fuzzing until OSS-Fuzz works again."
exit 1
- name: report unexpectedly working fuzz build
if: steps.build.outcome == 'success' && env.TS_FUZZ_CURRENTLY_BROKEN == 'true'
run: |
echo "fuzzer build succeeded, but we expect it to be broken"
echo "please set TS_FUZZ_CURRENTLY_BROKEN=false in .github/workflows/test.yml"
echo "to reenable fuzz testing"
exit 1
- name: run fuzzers
id: run
# Run the fuzzers whenever they're able to build, even if we're going to
# report a failure because TS_FUZZ_CURRENTLY_BROKEN is set to the wrong
# value.
if: steps.build.outcome == 'success'
uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
with:
oss-fuzz-project-name: 'tailscale'
fuzz-seconds: 300
dry-run: false
language: go
- name: upload crash
uses: actions/upload-artifact@v3
if: steps.run.outcome != 'success' && steps.build.outcome == 'success'
with:
name: artifacts
path: ./out/artifacts
depaware:
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: check depaware
run: |
export PATH=$(./tool/go env GOROOT)/bin:$PATH
find . -name 'depaware.txt' | xargs -n1 dirname | xargs ./tool/go run github.com/tailscale/depaware --check
go_generate:
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: check that 'go generate' is clean
run: |
pkgs=$(./tool/go list ./... | grep -Ev 'dnsfallback|k8s-operator')
./tool/go generate $pkgs
echo
echo
git diff --name-only --exit-code || (echo "The files above need updating. Please run 'go generate'."; exit 1)
go_mod_tidy:
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: check that 'go mod tidy' is clean
run: |
./tool/go mod tidy
echo
echo
git diff --name-only --exit-code || (echo "Please run 'go mod tidy'."; exit 1)
licenses:
runs-on: ubuntu-22.04
steps:
- name: checkout
uses: actions/checkout@v4
- name: check licenses
run: ./scripts/check_license_headers.sh .
staticcheck:
runs-on: ubuntu-22.04
strategy:
fail-fast: false # don't abort the entire matrix if one element fails
matrix:
goos: ["linux", "windows", "darwin"]
goarch: ["amd64"]
include:
- goos: "windows"
goarch: "386"
steps:
- name: checkout
uses: actions/checkout@v4
- name: install staticcheck
run: GOBIN=~/.local/bin ./tool/go install honnef.co/go/tools/cmd/staticcheck
- name: run staticcheck
run: |
export GOROOT=$(./tool/go env GOROOT)
export PATH=$GOROOT/bin:$PATH
staticcheck -- $(./tool/go list ./... | grep -v tempfork)
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
notify_slack:
if: always()
# Any of these jobs failing causes a slack notification.
needs:
- android
- test
- windows
- vm
- cross
- ios
- wasm
- tailscale_go
- fuzz
- depaware
- go_generate
- go_mod_tidy
- licenses
- staticcheck
runs-on: ubuntu-22.04
steps:
- name: notify
# Only notify slack for merged commits, not PR failures.
#
# It may be tempting to move this condition into the job's 'if' block, but
# don't: Github only collapses the test list into "everything is OK" if
# all jobs succeeded. A skipped job results in the list staying expanded.
# By having the job always run, but skipping its only step as needed, we
# let the CI output collapse nicely in PRs.
if: failure() && github.event_name == 'push'
uses: ruby/action-slack@v3.2.1
with:
payload: |
{
"attachments": [{
"title": "Failure: ${{ github.workflow }}",
"title_link": "https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks",
"text": "${{ github.repository }}@${{ github.ref_name }}: <https://github.com/${{ github.repository }}/commit/${{ github.sha }}|${{ github.sha }}>",
"fields": [{ "value": ${{ toJson(github.event.head_commit.message) }}, "short": false }],
"footer": "${{ github.event.head_commit.committer.name }} at ${{ github.event.head_commit.timestamp }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
check_mergeability:
if: always()
runs-on: ubuntu-22.04
needs:
- android
- test
- windows
- vm
- cross
- ios
- wasm
- tailscale_go
- fuzz
- depaware
- go_generate
- go_mod_tidy
- licenses
- staticcheck
steps:
- name: Decide if change is okay to merge
if: github.event_name != 'push'
uses: re-actors/alls-green@release/v1
with:
jobs: ${{ toJSON(needs) }}

@ -1,30 +0,0 @@
name: "@tailscale/connect npm publish"
on: workflow_dispatch
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up node
uses: actions/setup-node@v3
with:
node-version: "16.x"
registry-url: "https://registry.npmjs.org"
- name: Build package
# Build with build_dist.sh to ensure that version information is embedded.
# GOROOT is specified so that the Go/Wasm that is trigged by build-pk
# also picks up our custom Go toolchain.
run: |
./build_dist.sh tailscale.com/cmd/tsconnect
GOROOT="${HOME}/.cache/tailscale-go" ./tsconnect build-pkg
- name: Publish
env:
NODE_AUTH_TOKEN: ${{ secrets.TSCONNECT_NPM_PUBLISH_AUTH_TOKEN }}
run: ./tool/yarn --cwd ./cmd/tsconnect/pkg publish --access public

@ -0,0 +1,49 @@
name: update-flake
on:
# run action when a change lands in the main branch which updates go.mod. Also
# allow manual triggering.
push:
branches:
- main
paths:
- go.mod
- .github/workflows/update-flakes.yml
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
update-flake:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Run update-flakes
run: ./update-flake.sh
- name: Get access token
uses: tibdex/github-app-token@b62528385c34dbc9f38e5f4225ac829252d1ea92 # v1.8.0
id: generate-token
with:
app_id: ${{ secrets.LICENSING_APP_ID }}
installation_id: ${{ secrets.LICENSING_APP_INSTALLATION_ID }}
private_key: ${{ secrets.LICENSING_APP_PRIVATE_KEY }}
- name: Send pull request
uses: peter-evans/create-pull-request@284f54f989303d2699d373481a0cfa13ad5a6666 #v5.0.1
with:
token: ${{ steps.generate-token.outputs.token }}
author: Flakes Updater <noreply+flakes-updater@tailscale.com>
committer: Flakes Updater <noreply+flakes-updater@tailscale.com>
branch: flakes
commit-message: "go.mod.sri: update SRI hash for go.mod changes"
title: "go.mod.sri: update SRI hash for go.mod changes"
body: Triggered by ${{ github.repository }}@${{ github.sha }}
signoff: true
delete-branch: true
reviewers: danderson

@ -0,0 +1,52 @@
name: update-webclient-prebuilt
on:
# manually triggered
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
update-webclient-prebuilt:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Run go get
run: |
./tool/go version # build gocross if needed using regular GOPROXY
GOPROXY=direct ./tool/go get github.com/tailscale/web-client-prebuilt
./tool/go mod tidy
- name: Get access token
uses: tibdex/github-app-token@b62528385c34dbc9f38e5f4225ac829252d1ea92 # v1.8.0
id: generate-token
with:
# TODO(will): this should use the code updater app rather than licensing.
# It has the same permissions, so not a big deal, but still.
app_id: ${{ secrets.LICENSING_APP_ID }}
installation_id: ${{ secrets.LICENSING_APP_INSTALLATION_ID }}
private_key: ${{ secrets.LICENSING_APP_PRIVATE_KEY }}
- name: Send pull request
id: pull-request
uses: peter-evans/create-pull-request@284f54f989303d2699d373481a0cfa13ad5a6666 #v5.0.1
with:
token: ${{ steps.generate-token.outputs.token }}
author: OSS Updater <noreply+oss-updater@tailscale.com>
committer: OSS Updater <noreply+oss-updater@tailscale.com>
branch: actions/update-webclient-prebuilt
commit-message: "go.mod: update web-client-prebuilt module"
title: "go.mod: update web-client-prebuilt module"
body: Triggered by ${{ github.repository }}@${{ github.sha }}
signoff: true
delete-branch: true
reviewers: ${{ github.triggering_actor }}
- name: Summary
if: ${{ steps.pull-request.outputs.pull-request-number }}
run: echo "${{ steps.pull-request.outputs.pull-request-operation}} ${{ steps.pull-request.outputs.pull-request-url }}" >> $GITHUB_STEP_SUMMARY

@ -1,51 +0,0 @@
name: VM
on:
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
ubuntu2004-LTS-cloud-base:
runs-on: [ self-hosted, linux, vm ]
if: "(github.repository == 'tailscale/tailscale') && !contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Set GOPATH
run: echo "GOPATH=$HOME/go" >> $GITHUB_ENV
- name: Checkout Code
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
- name: Run VM tests
run: go test ./tstest/integration/vms -v -no-s3 -run-vm-tests -run=TestRunUbuntu2004
env:
HOME: "/tmp"
TMPDIR: "/tmp"
XDG_CACHE_HOME: "/var/lib/ghrunner/cache"
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

@ -0,0 +1,40 @@
name: webclient
on:
workflow_dispatch:
# For now, only run on requests, not the main branches.
pull_request:
branches:
- "*"
paths:
- "client/web/**"
- ".github/workflows/webclient.yml"
- "!**.md"
# TODO(soniaappasamy): enable for main branch after an initial waiting period.
#push:
# branches:
# - main
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
webclient:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Install deps
run: ./tool/yarn --cwd client/web
- name: Run lint
run: ./tool/yarn --cwd client/web run --silent lint
- name: Run test
run: ./tool/yarn --cwd client/web run --silent test
- name: Run formatter check
run: |
./tool/yarn --cwd client/web run --silent format-check || ( \
echo "Run this command on your local device to fix the error:" && \
echo "" && \
echo " ./tool/yarn --cwd client/web format" && \
echo "" && exit 1)

@ -1,67 +0,0 @@
name: Windows
on:
push:
branches:
- main
pull_request:
branches:
- '*'
- 'release-branch/*'
concurrency:
group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
test:
runs-on: windows-latest
if: "!contains(github.event.head_commit.message, '[ci skip]')"
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Install Go
uses: actions/setup-go@v3
with:
go-version-file: go.mod
- name: Restore Cache
uses: actions/cache@v3
with:
# Note: unlike some other setups, this is only grabbing the mod download
# cache, rather than the whole mod directory, as the download cache
# contains zips that can be unpacked in parallel faster than they can be
# fetched and extracted by tar
path: |
~/go/pkg/mod/cache
~\AppData\Local\go-build
# The -2- here should be incremented when the scheme of data to be
# cached changes (e.g. path above changes).
# TODO(raggi): add a go version here.
key: ${{ runner.os }}-go-2-${{ hashFiles('**/go.sum') }}
- name: Test
# Don't use -bench=. -benchtime=1x.
# Somewhere in the layers (powershell?)
# the equals signs cause great confusion.
run: go test -bench . -benchtime 1x ./...
- uses: k0kubun/action-slack@v2.0.0
with:
payload: |
{
"attachments": [{
"text": "${{ job.status }}: ${{ github.workflow }} <https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks|${{ env.COMMIT_DATE }} #${{ env.COMMIT_NUMBER_OF_DAY }}> " +
"(<https://github.com/${{ github.repository }}/commit/${{ github.sha }}|" + "${{ github.sha }}".substring(0, 10) + ">) " +
"of ${{ github.repository }}@" + "${{ github.ref }}".split('/').reverse()[0] + " by ${{ github.event.head_commit.committer.name }}",
"color": "danger"
}]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
if: failure() && github.event_name == 'push'

15
.gitignore vendored

@ -9,6 +9,7 @@
cmd/tailscale/tailscale
cmd/tailscaled/tailscaled
ssh/tailssh/testcontainers/tailscaled
# Test binary, built with `go test -c`
*.test
@ -26,5 +27,19 @@ cmd/tailscaled/tailscaled
# Ignore personal VS Code settings
.vscode/
# Support personal project-specific GOPATH
.gopath/
# Ignore nix build result path
/result
# Ignore direnv nix-shell environment cache
.direnv/
# Ignore web client node modules
.vite/
client/web/node_modules
client/web/build/assets
/gocross
/dist

@ -0,0 +1,104 @@
linters:
# Don't enable any linters by default; just the ones that we explicitly
# enable in the list below.
disable-all: true
enable:
- bidichk
- gofmt
- goimports
- govet
- misspell
- revive
# Configuration for how we run golangci-lint
run:
timeout: 5m
issues:
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
# These are forks of an upstream package and thus are exempt from stylistic
# changes that would make pulling in upstream changes harder.
- path: tempfork/.*\.go
text: "File is not `gofmt`-ed with `-s` `-r 'interface{} -> any'`"
- path: util/singleflight/.*\.go
text: "File is not `gofmt`-ed with `-s` `-r 'interface{} -> any'`"
# Per-linter settings are contained in this top-level key
linters-settings:
# Enable all rules by default; we don't use invisible unicode runes.
bidichk:
gofmt:
rewrite-rules:
- pattern: 'interface{}'
replacement: 'any'
goimports:
govet:
# Matches what we use in corp as of 2023-12-07
enable:
- asmdecl
- assign
- atomic
- bools
- buildtag
- cgocall
- copylocks
- deepequalerrors
- errorsas
- framepointer
- httpresponse
- ifaceassert
- loopclosure
- lostcancel
- nilfunc
- nilness
- printf
- reflectvaluecompare
- shift
- sigchanyzer
- sortslice
- stdmethods
- stringintconv
- structtag
- testinggoroutine
- tests
- unmarshal
- unreachable
- unsafeptr
- unusedresult
settings:
printf:
# List of print function names to check (in addition to default)
funcs:
- github.com/tailscale/tailscale/types/logger.Discard
# NOTE(andrew-d): this doesn't currently work because the printf
# analyzer doesn't support type declarations
#- github.com/tailscale/tailscale/types/logger.Logf
misspell:
revive:
enable-all-rules: false
ignore-generated-header: true
rules:
- name: atomic
- name: context-keys-type
- name: defer
arguments: [[
# Calling 'recover' at the time a defer is registered (i.e. "defer recover()") has no effect.
"immediate-recover",
# Calling 'recover' outside of a deferred function has no effect
"recover",
# Returning values from a deferred function has no effect
"return",
]]
- name: duplicated-imports
- name: errorf
- name: string-of-int
- name: time-equal
- name: unconditional-recursion
- name: useless-break
- name: waitgroup-by-value

@ -1 +1 @@
3.16
3.18

@ -0,0 +1 @@
/tailcfg/ @tailscale/control-protocol-owners

@ -1,6 +1,5 @@
# Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Copyright (c) Tailscale Inc & AUTHORS
# SPDX-License-Identifier: BSD-3-Clause
############################################################################
#
@ -32,7 +31,7 @@
# $ docker exec tailscaled tailscale status
FROM golang:1.19-alpine AS build-env
FROM golang:1.22-alpine AS build-env
WORKDIR /go/src/tailscale
@ -48,8 +47,7 @@ RUN go install \
golang.org/x/crypto/ssh \
golang.org/x/crypto/acme \
nhooyr.io/websocket \
github.com/mdlayher/netlink \
golang.zx2c4.com/wireguard/device
github.com/mdlayher/netlink
COPY . .
@ -63,15 +61,15 @@ ENV VERSION_GIT_HASH=$VERSION_GIT_HASH
ARG TARGETARCH
RUN GOARCH=$TARGETARCH go install -ldflags="\
-X tailscale.com/version.Long=$VERSION_LONG \
-X tailscale.com/version.Short=$VERSION_SHORT \
-X tailscale.com/version.GitCommit=$VERSION_GIT_HASH" \
-X tailscale.com/version.longStamp=$VERSION_LONG \
-X tailscale.com/version.shortStamp=$VERSION_SHORT \
-X tailscale.com/version.gitCommitStamp=$VERSION_GIT_HASH" \
-v ./cmd/tailscale ./cmd/tailscaled ./cmd/containerboot
FROM alpine:3.16
FROM alpine:3.18
RUN apk add --no-cache ca-certificates iptables iproute2 ip6tables
COPY --from=build-env /go/bin/* /usr/local/bin/
# For compat with the previous run.sh, although ideally you should be
# using build_docker.sh which sets an entrypoint for the image.
RUN ln -s /usr/local/bin/containerboot /tailscale/run.sh
RUN mkdir /tailscale && ln -s /usr/local/bin/containerboot /tailscale/run.sh

@ -1,6 +1,5 @@
# Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Copyright (c) Tailscale Inc & AUTHORS
# SPDX-License-Identifier: BSD-3-Clause
FROM alpine:3.16
RUN apk add --no-cache ca-certificates iptables iproute2 ip6tables
FROM alpine:3.18
RUN apk add --no-cache ca-certificates iptables iproute2 ip6tables iputils

@ -1,7 +1,6 @@
BSD 3-Clause License
Copyright (c) 2020 Tailscale & AUTHORS.
All rights reserved.
Copyright (c) 2020 Tailscale Inc & AUTHORS.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

@ -1,62 +1,126 @@
IMAGE_REPO ?= tailscale/tailscale
SYNO_ARCH ?= "amd64"
SYNO_ARCH ?= "x86_64"
SYNO_DSM ?= "7"
TAGS ?= "latest"
usage:
echo "See Makefile"
PLATFORM ?= "flyio" ## flyio==linux/amd64. Set to "" to build all platforms.
vet:
vet: ## Run go vet
./tool/go vet ./...
tidy:
tidy: ## Run go mod tidy
./tool/go mod tidy
updatedeps:
./tool/go run github.com/tailscale/depaware --update \
lint: ## Run golangci-lint
./tool/go run github.com/golangci/golangci-lint/cmd/golangci-lint run
updatedeps: ## Update depaware deps
# depaware (via x/tools/go/packages) shells back to "go", so make sure the "go"
# it finds in its $$PATH is the right one.
PATH="$$(./tool/go env GOROOT)/bin:$$PATH" ./tool/go run github.com/tailscale/depaware --update \
tailscale.com/cmd/tailscaled \
tailscale.com/cmd/tailscale \
tailscale.com/cmd/derper
tailscale.com/cmd/derper \
tailscale.com/cmd/stund
depaware:
./tool/go run github.com/tailscale/depaware --check \
depaware: ## Run depaware checks
# depaware (via x/tools/go/packages) shells back to "go", so make sure the "go"
# it finds in its $$PATH is the right one.
PATH="$$(./tool/go env GOROOT)/bin:$$PATH" ./tool/go run github.com/tailscale/depaware --check \
tailscale.com/cmd/tailscaled \
tailscale.com/cmd/tailscale \
tailscale.com/cmd/derper
tailscale.com/cmd/derper \
tailscale.com/cmd/stund
buildwindows:
buildwindows: ## Build tailscale CLI for windows/amd64
GOOS=windows GOARCH=amd64 ./tool/go install tailscale.com/cmd/tailscale tailscale.com/cmd/tailscaled
build386:
build386: ## Build tailscale CLI for linux/386
GOOS=linux GOARCH=386 ./tool/go install tailscale.com/cmd/tailscale tailscale.com/cmd/tailscaled
buildlinuxarm:
buildlinuxarm: ## Build tailscale CLI for linux/arm
GOOS=linux GOARCH=arm ./tool/go install tailscale.com/cmd/tailscale tailscale.com/cmd/tailscaled
buildwasm:
buildwasm: ## Build tailscale CLI for js/wasm
GOOS=js GOARCH=wasm ./tool/go install ./cmd/tsconnect/wasm ./cmd/tailscale/cli
buildmultiarchimage:
buildplan9:
GOOS=plan9 GOARCH=amd64 ./tool/go install ./cmd/tailscale ./cmd/tailscaled
buildlinuxloong64: ## Build tailscale CLI for linux/loong64
GOOS=linux GOARCH=loong64 ./tool/go install tailscale.com/cmd/tailscale tailscale.com/cmd/tailscaled
buildmultiarchimage: ## Build (and optionally push) multiarch docker image
./build_docker.sh
check: staticcheck vet depaware buildwindows build386 buildlinuxarm buildwasm
check: staticcheck vet depaware buildwindows build386 buildlinuxarm buildwasm ## Perform basic checks and compilation tests
staticcheck:
staticcheck: ## Run staticcheck.io checks
./tool/go run honnef.co/go/tools/cmd/staticcheck -- $$(./tool/go list ./... | grep -v tempfork)
spk:
PATH="${PWD}/tool:${PATH}" ./tool/go run github.com/tailscale/tailscale-synology@main -o tailscale.spk --source=. --goarch=${SYNO_ARCH} --dsm-version=${SYNO_DSM}
kube-generate-all: kube-generate-deepcopy ## Refresh generated files for Tailscale Kubernetes Operator
./tool/go generate ./cmd/k8s-operator
# Tailscale operator watches Connector custom resources in a Kubernetes cluster
# and caches them locally. Caching is done implicitly by controller-runtime
# library (the middleware used by Tailscale operator to create kube control
# loops). When a Connector resource is GET/LIST-ed from within our control loop,
# the request goes through the cache. To ensure that cache contents don't get
# modified by control loops, controller-runtime deep copies the requested
# object. In order for this to work, Connector must implement deep copy
# functionality so we autogenerate it here.
# https://github.com/kubernetes-sigs/controller-runtime/blob/v0.16.3/pkg/cache/internal/cache_reader.go#L86-L89
kube-generate-deepcopy: ## Refresh generated deepcopy functionality for Tailscale kube API types
./scripts/kube-deepcopy.sh
spkall:
mkdir -p spks
PATH="${PWD}/tool:${PATH}" ./tool/go run github.com/tailscale/tailscale-synology@main -o spks --source=. --goarch=all --dsm-version=all
spk: ## Build synology package for ${SYNO_ARCH} architecture and ${SYNO_DSM} DSM version
./tool/go run ./cmd/dist build synology/dsm${SYNO_DSM}/${SYNO_ARCH}
pushspk: spk
spkall: ## Build synology packages for all architectures and DSM versions
./tool/go run ./cmd/dist build synology
pushspk: spk ## Push and install synology package on ${SYNO_HOST} host
echo "Pushing SPK to root@${SYNO_HOST} (env var SYNO_HOST) ..."
scp tailscale.spk root@${SYNO_HOST}:
ssh root@${SYNO_HOST} /usr/syno/bin/synopkg install tailscale.spk
publishdevimage:
publishdevimage: ## Build and publish tailscale image to location specified by ${REPO}
@test -n "${REPO}" || (echo "REPO=... required; e.g. REPO=ghcr.io/${USER}/tailscale" && exit 1)
@test "${REPO}" != "tailscale/tailscale" || (echo "REPO=... must not be tailscale/tailscale" && exit 1)
@test "${REPO}" != "ghcr.io/tailscale/tailscale" || (echo "REPO=... must not be ghcr.io/tailscale/tailscale" && exit 1)
@test "${REPO}" != "tailscale/k8s-operator" || (echo "REPO=... must not be tailscale/k8s-operator" && exit 1)
@test "${REPO}" != "ghcr.io/tailscale/k8s-operator" || (echo "REPO=... must not be ghcr.io/tailscale/k8s-operator" && exit 1)
TAGS="${TAGS}" REPOS=${REPO} PLATFORM=${PLATFORM} PUSH=true TARGET=client ./build_docker.sh
publishdevoperator: ## Build and publish k8s-operator image to location specified by ${REPO}
@test -n "${REPO}" || (echo "REPO=... required; e.g. REPO=ghcr.io/${USER}/tailscale" && exit 1)
@test "${REPO}" != "tailscale/tailscale" || (echo "REPO=... must not be tailscale/tailscale" && exit 1)
@test "${REPO}" != "ghcr.io/tailscale/tailscale" || (echo "REPO=... must not be ghcr.io/tailscale/tailscale" && exit 1)
@test "${REPO}" != "tailscale/k8s-operator" || (echo "REPO=... must not be tailscale/k8s-operator" && exit 1)
@test "${REPO}" != "ghcr.io/tailscale/k8s-operator" || (echo "REPO=... must not be ghcr.io/tailscale/k8s-operator" && exit 1)
TAGS="${TAGS}" REPOS=${REPO} PLATFORM=${PLATFORM} PUSH=true TARGET=operator ./build_docker.sh
publishdevnameserver: ## Build and publish k8s-nameserver image to location specified by ${REPO}
@test -n "${REPO}" || (echo "REPO=... required; e.g. REPO=ghcr.io/${USER}/tailscale" && exit 1)
@test "${REPO}" != "tailscale/tailscale" || (echo "REPO=... must not be tailscale/tailscale" && exit 1)
@test "${REPO}" != "ghcr.io/tailscale/tailscale" || (echo "REPO=... must not be ghcr.io/tailscale/tailscale" && exit 1)
TAGS=latest REPOS=${REPO} PUSH=true ./build_docker.sh
@test "${REPO}" != "tailscale/k8s-nameserver" || (echo "REPO=... must not be tailscale/k8s-nameserver" && exit 1)
@test "${REPO}" != "ghcr.io/tailscale/k8s-nameserver" || (echo "REPO=... must not be ghcr.io/tailscale/k8s-nameserver" && exit 1)
TAGS="${TAGS}" REPOS=${REPO} PLATFORM=${PLATFORM} PUSH=true TARGET=k8s-nameserver ./build_docker.sh
.PHONY: sshintegrationtest
sshintegrationtest: ## Run the SSH integration tests in various Docker containers
@GOOS=linux GOARCH=amd64 go test -tags integrationtest -c ./ssh/tailssh -o ssh/tailssh/testcontainers/tailssh.test && \
GOOS=linux GOARCH=amd64 go build -o ssh/tailssh/testcontainers/tailscaled ./cmd/tailscaled && \
echo "Testing on ubuntu:focal" && docker build --build-arg="BASE=ubuntu:focal" -t ssh-ubuntu-focal ssh/tailssh/testcontainers && \
echo "Testing on ubuntu:jammy" && docker build --build-arg="BASE=ubuntu:jammy" -t ssh-ubuntu-jammy ssh/tailssh/testcontainers && \
echo "Testing on ubuntu:mantic" && docker build --build-arg="BASE=ubuntu:mantic" -t ssh-ubuntu-mantic ssh/tailssh/testcontainers && \
echo "Testing on ubuntu:noble" && docker build --build-arg="BASE=ubuntu:noble" -t ssh-ubuntu-noble ssh/tailssh/testcontainers
help: ## Show this help
@echo "\nSpecify a command. The choices are:\n"
@grep -hE '^[0-9a-zA-Z_-]+:.*?## .*$$' ${MAKEFILE_LIST} | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[0;36m%-20s\033[m %s\n", $$1, $$2}'
@echo ""
.PHONY: help
.DEFAULT_GOAL := help

@ -6,27 +6,41 @@ Private WireGuard® networks made easy
## Overview
This repository contains all the open source Tailscale client code and
the `tailscaled` daemon and `tailscale` CLI tool. The `tailscaled`
daemon runs on Linux, Windows and [macOS](https://tailscale.com/kb/1065/macos-variants/), and to varying degrees on FreeBSD, OpenBSD, and Darwin. (The Tailscale iOS and Android apps use this repo's code, but this repo doesn't contain the mobile GUI code.)
This repository contains the majority of Tailscale's open source code.
Notably, it includes the `tailscaled` daemon and
the `tailscale` CLI tool. The `tailscaled` daemon runs on Linux, Windows,
[macOS](https://tailscale.com/kb/1065/macos-variants/), and to varying degrees
on FreeBSD and OpenBSD. The Tailscale iOS and Android apps use this repo's
code, but this repo doesn't contain the mobile GUI code.
The Android app is at https://github.com/tailscale/tailscale-android
Other [Tailscale repos](https://github.com/orgs/tailscale/repositories) of note:
The Synology package is at https://github.com/tailscale/tailscale-synology
* the Android app is at https://github.com/tailscale/tailscale-android
* the Synology package is at https://github.com/tailscale/tailscale-synology
* the QNAP package is at https://github.com/tailscale/tailscale-qpkg
* the Chocolatey packaging is at https://github.com/tailscale/tailscale-chocolatey
For background on which parts of Tailscale are open source and why,
see [https://tailscale.com/opensource/](https://tailscale.com/opensource/).
## Using
We serve packages for a variety of distros at
https://pkgs.tailscale.com .
We serve packages for a variety of distros and platforms at
[https://pkgs.tailscale.com](https://pkgs.tailscale.com/).
## Other clients
The [macOS, iOS, and Windows clients](https://tailscale.com/download)
use the code in this repository but additionally include small GUI
wrappers that are not open source.
wrappers. The GUI wrappers on non-open source platforms are themselves
not open source.
## Building
We always require the latest Go release, currently Go 1.22. (While we build
releases with our [Go fork](https://github.com/tailscale/go/), its use is not
required.)
```
go install tailscale.com/cmd/tailscale{,d}
```
@ -43,8 +57,6 @@ If your distro has conventions that preclude the use of
`build_dist.sh`, please do the equivalent of what it does in your
distro's way, so that bug reports contain useful version information.
We require the latest Go release, currently Go 1.19.
## Bugs
Please file any issues about this code or the hosted service on

@ -1 +1 @@
1.33.0
1.67.0

1247
api.md

File diff suppressed because it is too large Load Diff

@ -0,0 +1,496 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// Package appc implements App Connectors.
// An AppConnector provides DNS domain oriented routing of traffic. An App
// Connector becomes a DNS server for a peer, authoritative for the set of
// configured domains. DNS resolution of the target domain triggers dynamic
// publication of routes to ensure that traffic to the domain is routed through
// the App Connector.
package appc
import (
"context"
"net/netip"
"slices"
"strings"
"sync"
xmaps "golang.org/x/exp/maps"
"golang.org/x/net/dns/dnsmessage"
"tailscale.com/types/logger"
"tailscale.com/types/views"
"tailscale.com/util/dnsname"
"tailscale.com/util/execqueue"
"tailscale.com/util/mak"
"tailscale.com/util/slicesx"
)
// RouteAdvertiser is an interface that allows the AppConnector to advertise
// newly discovered routes that need to be served through the AppConnector.
type RouteAdvertiser interface {
// AdvertiseRoute adds one or more route advertisements skipping any that
// are already advertised.
AdvertiseRoute(...netip.Prefix) error
// UnadvertiseRoute removes any matching route advertisements.
UnadvertiseRoute(...netip.Prefix) error
}
// RouteInfo is a data structure used to persist the in memory state of an AppConnector
// so that we can know, even after a restart, which routes came from ACLs and which were
// learned from domains.
type RouteInfo struct {
// Control is the routes from the 'routes' section of an app connector acl.
Control []netip.Prefix `json:",omitempty"`
// Domains are the routes discovered by observing DNS lookups for configured domains.
Domains map[string][]netip.Addr `json:",omitempty"`
// Wildcards are the configured DNS lookup domains to observe. When a DNS query matches Wildcards,
// its result is added to Domains.
Wildcards []string `json:",omitempty"`
}
// AppConnector is an implementation of an AppConnector that performs
// its function as a subsystem inside of a tailscale node. At the control plane
// side App Connector routing is configured in terms of domains rather than IP
// addresses.
// The AppConnectors responsibility inside tailscaled is to apply the routing
// and domain configuration as supplied in the map response.
// DNS requests for configured domains are observed. If the domains resolve to
// routes not yet served by the AppConnector the local node configuration is
// updated to advertise the new route.
type AppConnector struct {
logf logger.Logf
routeAdvertiser RouteAdvertiser
// storeRoutesFunc will be called to persist routes if it is not nil.
storeRoutesFunc func(*RouteInfo) error
// mu guards the fields that follow
mu sync.Mutex
// domains is a map of lower case domain names with no trailing dot, to an
// ordered list of resolved IP addresses.
domains map[string][]netip.Addr
// controlRoutes is the list of routes that were last supplied by control.
controlRoutes []netip.Prefix
// wildcards is the list of domain strings that match subdomains.
wildcards []string
// queue provides ordering for update operations
queue execqueue.ExecQueue
}
// NewAppConnector creates a new AppConnector.
func NewAppConnector(logf logger.Logf, routeAdvertiser RouteAdvertiser, routeInfo *RouteInfo, storeRoutesFunc func(*RouteInfo) error) *AppConnector {
ac := &AppConnector{
logf: logger.WithPrefix(logf, "appc: "),
routeAdvertiser: routeAdvertiser,
storeRoutesFunc: storeRoutesFunc,
}
if routeInfo != nil {
ac.domains = routeInfo.Domains
ac.wildcards = routeInfo.Wildcards
ac.controlRoutes = routeInfo.Control
}
return ac
}
// ShouldStoreRoutes returns true if the appconnector was created with the controlknob on
// and is storing its discovered routes persistently.
func (e *AppConnector) ShouldStoreRoutes() bool {
return e.storeRoutesFunc != nil
}
// storeRoutesLocked takes the current state of the AppConnector and persists it
func (e *AppConnector) storeRoutesLocked() error {
if !e.ShouldStoreRoutes() {
return nil
}
return e.storeRoutesFunc(&RouteInfo{
Control: e.controlRoutes,
Domains: e.domains,
Wildcards: e.wildcards,
})
}
// ClearRoutes removes all route state from the AppConnector.
func (e *AppConnector) ClearRoutes() error {
e.mu.Lock()
defer e.mu.Unlock()
e.controlRoutes = nil
e.domains = nil
e.wildcards = nil
return e.storeRoutesLocked()
}
// UpdateDomainsAndRoutes starts an asynchronous update of the configuration
// given the new domains and routes.
func (e *AppConnector) UpdateDomainsAndRoutes(domains []string, routes []netip.Prefix) {
e.queue.Add(func() {
// Add the new routes first.
e.updateRoutes(routes)
e.updateDomains(domains)
})
}
// UpdateDomains asynchronously replaces the current set of configured domains
// with the supplied set of domains. Domains must not contain a trailing dot,
// and should be lower case. If the domain contains a leading '*' label it
// matches all subdomains of a domain.
func (e *AppConnector) UpdateDomains(domains []string) {
e.queue.Add(func() {
e.updateDomains(domains)
})
}
// Wait waits for the currently scheduled asynchronous configuration changes to
// complete.
func (e *AppConnector) Wait(ctx context.Context) {
e.queue.Wait(ctx)
}
func (e *AppConnector) updateDomains(domains []string) {
e.mu.Lock()
defer e.mu.Unlock()
var oldDomains map[string][]netip.Addr
oldDomains, e.domains = e.domains, make(map[string][]netip.Addr, len(domains))
e.wildcards = e.wildcards[:0]
for _, d := range domains {
d = strings.ToLower(d)
if len(d) == 0 {
continue
}
if strings.HasPrefix(d, "*.") {
e.wildcards = append(e.wildcards, d[2:])
continue
}
e.domains[d] = oldDomains[d]
delete(oldDomains, d)
}
// Ensure that still-live wildcards addresses are preserved as well.
for d, addrs := range oldDomains {
for _, wc := range e.wildcards {
if dnsname.HasSuffix(d, wc) {
e.domains[d] = addrs
delete(oldDomains, d)
break
}
}
}
// Everything left in oldDomains is a domain we're no longer tracking
// and if we are storing route info we can unadvertise the routes
if e.ShouldStoreRoutes() {
toRemove := []netip.Prefix{}
for _, addrs := range oldDomains {
for _, a := range addrs {
toRemove = append(toRemove, netip.PrefixFrom(a, a.BitLen()))
}
}
if err := e.routeAdvertiser.UnadvertiseRoute(toRemove...); err != nil {
e.logf("failed to unadvertise routes on domain removal: %v: %v: %v", xmaps.Keys(oldDomains), toRemove, err)
}
}
e.logf("handling domains: %v and wildcards: %v", xmaps.Keys(e.domains), e.wildcards)
}
// updateRoutes merges the supplied routes into the currently configured routes. The routes supplied
// by control for UpdateRoutes are supplemental to the routes discovered by DNS resolution, but are
// also more often whole ranges. UpdateRoutes will remove any single address routes that are now
// covered by new ranges.
func (e *AppConnector) updateRoutes(routes []netip.Prefix) {
e.mu.Lock()
defer e.mu.Unlock()
// If there was no change since the last update, no work to do.
if slices.Equal(e.controlRoutes, routes) {
return
}
if err := e.routeAdvertiser.AdvertiseRoute(routes...); err != nil {
e.logf("failed to advertise routes: %v: %v", routes, err)
return
}
var toRemove []netip.Prefix
// If we're storing routes and know e.controlRoutes is a good
// representation of what should be in AdvertisedRoutes we can stop
// advertising routes that used to be in e.controlRoutes but are not
// in routes.
if e.ShouldStoreRoutes() {
toRemove = routesWithout(e.controlRoutes, routes)
}
nextRoute:
for _, r := range routes {
for _, addr := range e.domains {
for _, a := range addr {
if r.Contains(a) && netip.PrefixFrom(a, a.BitLen()) != r {
pfx := netip.PrefixFrom(a, a.BitLen())
toRemove = append(toRemove, pfx)
continue nextRoute
}
}
}
}
if err := e.routeAdvertiser.UnadvertiseRoute(toRemove...); err != nil {
e.logf("failed to unadvertise routes: %v: %v", toRemove, err)
}
e.controlRoutes = routes
if err := e.storeRoutesLocked(); err != nil {
e.logf("failed to store route info: %v", err)
}
}
// Domains returns the currently configured domain list.
func (e *AppConnector) Domains() views.Slice[string] {
e.mu.Lock()
defer e.mu.Unlock()
return views.SliceOf(xmaps.Keys(e.domains))
}
// DomainRoutes returns a map of domains to resolved IP
// addresses.
func (e *AppConnector) DomainRoutes() map[string][]netip.Addr {
e.mu.Lock()
defer e.mu.Unlock()
drCopy := make(map[string][]netip.Addr)
for k, v := range e.domains {
drCopy[k] = append(drCopy[k], v...)
}
return drCopy
}
// ObserveDNSResponse is a callback invoked by the DNS resolver when a DNS
// response is being returned over the PeerAPI. The response is parsed and
// matched against the configured domains, if matched the routeAdvertiser is
// advised to advertise the discovered route.
func (e *AppConnector) ObserveDNSResponse(res []byte) {
var p dnsmessage.Parser
if _, err := p.Start(res); err != nil {
return
}
if err := p.SkipAllQuestions(); err != nil {
return
}
// cnameChain tracks a chain of CNAMEs for a given query in order to reverse
// a CNAME chain back to the original query for flattening. The keys are
// CNAME record targets, and the value is the name the record answers, so
// for www.example.com CNAME example.com, the map would contain
// ["example.com"] = "www.example.com".
var cnameChain map[string]string
// addressRecords is a list of address records found in the response.
var addressRecords map[string][]netip.Addr
for {
h, err := p.AnswerHeader()
if err == dnsmessage.ErrSectionDone {
break
}
if err != nil {
return
}
if h.Class != dnsmessage.ClassINET {
if err := p.SkipAnswer(); err != nil {
return
}
continue
}
switch h.Type {
case dnsmessage.TypeCNAME, dnsmessage.TypeA, dnsmessage.TypeAAAA:
default:
if err := p.SkipAnswer(); err != nil {
return
}
continue
}
domain := strings.TrimSuffix(strings.ToLower(h.Name.String()), ".")
if len(domain) == 0 {
continue
}
if h.Type == dnsmessage.TypeCNAME {
res, err := p.CNAMEResource()
if err != nil {
return
}
cname := strings.TrimSuffix(strings.ToLower(res.CNAME.String()), ".")
if len(cname) == 0 {
continue
}
mak.Set(&cnameChain, cname, domain)
continue
}
switch h.Type {
case dnsmessage.TypeA:
r, err := p.AResource()
if err != nil {
return
}
addr := netip.AddrFrom4(r.A)
mak.Set(&addressRecords, domain, append(addressRecords[domain], addr))
case dnsmessage.TypeAAAA:
r, err := p.AAAAResource()
if err != nil {
return
}
addr := netip.AddrFrom16(r.AAAA)
mak.Set(&addressRecords, domain, append(addressRecords[domain], addr))
default:
if err := p.SkipAnswer(); err != nil {
return
}
continue
}
}
e.mu.Lock()
defer e.mu.Unlock()
for domain, addrs := range addressRecords {
domain, isRouted := e.findRoutedDomainLocked(domain, cnameChain)
// domain and none of the CNAMEs in the chain are routed
if !isRouted {
continue
}
// advertise each address we have learned for the routed domain, that
// was not already known.
var toAdvertise []netip.Prefix
for _, addr := range addrs {
if !e.isAddrKnownLocked(domain, addr) {
toAdvertise = append(toAdvertise, netip.PrefixFrom(addr, addr.BitLen()))
}
}
e.logf("[v2] observed new routes for %s: %s", domain, toAdvertise)
e.scheduleAdvertisement(domain, toAdvertise...)
}
}
// starting from the given domain that resolved to an address, find it, or any
// of the domains in the CNAME chain toward resolving it, that are routed
// domains, returning the routed domain name and a bool indicating whether a
// routed domain was found.
// e.mu must be held.
func (e *AppConnector) findRoutedDomainLocked(domain string, cnameChain map[string]string) (string, bool) {
var isRouted bool
for {
_, isRouted = e.domains[domain]
if isRouted {
break
}
// match wildcard domains
for _, wc := range e.wildcards {
if dnsname.HasSuffix(domain, wc) {
e.domains[domain] = nil
isRouted = true
break
}
}
next, ok := cnameChain[domain]
if !ok {
break
}
domain = next
}
return domain, isRouted
}
// isAddrKnownLocked returns true if the address is known to be associated with
// the given domain. Known domain tables are updated for covered routes to speed
// up future matches.
// e.mu must be held.
func (e *AppConnector) isAddrKnownLocked(domain string, addr netip.Addr) bool {
if e.hasDomainAddrLocked(domain, addr) {
return true
}
for _, route := range e.controlRoutes {
if route.Contains(addr) {
// record the new address associated with the domain for faster matching in subsequent
// requests and for diagnostic records.
e.addDomainAddrLocked(domain, addr)
return true
}
}
return false
}
// scheduleAdvertisement schedules an advertisement of the given address
// associated with the given domain.
func (e *AppConnector) scheduleAdvertisement(domain string, routes ...netip.Prefix) {
e.queue.Add(func() {
if err := e.routeAdvertiser.AdvertiseRoute(routes...); err != nil {
e.logf("failed to advertise routes for %s: %v: %v", domain, routes, err)
return
}
e.mu.Lock()
defer e.mu.Unlock()
for _, route := range routes {
if !route.IsSingleIP() {
continue
}
addr := route.Addr()
if !e.hasDomainAddrLocked(domain, addr) {
e.addDomainAddrLocked(domain, addr)
e.logf("[v2] advertised route for %v: %v", domain, addr)
}
}
if err := e.storeRoutesLocked(); err != nil {
e.logf("failed to store route info: %v", err)
}
})
}
// hasDomainAddrLocked returns true if the address has been observed in a
// resolution of domain.
func (e *AppConnector) hasDomainAddrLocked(domain string, addr netip.Addr) bool {
_, ok := slices.BinarySearchFunc(e.domains[domain], addr, compareAddr)
return ok
}
// addDomainAddrLocked adds the address to the list of addresses resolved for
// domain and ensures the list remains sorted. Does not attempt to deduplicate.
func (e *AppConnector) addDomainAddrLocked(domain string, addr netip.Addr) {
e.domains[domain] = append(e.domains[domain], addr)
slices.SortFunc(e.domains[domain], compareAddr)
}
func compareAddr(l, r netip.Addr) int {
return l.Compare(r)
}
// routesWithout returns a without b where a and b
// are unsorted slices of netip.Prefix
func routesWithout(a, b []netip.Prefix) []netip.Prefix {
m := make(map[netip.Prefix]bool, len(b))
for _, p := range b {
m[p] = true
}
return slicesx.Filter(make([]netip.Prefix, 0, len(a)), a, func(p netip.Prefix) bool {
return !m[p]
})
}

@ -0,0 +1,522 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package appc
import (
"context"
"net/netip"
"reflect"
"slices"
"testing"
xmaps "golang.org/x/exp/maps"
"golang.org/x/net/dns/dnsmessage"
"tailscale.com/appc/appctest"
"tailscale.com/util/mak"
"tailscale.com/util/must"
)
func fakeStoreRoutes(*RouteInfo) error { return nil }
func TestUpdateDomains(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
ctx := context.Background()
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, &appctest.RouteCollector{}, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, &appctest.RouteCollector{}, nil, nil)
}
a.UpdateDomains([]string{"example.com"})
a.Wait(ctx)
if got, want := a.Domains().AsSlice(), []string{"example.com"}; !slices.Equal(got, want) {
t.Errorf("got %v; want %v", got, want)
}
addr := netip.MustParseAddr("192.0.0.8")
a.domains["example.com"] = append(a.domains["example.com"], addr)
a.UpdateDomains([]string{"example.com"})
a.Wait(ctx)
if got, want := a.domains["example.com"], []netip.Addr{addr}; !slices.Equal(got, want) {
t.Errorf("got %v; want %v", got, want)
}
// domains are explicitly downcased on set.
a.UpdateDomains([]string{"UP.EXAMPLE.COM"})
a.Wait(ctx)
if got, want := xmaps.Keys(a.domains), []string{"up.example.com"}; !slices.Equal(got, want) {
t.Errorf("got %v; want %v", got, want)
}
}
}
func TestUpdateRoutes(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
ctx := context.Background()
rc := &appctest.RouteCollector{}
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, rc, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, rc, nil, nil)
}
a.updateDomains([]string{"*.example.com"})
// This route should be collapsed into the range
a.ObserveDNSResponse(dnsResponse("a.example.com.", "192.0.2.1"))
a.Wait(ctx)
if !slices.Equal(rc.Routes(), []netip.Prefix{netip.MustParsePrefix("192.0.2.1/32")}) {
t.Fatalf("got %v, want %v", rc.Routes(), []netip.Prefix{netip.MustParsePrefix("192.0.2.1/32")})
}
// This route should not be collapsed or removed
a.ObserveDNSResponse(dnsResponse("b.example.com.", "192.0.0.1"))
a.Wait(ctx)
routes := []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24"), netip.MustParsePrefix("192.0.0.1/32")}
a.updateRoutes(routes)
slices.SortFunc(rc.Routes(), prefixCompare)
rc.SetRoutes(slices.Compact(rc.Routes()))
slices.SortFunc(routes, prefixCompare)
// Ensure that the non-matching /32 is preserved, even though it's in the domains table.
if !slices.EqualFunc(routes, rc.Routes(), prefixEqual) {
t.Errorf("added routes: got %v, want %v", rc.Routes(), routes)
}
// Ensure that the contained /32 is removed, replaced by the /24.
wantRemoved := []netip.Prefix{netip.MustParsePrefix("192.0.2.1/32")}
if !slices.EqualFunc(rc.RemovedRoutes(), wantRemoved, prefixEqual) {
t.Fatalf("unexpected removed routes: %v", rc.RemovedRoutes())
}
}
}
func TestUpdateRoutesUnadvertisesContainedRoutes(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
rc := &appctest.RouteCollector{}
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, rc, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, rc, nil, nil)
}
mak.Set(&a.domains, "example.com", []netip.Addr{netip.MustParseAddr("192.0.2.1")})
rc.SetRoutes([]netip.Prefix{netip.MustParsePrefix("192.0.2.1/32")})
routes := []netip.Prefix{netip.MustParsePrefix("192.0.2.0/24")}
a.updateRoutes(routes)
if !slices.EqualFunc(routes, rc.Routes(), prefixEqual) {
t.Fatalf("got %v, want %v", rc.Routes(), routes)
}
}
}
func TestDomainRoutes(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
rc := &appctest.RouteCollector{}
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, rc, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, rc, nil, nil)
}
a.updateDomains([]string{"example.com"})
a.ObserveDNSResponse(dnsResponse("example.com.", "192.0.0.8"))
a.Wait(context.Background())
want := map[string][]netip.Addr{
"example.com": {netip.MustParseAddr("192.0.0.8")},
}
if got := a.DomainRoutes(); !reflect.DeepEqual(got, want) {
t.Fatalf("DomainRoutes: got %v, want %v", got, want)
}
}
}
func TestObserveDNSResponse(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
ctx := context.Background()
rc := &appctest.RouteCollector{}
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, rc, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, rc, nil, nil)
}
// a has no domains configured, so it should not advertise any routes
a.ObserveDNSResponse(dnsResponse("example.com.", "192.0.0.8"))
if got, want := rc.Routes(), ([]netip.Prefix)(nil); !slices.Equal(got, want) {
t.Errorf("got %v; want %v", got, want)
}
wantRoutes := []netip.Prefix{netip.MustParsePrefix("192.0.0.8/32")}
a.updateDomains([]string{"example.com"})
a.ObserveDNSResponse(dnsResponse("example.com.", "192.0.0.8"))
a.Wait(ctx)
if got, want := rc.Routes(), wantRoutes; !slices.Equal(got, want) {
t.Errorf("got %v; want %v", got, want)
}
// a CNAME record chain should result in a route being added if the chain
// matches a routed domain.
a.updateDomains([]string{"www.example.com", "example.com"})
a.ObserveDNSResponse(dnsCNAMEResponse("192.0.0.9", "www.example.com.", "chain.example.com.", "example.com."))
a.Wait(ctx)
wantRoutes = append(wantRoutes, netip.MustParsePrefix("192.0.0.9/32"))
if got, want := rc.Routes(), wantRoutes; !slices.Equal(got, want) {
t.Errorf("got %v; want %v", got, want)
}
// a CNAME record chain should result in a route being added if the chain
// even if only found in the middle of the chain
a.ObserveDNSResponse(dnsCNAMEResponse("192.0.0.10", "outside.example.org.", "www.example.com.", "example.org."))
a.Wait(ctx)
wantRoutes = append(wantRoutes, netip.MustParsePrefix("192.0.0.10/32"))
if got, want := rc.Routes(), wantRoutes; !slices.Equal(got, want) {
t.Errorf("got %v; want %v", got, want)
}
wantRoutes = append(wantRoutes, netip.MustParsePrefix("2001:db8::1/128"))
a.ObserveDNSResponse(dnsResponse("example.com.", "2001:db8::1"))
a.Wait(ctx)
if got, want := rc.Routes(), wantRoutes; !slices.Equal(got, want) {
t.Errorf("got %v; want %v", got, want)
}
// don't re-advertise routes that have already been advertised
a.ObserveDNSResponse(dnsResponse("example.com.", "2001:db8::1"))
a.Wait(ctx)
if !slices.Equal(rc.Routes(), wantRoutes) {
t.Errorf("rc.Routes(): got %v; want %v", rc.Routes(), wantRoutes)
}
// don't advertise addresses that are already in a control provided route
pfx := netip.MustParsePrefix("192.0.2.0/24")
a.updateRoutes([]netip.Prefix{pfx})
wantRoutes = append(wantRoutes, pfx)
a.ObserveDNSResponse(dnsResponse("example.com.", "192.0.2.1"))
a.Wait(ctx)
if !slices.Equal(rc.Routes(), wantRoutes) {
t.Errorf("rc.Routes(): got %v; want %v", rc.Routes(), wantRoutes)
}
if !slices.Contains(a.domains["example.com"], netip.MustParseAddr("192.0.2.1")) {
t.Errorf("missing %v from %v", "192.0.2.1", a.domains["exmaple.com"])
}
}
}
func TestWildcardDomains(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
ctx := context.Background()
rc := &appctest.RouteCollector{}
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, rc, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, rc, nil, nil)
}
a.updateDomains([]string{"*.example.com"})
a.ObserveDNSResponse(dnsResponse("foo.example.com.", "192.0.0.8"))
a.Wait(ctx)
if got, want := rc.Routes(), []netip.Prefix{netip.MustParsePrefix("192.0.0.8/32")}; !slices.Equal(got, want) {
t.Errorf("routes: got %v; want %v", got, want)
}
if got, want := a.wildcards, []string{"example.com"}; !slices.Equal(got, want) {
t.Errorf("wildcards: got %v; want %v", got, want)
}
a.updateDomains([]string{"*.example.com", "example.com"})
if _, ok := a.domains["foo.example.com"]; !ok {
t.Errorf("expected foo.example.com to be preserved in domains due to wildcard")
}
if got, want := a.wildcards, []string{"example.com"}; !slices.Equal(got, want) {
t.Errorf("wildcards: got %v; want %v", got, want)
}
// There was an early regression where the wildcard domain was added repeatedly, this guards against that.
a.updateDomains([]string{"*.example.com", "example.com"})
if len(a.wildcards) != 1 {
t.Errorf("expected only one wildcard domain, got %v", a.wildcards)
}
}
}
// dnsResponse is a test helper that creates a DNS response buffer for the given domain and address
func dnsResponse(domain, address string) []byte {
addr := netip.MustParseAddr(address)
b := dnsmessage.NewBuilder(nil, dnsmessage.Header{})
b.EnableCompression()
b.StartAnswers()
switch addr.BitLen() {
case 32:
b.AResource(
dnsmessage.ResourceHeader{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
TTL: 0,
},
dnsmessage.AResource{
A: addr.As4(),
},
)
case 128:
b.AAAAResource(
dnsmessage.ResourceHeader{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeAAAA,
Class: dnsmessage.ClassINET,
TTL: 0,
},
dnsmessage.AAAAResource{
AAAA: addr.As16(),
},
)
default:
panic("invalid address length")
}
return must.Get(b.Finish())
}
func dnsCNAMEResponse(address string, domains ...string) []byte {
addr := netip.MustParseAddr(address)
b := dnsmessage.NewBuilder(nil, dnsmessage.Header{})
b.EnableCompression()
b.StartAnswers()
if len(domains) >= 2 {
for i, domain := range domains[:len(domains)-1] {
b.CNAMEResource(
dnsmessage.ResourceHeader{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeCNAME,
Class: dnsmessage.ClassINET,
TTL: 0,
},
dnsmessage.CNAMEResource{
CNAME: dnsmessage.MustNewName(domains[i+1]),
},
)
}
}
domain := domains[len(domains)-1]
switch addr.BitLen() {
case 32:
b.AResource(
dnsmessage.ResourceHeader{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
TTL: 0,
},
dnsmessage.AResource{
A: addr.As4(),
},
)
case 128:
b.AAAAResource(
dnsmessage.ResourceHeader{
Name: dnsmessage.MustNewName(domain),
Type: dnsmessage.TypeAAAA,
Class: dnsmessage.ClassINET,
TTL: 0,
},
dnsmessage.AAAAResource{
AAAA: addr.As16(),
},
)
default:
panic("invalid address length")
}
return must.Get(b.Finish())
}
func prefixEqual(a, b netip.Prefix) bool {
return a == b
}
func prefixCompare(a, b netip.Prefix) int {
if a.Addr().Compare(b.Addr()) == 0 {
return a.Bits() - b.Bits()
}
return a.Addr().Compare(b.Addr())
}
func prefixes(in ...string) []netip.Prefix {
toRet := make([]netip.Prefix, len(in))
for i, s := range in {
toRet[i] = netip.MustParsePrefix(s)
}
return toRet
}
func TestUpdateRouteRouteRemoval(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
ctx := context.Background()
rc := &appctest.RouteCollector{}
assertRoutes := func(prefix string, routes, removedRoutes []netip.Prefix) {
if !slices.Equal(routes, rc.Routes()) {
t.Fatalf("%s: (shouldStore=%t) routes want %v, got %v", prefix, shouldStore, routes, rc.Routes())
}
if !slices.Equal(removedRoutes, rc.RemovedRoutes()) {
t.Fatalf("%s: (shouldStore=%t) removedRoutes want %v, got %v", prefix, shouldStore, removedRoutes, rc.RemovedRoutes())
}
}
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, rc, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, rc, nil, nil)
}
// nothing has yet been advertised
assertRoutes("appc init", []netip.Prefix{}, []netip.Prefix{})
a.UpdateDomainsAndRoutes([]string{}, prefixes("1.2.3.1/32", "1.2.3.2/32"))
a.Wait(ctx)
// the routes passed to UpdateDomainsAndRoutes have been advertised
assertRoutes("simple update", prefixes("1.2.3.1/32", "1.2.3.2/32"), []netip.Prefix{})
// one route the same, one different
a.UpdateDomainsAndRoutes([]string{}, prefixes("1.2.3.1/32", "1.2.3.3/32"))
a.Wait(ctx)
// old behavior: routes are not removed, resulting routes are both old and new
// (we have dupe 1.2.3.1 routes because the test RouteAdvertiser doesn't have the deduplication
// the real one does)
wantRoutes := prefixes("1.2.3.1/32", "1.2.3.2/32", "1.2.3.1/32", "1.2.3.3/32")
wantRemovedRoutes := []netip.Prefix{}
if shouldStore {
// new behavior: routes are removed, resulting routes are new only
wantRoutes = prefixes("1.2.3.1/32", "1.2.3.1/32", "1.2.3.3/32")
wantRemovedRoutes = prefixes("1.2.3.2/32")
}
assertRoutes("removal", wantRoutes, wantRemovedRoutes)
}
}
func TestUpdateDomainRouteRemoval(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
ctx := context.Background()
rc := &appctest.RouteCollector{}
assertRoutes := func(prefix string, routes, removedRoutes []netip.Prefix) {
if !slices.Equal(routes, rc.Routes()) {
t.Fatalf("%s: (shouldStore=%t) routes want %v, got %v", prefix, shouldStore, routes, rc.Routes())
}
if !slices.Equal(removedRoutes, rc.RemovedRoutes()) {
t.Fatalf("%s: (shouldStore=%t) removedRoutes want %v, got %v", prefix, shouldStore, removedRoutes, rc.RemovedRoutes())
}
}
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, rc, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, rc, nil, nil)
}
assertRoutes("appc init", []netip.Prefix{}, []netip.Prefix{})
a.UpdateDomainsAndRoutes([]string{"a.example.com", "b.example.com"}, []netip.Prefix{})
a.Wait(ctx)
// adding domains doesn't immediately cause any routes to be advertised
assertRoutes("update domains", []netip.Prefix{}, []netip.Prefix{})
a.ObserveDNSResponse(dnsResponse("a.example.com.", "1.2.3.1"))
a.ObserveDNSResponse(dnsResponse("a.example.com.", "1.2.3.2"))
a.ObserveDNSResponse(dnsResponse("b.example.com.", "1.2.3.3"))
a.ObserveDNSResponse(dnsResponse("b.example.com.", "1.2.3.4"))
a.Wait(ctx)
// observing dns responses causes routes to be advertised
assertRoutes("observed dns", prefixes("1.2.3.1/32", "1.2.3.2/32", "1.2.3.3/32", "1.2.3.4/32"), []netip.Prefix{})
a.UpdateDomainsAndRoutes([]string{"a.example.com"}, []netip.Prefix{})
a.Wait(ctx)
// old behavior, routes are not removed
wantRoutes := prefixes("1.2.3.1/32", "1.2.3.2/32", "1.2.3.3/32", "1.2.3.4/32")
wantRemovedRoutes := []netip.Prefix{}
if shouldStore {
// new behavior, routes are removed for b.example.com
wantRoutes = prefixes("1.2.3.1/32", "1.2.3.2/32")
wantRemovedRoutes = prefixes("1.2.3.3/32", "1.2.3.4/32")
}
assertRoutes("removal", wantRoutes, wantRemovedRoutes)
}
}
func TestUpdateWildcardRouteRemoval(t *testing.T) {
for _, shouldStore := range []bool{false, true} {
ctx := context.Background()
rc := &appctest.RouteCollector{}
assertRoutes := func(prefix string, routes, removedRoutes []netip.Prefix) {
if !slices.Equal(routes, rc.Routes()) {
t.Fatalf("%s: (shouldStore=%t) routes want %v, got %v", prefix, shouldStore, routes, rc.Routes())
}
if !slices.Equal(removedRoutes, rc.RemovedRoutes()) {
t.Fatalf("%s: (shouldStore=%t) removedRoutes want %v, got %v", prefix, shouldStore, removedRoutes, rc.RemovedRoutes())
}
}
var a *AppConnector
if shouldStore {
a = NewAppConnector(t.Logf, rc, &RouteInfo{}, fakeStoreRoutes)
} else {
a = NewAppConnector(t.Logf, rc, nil, nil)
}
assertRoutes("appc init", []netip.Prefix{}, []netip.Prefix{})
a.UpdateDomainsAndRoutes([]string{"a.example.com", "*.b.example.com"}, []netip.Prefix{})
a.Wait(ctx)
// adding domains doesn't immediately cause any routes to be advertised
assertRoutes("update domains", []netip.Prefix{}, []netip.Prefix{})
a.ObserveDNSResponse(dnsResponse("a.example.com.", "1.2.3.1"))
a.ObserveDNSResponse(dnsResponse("a.example.com.", "1.2.3.2"))
a.ObserveDNSResponse(dnsResponse("1.b.example.com.", "1.2.3.3"))
a.ObserveDNSResponse(dnsResponse("2.b.example.com.", "1.2.3.4"))
a.Wait(ctx)
// observing dns responses causes routes to be advertised
assertRoutes("observed dns", prefixes("1.2.3.1/32", "1.2.3.2/32", "1.2.3.3/32", "1.2.3.4/32"), []netip.Prefix{})
a.UpdateDomainsAndRoutes([]string{"a.example.com"}, []netip.Prefix{})
a.Wait(ctx)
// old behavior, routes are not removed
wantRoutes := prefixes("1.2.3.1/32", "1.2.3.2/32", "1.2.3.3/32", "1.2.3.4/32")
wantRemovedRoutes := []netip.Prefix{}
if shouldStore {
// new behavior, routes are removed for *.b.example.com
wantRoutes = prefixes("1.2.3.1/32", "1.2.3.2/32")
wantRemovedRoutes = prefixes("1.2.3.3/32", "1.2.3.4/32")
}
assertRoutes("removal", wantRoutes, wantRemovedRoutes)
}
}
func TestRoutesWithout(t *testing.T) {
assert := func(msg string, got, want []netip.Prefix) {
if !slices.Equal(want, got) {
t.Errorf("%s: want %v, got %v", msg, want, got)
}
}
assert("empty routes", routesWithout([]netip.Prefix{}, []netip.Prefix{}), []netip.Prefix{})
assert("a empty", routesWithout([]netip.Prefix{}, prefixes("1.1.1.1/32", "1.1.1.2/32")), []netip.Prefix{})
assert("b empty", routesWithout(prefixes("1.1.1.1/32", "1.1.1.2/32"), []netip.Prefix{}), prefixes("1.1.1.1/32", "1.1.1.2/32"))
assert("no overlap", routesWithout(prefixes("1.1.1.1/32", "1.1.1.2/32"), prefixes("1.1.1.3/32", "1.1.1.4/32")), prefixes("1.1.1.1/32", "1.1.1.2/32"))
assert("a has fewer", routesWithout(prefixes("1.1.1.1/32", "1.1.1.2/32"), prefixes("1.1.1.1/32", "1.1.1.2/32", "1.1.1.3/32", "1.1.1.4/32")), []netip.Prefix{})
assert("a has more", routesWithout(prefixes("1.1.1.1/32", "1.1.1.2/32", "1.1.1.3/32", "1.1.1.4/32"), prefixes("1.1.1.1/32", "1.1.1.3/32")), prefixes("1.1.1.2/32", "1.1.1.4/32"))
}

@ -0,0 +1,49 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package appctest
import (
"net/netip"
"slices"
)
// RouteCollector is a test helper that collects the list of routes advertised
type RouteCollector struct {
routes []netip.Prefix
removedRoutes []netip.Prefix
}
func (rc *RouteCollector) AdvertiseRoute(pfx ...netip.Prefix) error {
rc.routes = append(rc.routes, pfx...)
return nil
}
func (rc *RouteCollector) UnadvertiseRoute(toRemove ...netip.Prefix) error {
routes := rc.routes
rc.routes = rc.routes[:0]
for _, r := range routes {
if !slices.Contains(toRemove, r) {
rc.routes = append(rc.routes, r)
} else {
rc.removedRoutes = append(rc.removedRoutes, r)
}
}
return nil
}
// RemovedRoutes returns the list of routes that were removed.
func (rc *RouteCollector) RemovedRoutes() []netip.Prefix {
return rc.removedRoutes
}
// Routes returns the ordered list of routes that were added, including
// possible duplicates.
func (rc *RouteCollector) Routes() []netip.Prefix {
return rc.routes
}
func (rc *RouteCollector) SetRoutes(routes []netip.Prefix) error {
rc.routes = routes
return nil
}

@ -1,6 +1,5 @@
// Copyright (c) 2019 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// Package atomicfile contains code related to writing to filesystems
// atomically.
@ -9,14 +8,20 @@
package atomicfile // import "tailscale.com/atomicfile"
import (
"fmt"
"os"
"path/filepath"
"runtime"
)
// WriteFile writes data to filename+some suffix, then renames it
// into filename. The perm argument is ignored on Windows.
// WriteFile writes data to filename+some suffix, then renames it into filename.
// The perm argument is ignored on Windows. If the target filename already
// exists but is not a regular file, WriteFile returns an error.
func WriteFile(filename string, data []byte, perm os.FileMode) (err error) {
fi, err := os.Stat(filename)
if err == nil && !fi.Mode().IsRegular() {
return fmt.Errorf("%s already exists and is not a regular file", filename)
}
f, err := os.CreateTemp(filepath.Dir(filename), filepath.Base(filename)+".tmp")
if err != nil {
return err

@ -0,0 +1,47 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build !js && !windows
package atomicfile
import (
"net"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestDoesNotOverwriteIrregularFiles(t *testing.T) {
// Per tailscale/tailscale#7658 as one example, almost any imagined use of
// atomicfile.Write should likely not attempt to overwrite an irregular file
// such as a device node, socket, or named pipe.
const filename = "TestDoesNotOverwriteIrregularFiles"
var path string
// macOS private temp does not allow unix socket creation, but /tmp does.
if runtime.GOOS == "darwin" {
path = filepath.Join("/tmp", filename)
t.Cleanup(func() { os.Remove(path) })
} else {
path = filepath.Join(t.TempDir(), filename)
}
// The least troublesome thing to make that is not a file is a unix socket.
// Making a null device sadly requires root.
l, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
if err != nil {
t.Fatal(err)
}
defer l.Close()
err = WriteFile(path, []byte("hello"), 0644)
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "is not a regular file") {
t.Fatalf("unexpected error: %v", err)
}
}

@ -11,42 +11,25 @@
set -eu
IFS=".$IFS" read -r major minor patch <VERSION.txt
git_hash=$(git rev-parse HEAD)
if ! git diff-index --quiet HEAD; then
git_hash="${git_hash}-dirty"
go="go"
if [ -n "${TS_USE_TOOLCHAIN:-}" ]; then
go="./tool/go"
fi
base_hash=$(git rev-list --max-count=1 HEAD -- VERSION.txt)
change_count=$(git rev-list --count HEAD "^$base_hash")
short_hash=$(echo "$git_hash" | cut -c1-9)
if expr "$minor" : "[0-9]*[13579]$" >/dev/null; then
patch="$change_count"
change_suffix=""
elif [ "$change_count" != "0" ]; then
change_suffix="-$change_count"
else
change_suffix=""
fi
long_suffix="$change_suffix-t$short_hash"
MINOR="$major.$minor"
SHORT="$MINOR.$patch"
LONG="${SHORT}$long_suffix"
GIT_HASH="$git_hash"
eval `CGO_ENABLED=0 GOOS=$($go env GOHOSTOS) GOARCH=$($go env GOHOSTARCH) $go run ./cmd/mkversion`
if [ "$1" = "shellvars" ]; then
cat <<EOF
VERSION_MINOR="$MINOR"
VERSION_SHORT="$SHORT"
VERSION_LONG="$LONG"
VERSION_GIT_HASH="$GIT_HASH"
VERSION_MINOR="$VERSION_MINOR"
VERSION_SHORT="$VERSION_SHORT"
VERSION_LONG="$VERSION_LONG"
VERSION_GIT_HASH="$VERSION_GIT_HASH"
EOF
exit 0
fi
tags=""
ldflags="-X tailscale.com/version.Long=${LONG} -X tailscale.com/version.Short=${SHORT} -X tailscale.com/version.GitCommit=${GIT_HASH}"
ldflags="-X tailscale.com/version.longStamp=${VERSION_LONG} -X tailscale.com/version.shortStamp=${VERSION_SHORT}"
# build_dist.sh arguments must precede go build arguments.
while [ "$#" -gt 1 ]; do
@ -54,7 +37,7 @@ while [ "$#" -gt 1 ]; do
--extra-small)
shift
ldflags="$ldflags -w -s"
tags="${tags:+$tags,}ts_omit_aws,ts_omit_bird,ts_omit_tap"
tags="${tags:+$tags,}ts_omit_aws,ts_omit_bird,ts_omit_tap,ts_omit_kube,ts_omit_completion"
;;
--box)
shift
@ -66,4 +49,4 @@ while [ "$#" -gt 1 ]; do
esac
done
exec ./tool/go build ${tags:+-tags=$tags} -ldflags "$ldflags" "$@"
exec $go build ${tags:+-tags=$tags} -ldflags "$ldflags" "$@"

@ -20,29 +20,75 @@
set -eu
# Use the "go" binary from the "tool" directory (which is github.com/tailscale/go)
export PATH=$PWD/tool:$PATH
export PATH="$PWD"/tool:"$PATH"
eval $(./build_dist.sh shellvars)
eval "$(./build_dist.sh shellvars)"
DEFAULT_TARGET="client"
DEFAULT_TAGS="v${VERSION_SHORT},v${VERSION_MINOR}"
DEFAULT_REPOS="tailscale/tailscale,ghcr.io/tailscale/tailscale"
DEFAULT_BASE="ghcr.io/tailscale/alpine-base:3.16"
DEFAULT_BASE="tailscale/alpine-base:3.18"
PUSH="${PUSH:-false}"
REPOS="${REPOS:-${DEFAULT_REPOS}}"
TARGET="${TARGET:-${DEFAULT_TARGET}}"
TAGS="${TAGS:-${DEFAULT_TAGS}}"
BASE="${BASE:-${DEFAULT_BASE}}"
PLATFORM="${PLATFORM:-}" # default to all platforms
go run github.com/tailscale/mkctr \
--gopaths="\
tailscale.com/cmd/tailscale:/usr/local/bin/tailscale, \
tailscale.com/cmd/tailscaled:/usr/local/bin/tailscaled, \
tailscale.com/cmd/containerboot:/usr/local/bin/containerboot" \
--ldflags="\
-X tailscale.com/version.Long=${VERSION_LONG} \
-X tailscale.com/version.Short=${VERSION_SHORT} \
-X tailscale.com/version.GitCommit=${VERSION_GIT_HASH}" \
--base="${BASE}" \
--tags="${TAGS}" \
--repos="${REPOS}" \
--push="${PUSH}" \
/usr/local/bin/containerboot
case "$TARGET" in
client)
DEFAULT_REPOS="tailscale/tailscale"
REPOS="${REPOS:-${DEFAULT_REPOS}}"
go run github.com/tailscale/mkctr \
--gopaths="\
tailscale.com/cmd/tailscale:/usr/local/bin/tailscale, \
tailscale.com/cmd/tailscaled:/usr/local/bin/tailscaled, \
tailscale.com/cmd/containerboot:/usr/local/bin/containerboot" \
--ldflags="\
-X tailscale.com/version.longStamp=${VERSION_LONG} \
-X tailscale.com/version.shortStamp=${VERSION_SHORT} \
-X tailscale.com/version.gitCommitStamp=${VERSION_GIT_HASH}" \
--base="${BASE}" \
--tags="${TAGS}" \
--gotags="ts_kube" \
--repos="${REPOS}" \
--push="${PUSH}" \
--target="${PLATFORM}" \
/usr/local/bin/containerboot
;;
operator)
DEFAULT_REPOS="tailscale/k8s-operator"
REPOS="${REPOS:-${DEFAULT_REPOS}}"
go run github.com/tailscale/mkctr \
--gopaths="tailscale.com/cmd/k8s-operator:/usr/local/bin/operator" \
--ldflags="\
-X tailscale.com/version.longStamp=${VERSION_LONG} \
-X tailscale.com/version.shortStamp=${VERSION_SHORT} \
-X tailscale.com/version.gitCommitStamp=${VERSION_GIT_HASH}" \
--base="${BASE}" \
--tags="${TAGS}" \
--repos="${REPOS}" \
--push="${PUSH}" \
--target="${PLATFORM}" \
/usr/local/bin/operator
;;
k8s-nameserver)
DEFAULT_REPOS="tailscale/k8s-nameserver"
REPOS="${REPOS:-${DEFAULT_REPOS}}"
go run github.com/tailscale/mkctr \
--gopaths="tailscale.com/cmd/k8s-nameserver:/usr/local/bin/k8s-nameserver" \
--ldflags=" \
-X tailscale.com/version.longStamp=${VERSION_LONG} \
-X tailscale.com/version.shortStamp=${VERSION_SHORT} \
-X tailscale.com/version.gitCommitStamp=${VERSION_GIT_HASH}" \
--base="${BASE}" \
--tags="${TAGS}" \
--repos="${REPOS}" \
--push="${PUSH}" \
--target="${PLATFORM}" \
/usr/local/bin/k8s-nameserver
;;
*)
echo "unknown target: $TARGET"
exit 1
;;
esac

@ -1,6 +1,5 @@
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// Package chirp implements a client to communicate with the BIRD Internet
// Routing Daemon.

@ -1,6 +1,5 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package chirp
import (

@ -1,6 +1,5 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build go1.19
@ -104,7 +103,7 @@ func (c *Client) ACL(ctx context.Context) (acl *ACL, err error) {
// it as a string.
// HuJSON is JSON with a few modifications to make it more human-friendly. The primary
// changes are allowing comments and trailing comments. See the following links for more info:
// https://tailscale.com/kb/1018/acls?q=acl#tailscale-acl-policy-format
// https://tailscale.com/s/acl-format
// https://github.com/tailscale/hujson
func (c *Client) ACLHuJSON(ctx context.Context) (acl *ACLHuJSON, err error) {
// Format return errors to be descriptive.
@ -151,8 +150,9 @@ func (c *Client) ACLHuJSON(ctx context.Context) (acl *ACLHuJSON, err error) {
// ACLTestFailureSummary specifies the JSON format sent to the
// JavaScript client to be rendered in the HTML.
type ACLTestFailureSummary struct {
User string `json:"user"`
Errors []string `json:"errors"`
User string `json:"user,omitempty"`
Errors []string `json:"errors,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
// ACLTestError is ErrResponse but with an extra field to account for ACLTestFailureSummary.
@ -270,6 +270,14 @@ type UserRuleMatch struct {
Users []string `json:"users"`
Ports []string `json:"ports"`
LineNumber int `json:"lineNumber"`
// Postures is a list of posture policies that are
// associated with this match. The rules can be looked
// up in the ACLPreviewResponse parent struct.
// The source of the list is from srcPosture on
// an ACL or Grant rule:
// https://tailscale.com/kb/1288/device-posture#posture-conditions
Postures []string `json:"postures"`
}
// ACLPreviewResponse is the response type of previewACLPostRequest
@ -277,6 +285,12 @@ type ACLPreviewResponse struct {
Matches []UserRuleMatch `json:"matches"` // ACL rules that match the specified user or ipport.
Type string `json:"type"` // The request type: currently only "user" or "ipport".
PreviewFor string `json:"previewFor"` // A specific user or ipport.
// Postures is a map of postures and associated rules that apply
// to this preview.
// For more details about the posture mapping, see:
// https://tailscale.com/kb/1288/device-posture#postures
Postures map[string][]string `json:"postures,omitempty"`
}
// ACLPreview is the response type of PreviewACLForUser, PreviewACLForIPPort, PreviewACLHuJSONForUser, and PreviewACLHuJSONForIPPort
@ -284,6 +298,12 @@ type ACLPreview struct {
Matches []UserRuleMatch `json:"matches"`
User string `json:"user,omitempty"` // Filled if response of PreviewACLForUser or PreviewACLHuJSONForUser
IPPort string `json:"ipport,omitempty"` // Filled if response of PreviewACLForIPPort or PreviewACLHuJSONForIPPort
// Postures is a map of postures and associated rules that apply
// to this preview.
// For more details about the posture mapping, see:
// https://tailscale.com/kb/1288/device-posture#postures
Postures map[string][]string `json:"postures,omitempty"`
}
func (c *Client) previewACLPostRequest(ctx context.Context, body []byte, previewType string, previewFor string) (res *ACLPreviewResponse, err error) {
@ -341,8 +361,9 @@ func (c *Client) PreviewACLForUser(ctx context.Context, acl ACL, user string) (r
}
return &ACLPreview{
Matches: b.Matches,
User: b.PreviewFor,
Matches: b.Matches,
User: b.PreviewFor,
Postures: b.Postures,
}, nil
}
@ -369,8 +390,9 @@ func (c *Client) PreviewACLForIPPort(ctx context.Context, acl ACL, ipport netip.
}
return &ACLPreview{
Matches: b.Matches,
IPPort: b.PreviewFor,
Matches: b.Matches,
IPPort: b.PreviewFor,
Postures: b.Postures,
}, nil
}
@ -394,8 +416,9 @@ func (c *Client) PreviewACLHuJSONForUser(ctx context.Context, acl ACLHuJSON, use
}
return &ACLPreview{
Matches: b.Matches,
User: b.PreviewFor,
Matches: b.Matches,
User: b.PreviewFor,
Postures: b.Postures,
}, nil
}
@ -419,8 +442,9 @@ func (c *Client) PreviewACLHuJSONForIPPort(ctx context.Context, acl ACLHuJSON, i
}
return &ACLPreview{
Matches: b.Matches,
IPPort: b.PreviewFor,
Matches: b.Matches,
IPPort: b.PreviewFor,
Postures: b.Postures,
}, nil
}
@ -437,7 +461,7 @@ func (c *Client) ValidateACLJSON(ctx context.Context, source, dest string) (test
}
}()
tests := []ACLTest{ACLTest{User: source, Allow: []string{dest}}}
tests := []ACLTest{{User: source, Allow: []string{dest}}}
postData, err := json.Marshal(tests)
if err != nil {
return nil, err

@ -1,6 +1,5 @@
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// Package apitype contains types for the Tailscale LocalAPI and control plane API.
package apitype
@ -11,12 +10,14 @@ import "tailscale.com/tailcfg"
const LocalAPIHost = "local-tailscaled.sock"
// WhoIsResponse is the JSON type returned by tailscaled debug server's /whois?ip=$IP handler.
// In successful whois responses, Node and UserProfile are never nil.
type WhoIsResponse struct {
Node *tailcfg.Node
UserProfile *tailcfg.UserProfile
// Caps are extra capabilities that the remote Node has to this node.
Caps []string `json:",omitempty"`
// CapMap is a map of capabilities to their values.
// See tailcfg.PeerCapMap and tailcfg.PeerCapability for details.
CapMap tailcfg.PeerCapMap
}
// FileTarget is a node to which files can be sent, and the PeerAPI
@ -33,3 +34,26 @@ type WaitingFile struct {
Name string
Size int64
}
// SetPushDeviceTokenRequest is the body POSTed to the LocalAPI endpoint /set-device-token.
type SetPushDeviceTokenRequest struct {
// PushDeviceToken is the iOS/macOS APNs device token (and any future Android equivalent).
PushDeviceToken string
}
// ReloadConfigResponse is the response to a LocalAPI reload-config request.
//
// There are three possible outcomes: (false, "") if no config mode in use,
// (true, "") on success, or (false, "error message") on failure.
type ReloadConfigResponse struct {
Reloaded bool // whether the config was reloaded
Err string // any error message
}
// ExitNodeSuggestionResponse is the response to a LocalAPI suggest-exit-node GET request.
// It returns the StableNodeID, name, and location of a suggested exit node for the client making the request.
type ExitNodeSuggestionResponse struct {
ID tailcfg.StableNodeID
Name string
Location tailcfg.LocationView `json:",omitempty"`
}

@ -1,16 +1,16 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package apitype
type DNSConfig struct {
Resolvers []DNSResolver `json:"resolvers"`
FallbackResolvers []DNSResolver `json:"fallbackResolvers"`
Routes map[string][]DNSResolver `json:"routes"`
Domains []string `json:"domains"`
Nameservers []string `json:"nameservers"`
Proxied bool `json:"proxied"`
Resolvers []DNSResolver `json:"resolvers"`
FallbackResolvers []DNSResolver `json:"fallbackResolvers"`
Routes map[string][]DNSResolver `json:"routes"`
Domains []string `json:"domains"`
Nameservers []string `json:"nameservers"`
Proxied bool `json:"proxied"`
TempCorpIssue13969 string `json:"TempCorpIssue13969,omitempty"`
}
type DNSResolver struct {

@ -1,6 +1,5 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build go1.19
@ -13,7 +12,6 @@ import (
"fmt"
"net/http"
"net/url"
"strings"
"tailscale.com/types/opt"
)
@ -45,17 +43,18 @@ type Device struct {
Name string `json:"name"`
Hostname string `json:"hostname"`
ClientVersion string `json:"clientVersion"` // Empty for external devices.
UpdateAvailable bool `json:"updateAvailable"` // Empty for external devices.
OS string `json:"os"`
Created string `json:"created"` // Empty for external devices.
LastSeen string `json:"lastSeen"`
KeyExpiryDisabled bool `json:"keyExpiryDisabled"`
Expires string `json:"expires"`
Authorized bool `json:"authorized"`
IsExternal bool `json:"isExternal"`
MachineKey string `json:"machineKey"` // Empty for external devices.
NodeKey string `json:"nodeKey"`
ClientVersion string `json:"clientVersion"` // Empty for external devices.
UpdateAvailable bool `json:"updateAvailable"` // Empty for external devices.
OS string `json:"os"`
Tags []string `json:"tags"`
Created string `json:"created"` // Empty for external devices.
LastSeen string `json:"lastSeen"`
KeyExpiryDisabled bool `json:"keyExpiryDisabled"`
Expires string `json:"expires"`
Authorized bool `json:"authorized"`
IsExternal bool `json:"isExternal"`
MachineKey string `json:"machineKey"` // Empty for external devices.
NodeKey string `json:"nodeKey"`
// BlocksIncomingConnections is configured via the device's
// Tailscale client preferences. This field is only reported
@ -72,6 +71,17 @@ type Device struct {
AdvertisedRoutes []string `json:"advertisedRoutes"` // Empty for external devices.
ClientConnectivity *ClientConnectivity `json:"clientConnectivity"`
// PostureIdentity contains extra identifiers collected from the device when
// the tailnet has the device posture identification features enabled. If
// Tailscale have attempted to collect this from the device but it has not
// opted in, PostureIdentity will have Disabled=true.
PostureIdentity *DevicePostureIdentity `json:"postureIdentity"`
}
type DevicePostureIdentity struct {
Disabled bool `json:"disabled,omitempty"`
SerialNumbers []string `json:"serialNumbers,omitempty"`
}
// DeviceFieldsOpts determines which fields should be returned in the response.
@ -213,8 +223,20 @@ func (c *Client) DeleteDevice(ctx context.Context, deviceID string) (err error)
// AuthorizeDevice marks a device as authorized.
func (c *Client) AuthorizeDevice(ctx context.Context, deviceID string) error {
return c.SetAuthorized(ctx, deviceID, true)
}
// SetAuthorized marks a device as authorized or not.
func (c *Client) SetAuthorized(ctx context.Context, deviceID string, authorized bool) error {
params := &struct {
Authorized bool `json:"authorized"`
}{Authorized: authorized}
data, err := json.Marshal(params)
if err != nil {
return err
}
path := fmt.Sprintf("%s/api/v2/device/%s/authorized", c.baseURL(), url.PathEscape(deviceID))
req, err := http.NewRequestWithContext(ctx, "POST", path, strings.NewReader(`{"authorized":true}`))
req, err := http.NewRequestWithContext(ctx, "POST", path, bytes.NewBuffer(data))
if err != nil {
return err
}

@ -1,6 +1,5 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build go1.19
@ -64,7 +63,7 @@ func (c *Client) dnsGETRequest(ctx context.Context, endpoint string) ([]byte, er
return b, nil
}
func (c *Client) dnsPOSTRequest(ctx context.Context, endpoint string, postData interface{}) ([]byte, error) {
func (c *Client) dnsPOSTRequest(ctx context.Context, endpoint string, postData any) ([]byte, error) {
path := fmt.Sprintf("%s/api/v2/tailnet/%s/dns/%s", c.baseURL(), c.tailnet, endpoint)
data, err := json.Marshal(&postData)
if err != nil {

@ -1,6 +1,5 @@
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// The servetls program shows how to run an HTTPS server
// using a Tailscale cert via LetsEncrypt.

@ -0,0 +1,166 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package tailscale
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// Key represents a Tailscale API or auth key.
type Key struct {
ID string `json:"id"`
Created time.Time `json:"created"`
Expires time.Time `json:"expires"`
Capabilities KeyCapabilities `json:"capabilities"`
}
// KeyCapabilities are the capabilities of a Key.
type KeyCapabilities struct {
Devices KeyDeviceCapabilities `json:"devices,omitempty"`
}
// KeyDeviceCapabilities are the device-related capabilities of a Key.
type KeyDeviceCapabilities struct {
Create KeyDeviceCreateCapabilities `json:"create"`
}
// KeyDeviceCreateCapabilities are the device creation capabilities of a Key.
type KeyDeviceCreateCapabilities struct {
Reusable bool `json:"reusable"`
Ephemeral bool `json:"ephemeral"`
Preauthorized bool `json:"preauthorized"`
Tags []string `json:"tags,omitempty"`
}
// Keys returns the list of keys for the current user.
func (c *Client) Keys(ctx context.Context) ([]string, error) {
path := fmt.Sprintf("%s/api/v2/tailnet/%s/keys", c.baseURL(), c.tailnet)
req, err := http.NewRequestWithContext(ctx, "GET", path, nil)
if err != nil {
return nil, err
}
b, resp, err := c.sendRequest(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, handleErrorResponse(b, resp)
}
var keys struct {
Keys []*Key `json:"keys"`
}
if err := json.Unmarshal(b, &keys); err != nil {
return nil, err
}
ret := make([]string, 0, len(keys.Keys))
for _, k := range keys.Keys {
ret = append(ret, k.ID)
}
return ret, nil
}
// CreateKey creates a new key for the current user. Currently, only auth keys
// can be created. It returns the secret key itself, which cannot be retrieved again
// later, and the key metadata.
//
// To create a key with a specific expiry, use CreateKeyWithExpiry.
func (c *Client) CreateKey(ctx context.Context, caps KeyCapabilities) (keySecret string, keyMeta *Key, _ error) {
return c.CreateKeyWithExpiry(ctx, caps, 0)
}
// CreateKeyWithExpiry is like CreateKey, but allows specifying a expiration time.
//
// The time is truncated to a whole number of seconds. If zero, that means no expiration.
func (c *Client) CreateKeyWithExpiry(ctx context.Context, caps KeyCapabilities, expiry time.Duration) (keySecret string, keyMeta *Key, _ error) {
// convert expirySeconds to an int64 (seconds)
expirySeconds := int64(expiry.Seconds())
if expirySeconds < 0 {
return "", nil, fmt.Errorf("expiry must be positive")
}
if expirySeconds == 0 && expiry != 0 {
return "", nil, fmt.Errorf("non-zero expiry must be at least one second")
}
keyRequest := struct {
Capabilities KeyCapabilities `json:"capabilities"`
ExpirySeconds int64 `json:"expirySeconds,omitempty"`
}{caps, int64(expirySeconds)}
bs, err := json.Marshal(keyRequest)
if err != nil {
return "", nil, err
}
path := fmt.Sprintf("%s/api/v2/tailnet/%s/keys", c.baseURL(), c.tailnet)
req, err := http.NewRequestWithContext(ctx, "POST", path, bytes.NewReader(bs))
if err != nil {
return "", nil, err
}
b, resp, err := c.sendRequest(req)
if err != nil {
return "", nil, err
}
if resp.StatusCode != http.StatusOK {
return "", nil, handleErrorResponse(b, resp)
}
var key struct {
Key
Secret string `json:"key"`
}
if err := json.Unmarshal(b, &key); err != nil {
return "", nil, err
}
return key.Secret, &key.Key, nil
}
// Key returns the metadata for the given key ID. Currently, capabilities are
// only returned for auth keys, API keys only return general metadata.
func (c *Client) Key(ctx context.Context, id string) (*Key, error) {
path := fmt.Sprintf("%s/api/v2/tailnet/%s/keys/%s", c.baseURL(), c.tailnet, id)
req, err := http.NewRequestWithContext(ctx, "GET", path, nil)
if err != nil {
return nil, err
}
b, resp, err := c.sendRequest(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, handleErrorResponse(b, resp)
}
var key Key
if err := json.Unmarshal(b, &key); err != nil {
return nil, err
}
return &key, nil
}
// DeleteKey deletes the key with the given ID.
func (c *Client) DeleteKey(ctx context.Context, id string) error {
path := fmt.Sprintf("%s/api/v2/tailnet/%s/keys/%s", c.baseURL(), c.tailnet, id)
req, err := http.NewRequestWithContext(ctx, "DELETE", path, nil)
if err != nil {
return err
}
b, resp, err := c.sendRequest(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return handleErrorResponse(b, resp)
}
return nil
}

@ -1,6 +1,5 @@
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build go1.19
@ -8,6 +7,7 @@ package tailscale
import (
"bytes"
"cmp"
"context"
"crypto/tls"
"encoding/json"
@ -28,6 +28,7 @@ import (
"go4.org/mem"
"tailscale.com/client/tailscale/apitype"
"tailscale.com/drive"
"tailscale.com/envknob"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnstate"
@ -37,6 +38,7 @@ import (
"tailscale.com/tailcfg"
"tailscale.com/tka"
"tailscale.com/types/key"
"tailscale.com/types/tkatype"
)
// defaultLocalClient is the default LocalClient when using the legacy
@ -96,12 +98,12 @@ func (lc *LocalClient) defaultDialer(ctx context.Context, network, addr string)
// a TCP server on a random port, find the random port. For HTTP connections,
// we don't send the token. It gets added in an HTTP Basic-Auth header.
if port, _, err := safesocket.LocalTCPPortAndToken(); err == nil {
// We use 127.0.0.1 and not "localhost" (issue 7851).
var d net.Dialer
return d.DialContext(ctx, "tcp", "localhost:"+strconv.Itoa(port))
return d.DialContext(ctx, "tcp", "127.0.0.1:"+strconv.Itoa(port))
}
}
s := safesocket.DefaultConnectionStrategy(lc.socket())
return safesocket.Connect(s)
return safesocket.Connect(lc.socket())
}
// DoLocalRequest makes an HTTP request to the local machine's Tailscale daemon.
@ -114,6 +116,7 @@ func (lc *LocalClient) defaultDialer(ctx context.Context, network, addr string)
//
// DoLocalRequest may mutate the request to add Authorization headers.
func (lc *LocalClient) DoLocalRequest(req *http.Request) (*http.Response, error) {
req.Header.Set("Tailscale-Cap", strconv.Itoa(int(tailcfg.CurrentCapabilityVersion)))
lc.tsClientOnce.Do(func() {
lc.tsClient = &http.Client{
Transport: &http.Transport{
@ -137,6 +140,10 @@ func (lc *LocalClient) doLocalRequestNiceError(req *http.Request) (*http.Respons
all, _ := io.ReadAll(res.Body)
return nil, &AccessDeniedError{errors.New(errorMessageFromBody(all))}
}
if res.StatusCode == http.StatusPreconditionFailed {
all, _ := io.ReadAll(res.Body)
return nil, &PreconditionsFailedError{errors.New(errorMessageFromBody(all))}
}
return res, nil
}
if ue, ok := err.(*url.Error); ok {
@ -167,6 +174,24 @@ func IsAccessDeniedError(err error) bool {
return errors.As(err, &ae)
}
// PreconditionsFailedError is returned when the server responds
// with an HTTP 412 status code.
type PreconditionsFailedError struct {
err error
}
func (e *PreconditionsFailedError) Error() string {
return fmt.Sprintf("Preconditions failed: %v", e.err)
}
func (e *PreconditionsFailedError) Unwrap() error { return e.err }
// IsPreconditionsFailedError reports whether err is or wraps an PreconditionsFailedError.
func IsPreconditionsFailedError(err error) bool {
var ae *PreconditionsFailedError
return errors.As(err, &ae)
}
// bestError returns either err, or if body contains a valid JSON
// object of type errorJSON, its non-empty error body.
func bestError(err error, body []byte) error {
@ -195,27 +220,42 @@ func SetVersionMismatchHandler(f func(clientVer, serverVer string)) {
}
func (lc *LocalClient) send(ctx context.Context, method, path string, wantStatus int, body io.Reader) ([]byte, error) {
slurp, _, err := lc.sendWithHeaders(ctx, method, path, wantStatus, body, nil)
return slurp, err
}
func (lc *LocalClient) sendWithHeaders(
ctx context.Context,
method,
path string,
wantStatus int,
body io.Reader,
h http.Header,
) ([]byte, http.Header, error) {
if jr, ok := body.(jsonReader); ok && jr.err != nil {
return nil, jr.err // fail early if there was a JSON marshaling error
return nil, nil, jr.err // fail early if there was a JSON marshaling error
}
req, err := http.NewRequestWithContext(ctx, method, "http://"+apitype.LocalAPIHost+path, body)
if err != nil {
return nil, err
return nil, nil, err
}
if h != nil {
req.Header = h
}
res, err := lc.doLocalRequestNiceError(req)
if err != nil {
return nil, err
return nil, nil, err
}
defer res.Body.Close()
slurp, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
return nil, nil, err
}
if res.StatusCode != wantStatus {
err = fmt.Errorf("%v: %s", res.Status, bytes.TrimSpace(slurp))
return nil, bestError(err, slurp)
return nil, nil, bestError(err, slurp)
}
return slurp, nil
return slurp, res.Header, nil
}
func (lc *LocalClient) get200(ctx context.Context, path string) ([]byte, error) {
@ -257,6 +297,45 @@ func (lc *LocalClient) DaemonMetrics(ctx context.Context) ([]byte, error) {
return lc.get200(ctx, "/localapi/v0/metrics")
}
// IncrementCounter increments the value of a Tailscale daemon's counter
// metric by the given delta. If the metric has yet to exist, a new counter
// metric is created and initialized to delta.
//
// IncrementCounter does not support gauge metrics or negative delta values.
func (lc *LocalClient) IncrementCounter(ctx context.Context, name string, delta int) error {
type metricUpdate struct {
Name string `json:"name"`
Type string `json:"type"`
Value int `json:"value"` // amount to increment by
}
if delta < 0 {
return errors.New("negative delta not allowed")
}
_, err := lc.send(ctx, "POST", "/localapi/v0/upload-client-metrics", 200, jsonBody([]metricUpdate{{
Name: name,
Type: "counter",
Value: delta,
}}))
return err
}
// TailDaemonLogs returns a stream the Tailscale daemon's logs as they arrive.
// Close the context to stop the stream.
func (lc *LocalClient) TailDaemonLogs(ctx context.Context) (io.Reader, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "http://"+apitype.LocalAPIHost+"/localapi/v0/logtap", nil)
if err != nil {
return nil, err
}
res, err := lc.doLocalRequestNiceError(req)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, errors.New(res.Status)
}
return res.Body, nil
}
// Pprof returns a pprof profile of the Tailscale daemon.
func (lc *LocalClient) Pprof(ctx context.Context, pprofType string, sec int) ([]byte, error) {
var secArg string
@ -350,6 +429,84 @@ func (lc *LocalClient) DebugAction(ctx context.Context, action string) error {
return nil
}
// DebugResultJSON invokes a debug action and returns its result as something JSON-able.
// These are development tools and subject to change or removal over time.
func (lc *LocalClient) DebugResultJSON(ctx context.Context, action string) (any, error) {
body, err := lc.send(ctx, "POST", "/localapi/v0/debug?action="+url.QueryEscape(action), 200, nil)
if err != nil {
return nil, fmt.Errorf("error %w: %s", err, body)
}
var x any
if err := json.Unmarshal(body, &x); err != nil {
return nil, err
}
return x, nil
}
// DebugPortmapOpts contains options for the DebugPortmap command.
type DebugPortmapOpts struct {
// Duration is how long the mapping should be created for. It defaults
// to 5 seconds if not set.
Duration time.Duration
// Type is the kind of portmap to debug. The empty string instructs the
// portmap client to perform all known types. Other valid options are
// "pmp", "pcp", and "upnp".
Type string
// GatewayAddr specifies the gateway address used during portmapping.
// If set, SelfAddr must also be set. If unset, it will be
// autodetected.
GatewayAddr netip.Addr
// SelfAddr specifies the gateway address used during portmapping. If
// set, GatewayAddr must also be set. If unset, it will be
// autodetected.
SelfAddr netip.Addr
// LogHTTP instructs the debug-portmap endpoint to print all HTTP
// requests and responses made to the logs.
LogHTTP bool
}
// DebugPortmap invokes the debug-portmap endpoint, and returns an
// io.ReadCloser that can be used to read the logs that are printed during this
// process.
//
// opts can be nil; if so, default values will be used.
func (lc *LocalClient) DebugPortmap(ctx context.Context, opts *DebugPortmapOpts) (io.ReadCloser, error) {
vals := make(url.Values)
if opts == nil {
opts = &DebugPortmapOpts{}
}
vals.Set("duration", cmp.Or(opts.Duration, 5*time.Second).String())
vals.Set("type", opts.Type)
vals.Set("log_http", strconv.FormatBool(opts.LogHTTP))
if opts.GatewayAddr.IsValid() != opts.SelfAddr.IsValid() {
return nil, fmt.Errorf("both GatewayAddr and SelfAddr must be provided if one is")
} else if opts.GatewayAddr.IsValid() {
vals.Set("gateway_and_self", fmt.Sprintf("%s/%s", opts.GatewayAddr, opts.SelfAddr))
}
req, err := http.NewRequestWithContext(ctx, "GET", "http://"+apitype.LocalAPIHost+"/localapi/v0/debug-portmap?"+vals.Encode(), nil)
if err != nil {
return nil, err
}
res, err := lc.doLocalRequestNiceError(req)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
body, _ := io.ReadAll(res.Body)
res.Body.Close()
return nil, fmt.Errorf("HTTP %s: %s", res.Status, body)
}
return res.Body, nil
}
// SetDevStoreKeyValue set a statestore key/value. It's only meant for development.
// The schema (including when keys are re-read) is not a stable interface.
func (lc *LocalClient) SetDevStoreKeyValue(ctx context.Context, key, value string) error {
@ -522,6 +679,26 @@ func (lc *LocalClient) CheckIPForwarding(ctx context.Context) error {
return nil
}
// CheckUDPGROForwarding asks the local Tailscale daemon whether it looks like
// the machine is optimally configured to forward UDP packets as a subnet router
// or exit node.
func (lc *LocalClient) CheckUDPGROForwarding(ctx context.Context) error {
body, err := lc.get200(ctx, "/localapi/v0/check-udp-gro-forwarding")
if err != nil {
return err
}
var jres struct {
Warning string
}
if err := json.Unmarshal(body, &jres); err != nil {
return fmt.Errorf("invalid JSON from check-udp-gro-forwarding: %w", err)
}
if jres.Warning != "" {
return errors.New(jres.Warning)
}
return nil
}
// CheckPrefs validates the provided preferences, without making any changes.
//
// The CLI uses this before a Start call to fail fast if the preferences won't
@ -760,11 +937,25 @@ func (lc *LocalClient) ExpandSNIName(ctx context.Context, name string) (fqdn str
return "", false
}
// PingOpts contains options for the ping request.
//
// The zero value is valid, which means to use defaults.
type PingOpts struct {
// Size is the length of the ping message in bytes. It's ignored if it's
// smaller than the minimum message size.
//
// For disco pings, it specifies the length of the packet's payload. That
// is, it includes the disco headers and message, but not the IP and UDP
// headers.
Size int
}
// Ping sends a ping of the provided type to the provided IP and waits
// for its response.
func (lc *LocalClient) Ping(ctx context.Context, ip netip.Addr, pingtype tailcfg.PingType) (*ipnstate.PingResult, error) {
// for its response. The opts type specifies additional options.
func (lc *LocalClient) PingWithOpts(ctx context.Context, ip netip.Addr, pingtype tailcfg.PingType, opts PingOpts) (*ipnstate.PingResult, error) {
v := url.Values{}
v.Set("ip", ip.String())
v.Set("size", strconv.Itoa(opts.Size))
v.Set("type", string(pingtype))
body, err := lc.send(ctx, "POST", "/localapi/v0/ping?"+v.Encode(), 200, nil)
if err != nil {
@ -773,6 +964,12 @@ func (lc *LocalClient) Ping(ctx context.Context, ip netip.Addr, pingtype tailcfg
return decodeJSON[*ipnstate.PingResult](body)
}
// Ping sends a ping of the provided type to the provided IP and waits
// for its response.
func (lc *LocalClient) Ping(ctx context.Context, ip netip.Addr, pingtype tailcfg.PingType) (*ipnstate.PingResult, error) {
return lc.PingWithOpts(ctx, ip, pingtype, PingOpts{})
}
// NetworkLockStatus fetches information about the tailnet key authority, if one is configured.
func (lc *LocalClient) NetworkLockStatus(ctx context.Context) (*ipnstate.NetworkLockStatus, error) {
body, err := lc.send(ctx, "GET", "/localapi/v0/tka/status", 200, nil)
@ -804,8 +1001,32 @@ func (lc *LocalClient) NetworkLockInit(ctx context.Context, keys []tka.Key, disa
return decodeJSON[*ipnstate.NetworkLockStatus](body)
}
// NetworkLockWrapPreauthKey wraps a pre-auth key with information to
// enable unattended bringup in the locked tailnet.
func (lc *LocalClient) NetworkLockWrapPreauthKey(ctx context.Context, preauthKey string, tkaKey key.NLPrivate) (string, error) {
encodedPrivate, err := tkaKey.MarshalText()
if err != nil {
return "", err
}
var b bytes.Buffer
type wrapRequest struct {
TSKey string
TKAKey string // key.NLPrivate.MarshalText
}
if err := json.NewEncoder(&b).Encode(wrapRequest{TSKey: preauthKey, TKAKey: string(encodedPrivate)}); err != nil {
return "", err
}
body, err := lc.send(ctx, "POST", "/localapi/v0/tka/wrap-preauth-key", 200, &b)
if err != nil {
return "", fmt.Errorf("error: %w", err)
}
return string(body), nil
}
// NetworkLockModify adds and/or removes key(s) to the tailnet key authority.
func (lc *LocalClient) NetworkLockModify(ctx context.Context, addKeys, removeKeys []tka.Key) (*ipnstate.NetworkLockStatus, error) {
func (lc *LocalClient) NetworkLockModify(ctx context.Context, addKeys, removeKeys []tka.Key) error {
var b bytes.Buffer
type modifyRequest struct {
AddKeys []tka.Key
@ -813,14 +1034,13 @@ func (lc *LocalClient) NetworkLockModify(ctx context.Context, addKeys, removeKey
}
if err := json.NewEncoder(&b).Encode(modifyRequest{AddKeys: addKeys, RemoveKeys: removeKeys}); err != nil {
return nil, err
return err
}
body, err := lc.send(ctx, "POST", "/localapi/v0/tka/modify", 200, &b)
if err != nil {
return nil, fmt.Errorf("error: %w", err)
if _, err := lc.send(ctx, "POST", "/localapi/v0/tka/modify", 204, &b); err != nil {
return fmt.Errorf("error: %w", err)
}
return decodeJSON[*ipnstate.NetworkLockStatus](body)
return nil
}
// NetworkLockSign signs the specified node-key and transmits that signature to the control plane.
@ -842,6 +1062,15 @@ func (lc *LocalClient) NetworkLockSign(ctx context.Context, nodeKey key.NodePubl
return nil
}
// NetworkLockAffectedSigs returns all signatures signed by the specified keyID.
func (lc *LocalClient) NetworkLockAffectedSigs(ctx context.Context, keyID tkatype.KeyID) ([]tkatype.MarshaledSignature, error) {
body, err := lc.send(ctx, "POST", "/localapi/v0/tka/affected-sigs", 200, bytes.NewReader(keyID))
if err != nil {
return nil, fmt.Errorf("error: %w", err)
}
return decodeJSON[[]tkatype.MarshaledSignature](body)
}
// NetworkLockLog returns up to maxEntries number of changes to network-lock state.
func (lc *LocalClient) NetworkLockLog(ctx context.Context, maxEntries int) ([]ipnstate.NetworkLockUpdate, error) {
v := url.Values{}
@ -867,11 +1096,65 @@ func (lc *LocalClient) NetworkLockForceLocalDisable(ctx context.Context) error {
return nil
}
// NetworkLockVerifySigningDeeplink verifies the network lock deeplink contained
// in url and returns information extracted from it.
func (lc *LocalClient) NetworkLockVerifySigningDeeplink(ctx context.Context, url string) (*tka.DeeplinkValidationResult, error) {
vr := struct {
URL string
}{url}
body, err := lc.send(ctx, "POST", "/localapi/v0/tka/verify-deeplink", 200, jsonBody(vr))
if err != nil {
return nil, fmt.Errorf("sending verify-deeplink: %w", err)
}
return decodeJSON[*tka.DeeplinkValidationResult](body)
}
// NetworkLockGenRecoveryAUM generates an AUM for recovering from a tailnet-lock key compromise.
func (lc *LocalClient) NetworkLockGenRecoveryAUM(ctx context.Context, removeKeys []tkatype.KeyID, forkFrom tka.AUMHash) ([]byte, error) {
vr := struct {
Keys []tkatype.KeyID
ForkFrom string
}{removeKeys, forkFrom.String()}
body, err := lc.send(ctx, "POST", "/localapi/v0/tka/generate-recovery-aum", 200, jsonBody(vr))
if err != nil {
return nil, fmt.Errorf("sending generate-recovery-aum: %w", err)
}
return body, nil
}
// NetworkLockCosignRecoveryAUM co-signs a recovery AUM using the node's tailnet lock key.
func (lc *LocalClient) NetworkLockCosignRecoveryAUM(ctx context.Context, aum tka.AUM) ([]byte, error) {
r := bytes.NewReader(aum.Serialize())
body, err := lc.send(ctx, "POST", "/localapi/v0/tka/cosign-recovery-aum", 200, r)
if err != nil {
return nil, fmt.Errorf("sending cosign-recovery-aum: %w", err)
}
return body, nil
}
// NetworkLockSubmitRecoveryAUM submits a recovery AUM to the control plane.
func (lc *LocalClient) NetworkLockSubmitRecoveryAUM(ctx context.Context, aum tka.AUM) error {
r := bytes.NewReader(aum.Serialize())
_, err := lc.send(ctx, "POST", "/localapi/v0/tka/submit-recovery-aum", 200, r)
if err != nil {
return fmt.Errorf("sending cosign-recovery-aum: %w", err)
}
return nil
}
// SetServeConfig sets or replaces the serving settings.
// If config is nil, settings are cleared and serving is disabled.
func (lc *LocalClient) SetServeConfig(ctx context.Context, config *ipn.ServeConfig) error {
_, err := lc.send(ctx, "POST", "/localapi/v0/serve-config", 200, jsonBody(config))
h := make(http.Header)
if config != nil {
h.Set("If-Match", config.ETag)
}
_, _, err := lc.sendWithHeaders(ctx, "POST", "/localapi/v0/serve-config", 200, jsonBody(config), h)
if err != nil {
return fmt.Errorf("sending serve config: %w", err)
}
@ -890,11 +1173,19 @@ func (lc *LocalClient) NetworkLockDisable(ctx context.Context, secret []byte) er
//
// If the serve config is empty, it returns (nil, nil).
func (lc *LocalClient) GetServeConfig(ctx context.Context) (*ipn.ServeConfig, error) {
body, err := lc.send(ctx, "GET", "/localapi/v0/serve-config", 200, nil)
body, h, err := lc.sendWithHeaders(ctx, "GET", "/localapi/v0/serve-config", 200, nil, nil)
if err != nil {
return nil, fmt.Errorf("getting serve config: %w", err)
}
return getServeConfigFromJSON(body)
sc, err := getServeConfigFromJSON(body)
if err != nil {
return nil, err
}
if sc == nil {
sc = new(ipn.ServeConfig)
}
sc.ETag = h.Get("Etag")
return sc, nil
}
func getServeConfigFromJSON(body []byte) (sc *ipn.ServeConfig, err error) {
@ -973,6 +1264,22 @@ func (lc *LocalClient) ProfileStatus(ctx context.Context) (current ipn.LoginProf
return current, all, err
}
// ReloadConfig reloads the config file, if possible.
func (lc *LocalClient) ReloadConfig(ctx context.Context) (ok bool, err error) {
body, err := lc.send(ctx, "POST", "/localapi/v0/reload-config", 200, nil)
if err != nil {
return
}
res, err := decodeJSON[apitype.ReloadConfigResponse](body)
if err != nil {
return
}
if res.Err != "" {
return false, errors.New(res.Err)
}
return res.Reloaded, nil
}
// SwitchToEmptyProfile creates and switches to a new unnamed profile. The new
// profile is not assigned an ID until it is persisted after a successful login.
// In order to login to the new profile, the user must call LoginInteractive.
@ -995,6 +1302,27 @@ func (lc *LocalClient) DeleteProfile(ctx context.Context, profile ipn.ProfileID)
return err
}
// QueryFeature makes a request for instructions on how to enable
// a feature, such as Funnel, for the node's tailnet. If relevant,
// this includes a control server URL the user can visit to enable
// the feature.
//
// If you are looking to use QueryFeature, you'll likely want to
// use cli.enableFeatureInteractive instead, which handles the logic
// of wraping QueryFeature and translating its response into an
// interactive flow for the user, including using the IPN notify bus
// to block until the feature has been enabled.
//
// 2023-08-09: Valid feature values are "serve" and "funnel".
func (lc *LocalClient) QueryFeature(ctx context.Context, feature string) (*tailcfg.QueryFeatureResponse, error) {
v := url.Values{"feature": {feature}}
body, err := lc.send(ctx, "POST", "/localapi/v0/query-feature?"+v.Encode(), 200, nil)
if err != nil {
return nil, fmt.Errorf("error %w: %s", err, body)
}
return decodeJSON[*tailcfg.QueryFeatureResponse](body)
}
func (lc *LocalClient) DebugDERPRegion(ctx context.Context, regionIDOrCode string) (*ipnstate.DebugDERPRegionReport, error) {
v := url.Values{"region": {regionIDOrCode}}
body, err := lc.send(ctx, "POST", "/localapi/v0/debug-derp-region?"+v.Encode(), 200, nil)
@ -1004,6 +1332,44 @@ func (lc *LocalClient) DebugDERPRegion(ctx context.Context, regionIDOrCode strin
return decodeJSON[*ipnstate.DebugDERPRegionReport](body)
}
// DebugPacketFilterRules returns the packet filter rules for the current device.
func (lc *LocalClient) DebugPacketFilterRules(ctx context.Context) ([]tailcfg.FilterRule, error) {
body, err := lc.send(ctx, "POST", "/localapi/v0/debug-packet-filter-rules", 200, nil)
if err != nil {
return nil, fmt.Errorf("error %w: %s", err, body)
}
return decodeJSON[[]tailcfg.FilterRule](body)
}
// DebugSetExpireIn marks the current node key to expire in d.
//
// This is meant primarily for debug and testing.
func (lc *LocalClient) DebugSetExpireIn(ctx context.Context, d time.Duration) error {
v := url.Values{"expiry": {fmt.Sprint(time.Now().Add(d).Unix())}}
_, err := lc.send(ctx, "POST", "/localapi/v0/set-expiry-sooner?"+v.Encode(), 200, nil)
return err
}
// StreamDebugCapture streams a pcap-formatted packet capture.
//
// The provided context does not determine the lifetime of the
// returned io.ReadCloser.
func (lc *LocalClient) StreamDebugCapture(ctx context.Context) (io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, "POST", "http://"+apitype.LocalAPIHost+"/localapi/v0/debug-capture", nil)
if err != nil {
return nil, err
}
res, err := lc.doLocalRequestNiceError(req)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
res.Body.Close()
return nil, errors.New(res.Status)
}
return res.Body, nil
}
// WatchIPNBus subscribes to the IPN notification bus. It returns a watcher
// once the bus is connected successfully.
//
@ -1037,6 +1403,81 @@ func (lc *LocalClient) WatchIPNBus(ctx context.Context, mask ipn.NotifyWatchOpt)
}, nil
}
// CheckUpdate returns a tailcfg.ClientVersion indicating whether or not an update is available
// to be installed via the LocalAPI. In case the LocalAPI can't install updates, it returns a
// ClientVersion that says that we are up to date.
func (lc *LocalClient) CheckUpdate(ctx context.Context) (*tailcfg.ClientVersion, error) {
body, err := lc.get200(ctx, "/localapi/v0/update/check")
if err != nil {
return nil, err
}
cv, err := decodeJSON[tailcfg.ClientVersion](body)
if err != nil {
return nil, err
}
return &cv, nil
}
// SetUseExitNode toggles the use of an exit node on or off.
// To turn it on, there must have been a previously used exit node.
// The most previously used one is reused.
// This is a convenience method for GUIs. To select an actual one, update the prefs.
func (lc *LocalClient) SetUseExitNode(ctx context.Context, on bool) error {
_, err := lc.send(ctx, "POST", "/localapi/v0/set-use-exit-node-enabled?enabled="+strconv.FormatBool(on), http.StatusOK, nil)
return err
}
// DriveSetServerAddr instructs Taildrive to use the server at addr to access
// the filesystem. This is used on platforms like Windows and MacOS to let
// Taildrive know to use the file server running in the GUI app.
func (lc *LocalClient) DriveSetServerAddr(ctx context.Context, addr string) error {
_, err := lc.send(ctx, "PUT", "/localapi/v0/drive/fileserver-address", http.StatusCreated, strings.NewReader(addr))
return err
}
// DriveShareSet adds or updates the given share in the list of shares that
// Taildrive will serve to remote nodes. If a share with the same name already
// exists, the existing share is replaced/updated.
func (lc *LocalClient) DriveShareSet(ctx context.Context, share *drive.Share) error {
_, err := lc.send(ctx, "PUT", "/localapi/v0/drive/shares", http.StatusCreated, jsonBody(share))
return err
}
// DriveShareRemove removes the share with the given name from the list of
// shares that Taildrive will serve to remote nodes.
func (lc *LocalClient) DriveShareRemove(ctx context.Context, name string) error {
_, err := lc.send(
ctx,
"DELETE",
"/localapi/v0/drive/shares",
http.StatusNoContent,
strings.NewReader(name))
return err
}
// DriveShareRename renames the share from old to new name.
func (lc *LocalClient) DriveShareRename(ctx context.Context, oldName, newName string) error {
_, err := lc.send(
ctx,
"POST",
"/localapi/v0/drive/shares",
http.StatusNoContent,
jsonBody([2]string{oldName, newName}))
return err
}
// DriveShareList returns the list of shares that drive is currently serving
// to remote nodes.
func (lc *LocalClient) DriveShareList(ctx context.Context) ([]*drive.Share, error) {
result, err := lc.get200(ctx, "/localapi/v0/drive/shares")
if err != nil {
return nil, err
}
var shares []*drive.Share
err = json.Unmarshal(result, &shares)
return shares, err
}
// IPNBusWatcher is an active subscription (watch) of the local tailscaled IPN bus.
// It's returned by LocalClient.WatchIPNBus.
//
@ -1073,3 +1514,12 @@ func (w *IPNBusWatcher) Next() (ipn.Notify, error) {
}
return n, nil
}
// SuggestExitNode requests an exit node suggestion and returns the exit node's details.
func (lc *LocalClient) SuggestExitNode(ctx context.Context) (apitype.ExitNodeSuggestionResponse, error) {
body, err := lc.get200(ctx, "/localapi/v0/suggest-exit-node")
if err != nil {
return apitype.ExitNodeSuggestionResponse{}, err
}
return decodeJSON[apitype.ExitNodeSuggestionResponse](body)
}

@ -1,12 +1,15 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build go1.19
package tailscale
import "testing"
import (
"testing"
"tailscale.com/tstest/deptest"
)
func TestGetServeConfigFromJSON(t *testing.T) {
sc, err := getServeConfigFromJSON([]byte("null"))
@ -26,3 +29,15 @@ func TestGetServeConfigFromJSON(t *testing.T) {
t.Errorf("want non-nil TCP for object")
}
}
func TestDeps(t *testing.T) {
deptest.DepChecker{
BadDeps: map[string]string{
// Make sure we don't again accidentally bring in a dependency on
// drive or its transitive dependencies
"testing": "do not use testing package in production code",
"tailscale.com/drive/driveimpl": "https://github.com/tailscale/tailscale/pull/10631",
"github.com/studio-b12/gowebdav": "https://github.com/tailscale/tailscale/pull/10631",
},
}.Check(t)
}

@ -1,11 +1,10 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build !go1.19
//go:build !go1.21
package tailscale
func init() {
you_need_Go_1_19_to_compile_Tailscale()
you_need_Go_1_21_to_compile_Tailscale()
}

@ -1,6 +1,5 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build go1.19

@ -1,6 +1,5 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build go1.19
@ -11,6 +10,8 @@ import (
"fmt"
"net/http"
"net/url"
"tailscale.com/util/httpm"
)
// TailnetDeleteRequest handles sending a DELETE request for a tailnet to control.
@ -22,7 +23,7 @@ func (c *Client) TailnetDeleteRequest(ctx context.Context, tailnetID string) (er
}()
path := fmt.Sprintf("%s/api/v2/tailnet/%s", c.baseURL(), url.PathEscape(string(tailnetID)))
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, path, nil)
req, err := http.NewRequestWithContext(ctx, httpm.DELETE, path, nil)
if err != nil {
return err
}

@ -1,6 +1,5 @@
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build go1.19

@ -0,0 +1,131 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package web
import (
"io"
"io/fs"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
prebuilt "github.com/tailscale/web-client-prebuilt"
)
var start = time.Now()
func assetsHandler(devMode bool) (_ http.Handler, cleanup func()) {
if devMode {
// When in dev mode, proxy asset requests to the Vite dev server.
cleanup := startDevServer()
return devServerProxy(), cleanup
}
fsys := prebuilt.FS()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/")
f, err := openPrecompressedFile(w, r, path, fsys)
if err != nil {
// Rewrite request to just fetch index.html and let
// the frontend router handle it.
r = r.Clone(r.Context())
path = "index.html"
f, err = openPrecompressedFile(w, r, path, fsys)
}
if f == nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
defer f.Close()
// fs.File does not claim to implement Seeker, but in practice it does.
fSeeker, ok := f.(io.ReadSeeker)
if !ok {
http.Error(w, "Not seekable", http.StatusInternalServerError)
return
}
if strings.HasPrefix(path, "assets/") {
// Aggressively cache static assets, since we cache-bust our assets with
// hashed filenames.
w.Header().Set("Cache-Control", "public, max-age=31535996")
w.Header().Set("Vary", "Accept-Encoding")
}
http.ServeContent(w, r, path, start, fSeeker)
}), nil
}
func openPrecompressedFile(w http.ResponseWriter, r *http.Request, path string, fs fs.FS) (fs.File, error) {
if f, err := fs.Open(path + ".gz"); err == nil {
w.Header().Set("Content-Encoding", "gzip")
return f, nil
}
return fs.Open(path) // fallback
}
// startDevServer starts the JS dev server that does on-demand rebuilding
// and serving of web client JS and CSS resources.
func startDevServer() (cleanup func()) {
root := gitRootDir()
webClientPath := filepath.Join(root, "client", "web")
yarn := filepath.Join(root, "tool", "yarn")
node := filepath.Join(root, "tool", "node")
vite := filepath.Join(webClientPath, "node_modules", ".bin", "vite")
log.Printf("installing JavaScript deps using %s...", yarn)
out, err := exec.Command(yarn, "--non-interactive", "-s", "--cwd", webClientPath, "install").CombinedOutput()
if err != nil {
log.Fatalf("error running tailscale web's yarn install: %v, %s", err, out)
}
log.Printf("starting JavaScript dev server...")
cmd := exec.Command(node, vite)
cmd.Dir = webClientPath
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
log.Fatalf("Starting JS dev server: %v", err)
}
log.Printf("JavaScript dev server running as pid %d", cmd.Process.Pid)
return func() {
cmd.Process.Signal(os.Interrupt)
err := cmd.Wait()
log.Printf("JavaScript dev server exited: %v", err)
}
}
// devServerProxy returns a reverse proxy to the vite dev server.
func devServerProxy() *httputil.ReverseProxy {
// We use Vite to develop on the web client.
// Vite starts up its own local server for development,
// which we proxy requests to from Server.ServeHTTP.
// Here we set up the proxy to Vite's server.
handleErr := func(w http.ResponseWriter, r *http.Request, err error) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusBadGateway)
w.Write([]byte("The web client development server isn't running. " +
"Run `./tool/yarn --cwd client/web start` from " +
"the repo root to start the development server."))
w.Write([]byte("\n\nError: " + err.Error()))
}
viteTarget, _ := url.Parse("http://127.0.0.1:4000")
devProxy := httputil.NewSingleHostReverseProxy(viteTarget)
devProxy.ErrorHandler = handleErr
return devProxy
}
func gitRootDir() string {
top, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
if err != nil {
log.Fatalf("failed to find git top level (not in corp git?): %v", err)
}
return strings.TrimSpace(string(top))
}

@ -0,0 +1,339 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package web
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strings"
"time"
"tailscale.com/client/tailscale/apitype"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tailcfg"
)
const (
sessionCookieName = "TS-Web-Session"
sessionCookieExpiry = time.Hour * 24 * 30 // 30 days
)
// browserSession holds data about a user's browser session
// on the full management web client.
type browserSession struct {
// ID is the unique identifier for the session.
// It is passed in the user's "TS-Web-Session" browser cookie.
ID string
SrcNode tailcfg.NodeID
SrcUser tailcfg.UserID
AuthID string // from tailcfg.WebClientAuthResponse
AuthURL string // from tailcfg.WebClientAuthResponse
Created time.Time
Authenticated bool
}
// isAuthorized reports true if the given session is authorized
// to be used by its associated user to access the full management
// web client.
//
// isAuthorized is true only when s.Authenticated is true (i.e.
// the user has authenticated the session) and the session is not
// expired.
// 2023-10-05: Sessions expire by default 30 days after creation.
func (s *browserSession) isAuthorized(now time.Time) bool {
switch {
case s == nil:
return false
case !s.Authenticated:
return false // awaiting auth
case s.isExpired(now):
return false // expired
}
return true
}
// isExpired reports true if s is expired.
// 2023-10-05: Sessions expire by default 30 days after creation.
func (s *browserSession) isExpired(now time.Time) bool {
return !s.Created.IsZero() && now.After(s.expires())
}
// expires reports when the given session expires.
func (s *browserSession) expires() time.Time {
return s.Created.Add(sessionCookieExpiry)
}
var (
errNoSession = errors.New("no-browser-session")
errNotUsingTailscale = errors.New("not-using-tailscale")
errTaggedRemoteSource = errors.New("tagged-remote-source")
errTaggedLocalSource = errors.New("tagged-local-source")
errNotOwner = errors.New("not-owner")
)
// getSession retrieves the browser session associated with the request,
// if one exists.
//
// An error is returned in any of the following cases:
//
// - (errNotUsingTailscale) The request was not made over tailscale.
//
// - (errNoSession) The request does not have a session.
//
// - (errTaggedRemoteSource) The source is remote (another node) and tagged.
// Users must use their own user-owned devices to manage other nodes'
// web clients.
//
// - (errTaggedLocalSource) The source is local (the same node) and tagged.
// Tagged nodes can only be remotely managed, allowing ACLs to dictate
// access to web clients.
//
// - (errNotOwner) The source is not the owner of this client (if the
// client is user-owned). Only the owner is allowed to manage the
// node via the web client.
//
// If no error is returned, the browserSession is always non-nil.
// getTailscaleBrowserSession does not check whether the session has been
// authorized by the user. Callers can use browserSession.isAuthorized.
//
// The WhoIsResponse is always populated, with a non-nil Node and UserProfile,
// unless getTailscaleBrowserSession reports errNotUsingTailscale.
func (s *Server) getSession(r *http.Request) (*browserSession, *apitype.WhoIsResponse, *ipnstate.Status, error) {
whoIs, whoIsErr := s.lc.WhoIs(r.Context(), r.RemoteAddr)
status, statusErr := s.lc.StatusWithoutPeers(r.Context())
switch {
case whoIsErr != nil:
return nil, nil, status, errNotUsingTailscale
case statusErr != nil:
return nil, whoIs, nil, statusErr
case status.Self == nil:
return nil, whoIs, status, errors.New("missing self node in tailscale status")
case whoIs.Node.IsTagged() && whoIs.Node.StableID == status.Self.ID:
return nil, whoIs, status, errTaggedLocalSource
case whoIs.Node.IsTagged():
return nil, whoIs, status, errTaggedRemoteSource
case !status.Self.IsTagged() && status.Self.UserID != whoIs.UserProfile.ID:
return nil, whoIs, status, errNotOwner
}
srcNode := whoIs.Node.ID
srcUser := whoIs.UserProfile.ID
cookie, err := r.Cookie(sessionCookieName)
if errors.Is(err, http.ErrNoCookie) {
return nil, whoIs, status, errNoSession
} else if err != nil {
return nil, whoIs, status, err
}
v, ok := s.browserSessions.Load(cookie.Value)
if !ok {
return nil, whoIs, status, errNoSession
}
session := v.(*browserSession)
if session.SrcNode != srcNode || session.SrcUser != srcUser {
// In this case the browser cookie is associated with another tailscale node.
// Maybe the source browser's machine was logged out and then back in as a different node.
// Return errNoSession because there is no session for this user.
return nil, whoIs, status, errNoSession
} else if session.isExpired(s.timeNow()) {
// Session expired, remove from session map and return errNoSession.
s.browserSessions.Delete(session.ID)
return nil, whoIs, status, errNoSession
}
return session, whoIs, status, nil
}
// newSession creates a new session associated with the given source user/node,
// and stores it back to the session cache. Creating of a new session includes
// generating a new auth URL from the control server.
func (s *Server) newSession(ctx context.Context, src *apitype.WhoIsResponse) (*browserSession, error) {
sid, err := s.newSessionID()
if err != nil {
return nil, err
}
session := &browserSession{
ID: sid,
SrcNode: src.Node.ID,
SrcUser: src.UserProfile.ID,
Created: s.timeNow(),
}
if s.controlSupportsCheckMode(ctx) {
// control supports check mode, so get a new auth URL and return.
a, err := s.newAuthURL(ctx, src.Node.ID)
if err != nil {
return nil, err
}
session.AuthID = a.ID
session.AuthURL = a.URL
} else {
// control does not support check mode, so there is no additional auth we can do.
session.Authenticated = true
}
s.browserSessions.Store(sid, session)
return session, nil
}
// controlSupportsCheckMode returns whether the current control server supports web client check mode, to verify a user's identity.
// We assume that only "tailscale.com" control servers support check mode.
// This allows the web client to be used with non-standard control servers.
// If an error occurs getting the control URL, this method returns true to fail closed.
//
// TODO(juanfont/headscale#1623): adjust or remove this when headscale supports check mode.
func (s *Server) controlSupportsCheckMode(ctx context.Context) bool {
prefs, err := s.lc.GetPrefs(ctx)
if err != nil {
return true
}
controlURL, err := url.Parse(prefs.ControlURLOrDefault())
if err != nil {
return true
}
return strings.HasSuffix(controlURL.Host, ".tailscale.com")
}
// awaitUserAuth blocks until the given session auth has been completed
// by the user on the control server, then updates the session cache upon
// completion. An error is returned if control auth failed for any reason.
func (s *Server) awaitUserAuth(ctx context.Context, session *browserSession) error {
if session.isAuthorized(s.timeNow()) {
return nil // already authorized
}
a, err := s.waitAuthURL(ctx, session.AuthID, session.SrcNode)
if err != nil {
// Clean up the session. Doing this on any error from control
// server to avoid the user getting stuck with a bad session
// cookie.
s.browserSessions.Delete(session.ID)
return err
}
if a.Complete {
session.Authenticated = a.Complete
s.browserSessions.Store(session.ID, session)
}
return nil
}
func (s *Server) newSessionID() (string, error) {
raw := make([]byte, 16)
for range 5 {
if _, err := rand.Read(raw); err != nil {
return "", err
}
cookie := "ts-web-" + base64.RawURLEncoding.EncodeToString(raw)
if _, ok := s.browserSessions.Load(cookie); !ok {
return cookie, nil
}
}
return "", errors.New("too many collisions generating new session; please refresh page")
}
// peerCapabilities holds information about what a source
// peer is allowed to edit via the web UI.
//
// map value is true if the peer can edit the given feature.
// Only capFeatures included in validCaps will be included.
type peerCapabilities map[capFeature]bool
// canEdit is true if the peerCapabilities grant edit access
// to the given feature.
func (p peerCapabilities) canEdit(feature capFeature) bool {
if p == nil {
return false
}
if p[capFeatureAll] {
return true
}
return p[feature]
}
// isEmpty is true if p is either nil or has no capabilities
// with value true.
func (p peerCapabilities) isEmpty() bool {
if p == nil {
return true
}
for _, v := range p {
if v == true {
return false
}
}
return true
}
type capFeature string
const (
// The following values should not be edited.
// New caps can be added, but existing ones should not be changed,
// as these exact values are used by users in tailnet policy files.
//
// IMPORTANT: When adding a new cap, also update validCaps slice below.
capFeatureAll capFeature = "*" // grants peer management of all features
capFeatureSSH capFeature = "ssh" // grants peer SSH server management
capFeatureSubnets capFeature = "subnets" // grants peer subnet routes management
capFeatureExitNodes capFeature = "exitnodes" // grants peer ability to advertise-as and use exit nodes
capFeatureAccount capFeature = "account" // grants peer ability to turn on auto updates and log out of node
)
// validCaps contains the list of valid capabilities used in the web client.
// Any capabilities included in a peer's grants that do not fall into this
// list will be ignored.
var validCaps []capFeature = []capFeature{
capFeatureAll,
capFeatureSSH,
capFeatureSubnets,
capFeatureExitNodes,
capFeatureAccount,
}
type capRule struct {
CanEdit []string `json:"canEdit,omitempty"` // list of features peer is allowed to edit
}
// toPeerCapabilities parses out the web ui capabilities from the
// given whois response.
func toPeerCapabilities(status *ipnstate.Status, whois *apitype.WhoIsResponse) (peerCapabilities, error) {
if whois == nil || status == nil {
return peerCapabilities{}, nil
}
if whois.Node.IsTagged() {
// We don't allow management *from* tagged nodes, so ignore caps.
// The web client auth flow relies on having a true user identity
// that can be verified through login.
return peerCapabilities{}, nil
}
if !status.Self.IsTagged() {
// User owned nodes are only ever manageable by the owner.
if status.Self.UserID != whois.UserProfile.ID {
return peerCapabilities{}, nil
} else {
return peerCapabilities{capFeatureAll: true}, nil // owner can edit all features
}
}
// For tagged nodes, we actually look at the granted capabilities.
caps := peerCapabilities{}
rules, err := tailcfg.UnmarshalCapJSON[capRule](whois.CapMap, tailcfg.PeerCapabilityWebUI)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal capability: %v", err)
}
for _, c := range rules {
for _, f := range c.CanEdit {
cap := capFeature(strings.ToLower(f))
if slices.Contains(validCaps, cap) {
caps[cap] = true
}
}
}
return caps, nil
}

@ -0,0 +1,29 @@
<!doctype html>
<html class="bg-gray-50">
<head>
<title>Tailscale</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQflAx4QGA4EvmzDAAAA30lEQVRIx2NgGAWMCKa8JKM4A8Ovt88ekyLCDGOoyDBJMjExMbFy8zF8/EKsCAMDE8yAPyIwFps48SJIBpAL4AZwvoSx/r0lXgQpDN58EWL5x/7/H+vL20+JFxluQKVe5b3Ke5V+0kQQCamfoYKBg4GDwUKI8d0BYkWQkrLKewYBKPPDHUFiRaiZkBgmwhj/F5IgggyUJ6i8V3mv0kCayDAAeEsklXqGAgYGhgV3CnGrwVciYSYk0kokhgS44/JxqqFpiYSZbEgskd4dEBRk1GD4wdB5twKXmlHAwMDAAACdEZau06NQUwAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMC0wNy0xNVQxNTo1Mzo0MCswMDowMCVXsDIAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjAtMDctMTVUMTU6NTM6NDArMDA6MDBUCgiOAAAAAElFTkSuQmCC" />
<link rel="preload" as="font" href="./assets/Inter.var.latin-39e72c07.woff2" type="font/woff2" crossorigin />
<script type="module" crossorigin src="./assets/index-fd4af382.js"></script>
<link rel="stylesheet" href="./assets/index-218918fa.css">
</head>
<body class="px-2">
<noscript>
<p class="mb-2">You need to enable Javascript to access the Tailscale web client.</p>
<p>If you need any help, feel free to <a href="mailto:support+webclient@tailscale.com" class="link">contact us</a>.</p>
</noscript>
<script>
window.addEventListener("load", () => {
if (!window.Tailscale) {
const rootEl = document.createElement("p")
rootEl.innerHTML = 'Tailscale was built without the web client. See <a href="https://github.com/tailscale/tailscale#building-the-web-client">Building the web client</a> for more information.'
document.body.append(rootEl)
}
});
</script>
</body>
</html>

@ -0,0 +1,28 @@
<!doctype html>
<html class="bg-gray-50">
<head>
<title>Tailscale</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQflAx4QGA4EvmzDAAAA30lEQVRIx2NgGAWMCKa8JKM4A8Ovt88ekyLCDGOoyDBJMjExMbFy8zF8/EKsCAMDE8yAPyIwFps48SJIBpAL4AZwvoSx/r0lXgQpDN58EWL5x/7/H+vL20+JFxluQKVe5b3Ke5V+0kQQCamfoYKBg4GDwUKI8d0BYkWQkrLKewYBKPPDHUFiRaiZkBgmwhj/F5IgggyUJ6i8V3mv0kCayDAAeEsklXqGAgYGhgV3CnGrwVciYSYk0kokhgS44/JxqqFpiYSZbEgskd4dEBRk1GD4wdB5twKXmlHAwMDAAACdEZau06NQUwAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMC0wNy0xNVQxNTo1Mzo0MCswMDowMCVXsDIAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjAtMDctMTVUMTU6NTM6NDArMDA6MDBUCgiOAAAAAElFTkSuQmCC" />
<link rel="stylesheet" type="text/css" href="/src/index.css" />
<link rel="preload" as="font" href="/src/assets/fonts/Inter.var.latin.woff2" type="font/woff2" crossorigin />
</head>
<body class="px-2">
<noscript>
<p class="mb-2">You need to enable Javascript to access the Tailscale web client.</p>
<p>If you need any help, feel free to <a href="mailto:support+webclient@tailscale.com" class="link">contact us</a>.</p>
</noscript>
<script type="module" src="/src/index.tsx"></script>
<script>
// if this script is changed, also change hash in web.go
window.addEventListener("load", () => {
if (!window.Tailscale) {
const rootEl = document.createElement("p")
rootEl.innerHTML = 'Tailscale web interface is unavailable.';
document.body.append(rootEl)
}
})
</script>
</body>
</html>

@ -0,0 +1,81 @@
{
"name": "webclient",
"version": "0.0.1",
"license": "BSD-3-Clause",
"engines": {
"node": "18.16.1",
"yarn": "1.22.19"
},
"type": "module",
"private": true,
"dependencies": {
"@radix-ui/react-collapsible": "^1.0.3",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-popover": "^1.0.6",
"classnames": "^2.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"swr": "^2.2.4",
"wouter": "^2.11.0",
"zustand": "^4.4.7"
},
"devDependencies": {
"@types/node": "^18.16.1",
"@types/react": "^18.0.20",
"@types/react-dom": "^18.0.6",
"@vitejs/plugin-react-swc": "^3.6.0",
"autoprefixer": "^10.4.15",
"eslint": "^8.23.1",
"eslint-config-react-app": "^7.0.1",
"eslint-plugin-curly-quotes": "^1.0.4",
"jsdom": "^23.0.1",
"postcss": "^8.4.31",
"prettier": "^2.5.1",
"prettier-plugin-organize-imports": "^3.2.2",
"tailwindcss": "^3.3.3",
"typescript": "^5.3.3",
"vite": "^5.1.7",
"vite-plugin-svgr": "^4.2.0",
"vite-tsconfig-paths": "^3.5.0",
"vitest": "^1.3.1"
},
"resolutions": {
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1"
},
"scripts": {
"build": "vite build",
"start": "vite",
"lint": "tsc --noEmit && eslint 'src/**/*.{ts,tsx,js,jsx}'",
"test": "vitest",
"format": "prettier --write 'src/**/*.{ts,tsx}'",
"format-check": "prettier --check 'src/**/*.{ts,tsx}'"
},
"eslintConfig": {
"extends": [
"react-app"
],
"plugins": [
"curly-quotes",
"react-hooks"
],
"rules": {
"curly-quotes/no-straight-quotes": "warn",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "error"
},
"settings": {
"projectRoot": "client/web/package.json"
}
},
"prettier": {
"semi": false,
"printWidth": 80
},
"postcss": {
"plugins": {
"tailwindcss": {},
"autoprefixer": {}
}
}
}

@ -0,0 +1,127 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// qnap.go contains handlers and logic, such as authentication,
// that is specific to running the web client on QNAP.
package web
import (
"crypto/tls"
"encoding/xml"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
)
// authorizeQNAP authenticates the logged-in QNAP user and verifies that they
// are authorized to use the web client.
// If the user is not authorized to use the client, an error is returned.
func authorizeQNAP(r *http.Request) (authorized bool, err error) {
_, resp, err := qnapAuthn(r)
if err != nil {
return false, err
}
if resp.IsAdmin == 0 {
return false, errors.New("user is not an admin")
}
return true, nil
}
type qnapAuthResponse struct {
AuthPassed int `xml:"authPassed"`
IsAdmin int `xml:"isAdmin"`
AuthSID string `xml:"authSid"`
ErrorValue int `xml:"errorValue"`
}
func qnapAuthn(r *http.Request) (string, *qnapAuthResponse, error) {
user, err := r.Cookie("NAS_USER")
if err != nil {
return "", nil, err
}
token, err := r.Cookie("qtoken")
if err == nil {
return qnapAuthnQtoken(r, user.Value, token.Value)
}
sid, err := r.Cookie("NAS_SID")
if err == nil {
return qnapAuthnSid(r, user.Value, sid.Value)
}
return "", nil, fmt.Errorf("not authenticated by any mechanism")
}
// qnapAuthnURL returns the auth URL to use by inferring where the UI is
// running based on the request URL. This is necessary because QNAP has so
// many options, see https://github.com/tailscale/tailscale/issues/7108
// and https://github.com/tailscale/tailscale/issues/6903
func qnapAuthnURL(requestUrl string, query url.Values) string {
in, err := url.Parse(requestUrl)
scheme := ""
host := ""
if err != nil || in.Scheme == "" {
log.Printf("Cannot parse QNAP login URL %v", err)
// try localhost and hope for the best
scheme = "http"
host = "localhost"
} else {
scheme = in.Scheme
host = in.Host
}
u := url.URL{
Scheme: scheme,
Host: host,
Path: "/cgi-bin/authLogin.cgi",
RawQuery: query.Encode(),
}
return u.String()
}
func qnapAuthnQtoken(r *http.Request, user, token string) (string, *qnapAuthResponse, error) {
query := url.Values{
"qtoken": []string{token},
"user": []string{user},
}
return qnapAuthnFinish(user, qnapAuthnURL(r.URL.String(), query))
}
func qnapAuthnSid(r *http.Request, user, sid string) (string, *qnapAuthResponse, error) {
query := url.Values{
"sid": []string{sid},
}
return qnapAuthnFinish(user, qnapAuthnURL(r.URL.String(), query))
}
func qnapAuthnFinish(user, url string) (string, *qnapAuthResponse, error) {
// QNAP Force HTTPS mode uses a self-signed certificate. Even importing
// the QNAP root CA isn't enough, the cert doesn't have a usable CN nor
// SAN. See https://github.com/tailscale/tailscale/issues/6903
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)
if err != nil {
return "", nil, err
}
defer resp.Body.Close()
out, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, err
}
authResp := &qnapAuthResponse{}
if err := xml.Unmarshal(out, authResp); err != nil {
return "", nil, err
}
if authResp.AuthPassed == 0 {
return "", nil, fmt.Errorf("not authenticated")
}
return user, authResp, nil
}

@ -0,0 +1,377 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import { useCallback } from "react"
import useToaster from "src/hooks/toaster"
import { ExitNode, NodeData, SubnetRoute } from "src/types"
import { assertNever } from "src/utils/util"
import { MutatorOptions, SWRConfiguration, useSWRConfig } from "swr"
import { noExitNode, runAsExitNode } from "./hooks/exit-nodes"
export const swrConfig: SWRConfiguration = {
fetcher: (url: string) => apiFetch(url, "GET"),
onError: (err, _) => console.error(err),
}
type APIType =
| { action: "up"; data: TailscaleUpData }
| { action: "logout" }
| { action: "new-auth-session"; data: AuthSessionNewData }
| { action: "update-prefs"; data: LocalPrefsData }
| { action: "update-routes"; data: SubnetRoute[] }
| { action: "update-exit-node"; data: ExitNode }
/**
* POST /api/up data
*/
type TailscaleUpData = {
Reauthenticate?: boolean // force reauthentication
ControlURL?: string
AuthKey?: string
}
/**
* GET /api/auth/session/new data
*/
type AuthSessionNewData = {
authUrl: string
}
/**
* PATCH /api/local/v0/prefs data
*/
type LocalPrefsData = {
RunSSHSet?: boolean
RunSSH?: boolean
}
/**
* POST /api/routes data
*/
type RoutesData = {
SetExitNode?: boolean
SetRoutes?: boolean
UseExitNode?: string
AdvertiseExitNode?: boolean
AdvertiseRoutes?: string[]
}
/**
* useAPI hook returns an api handler that can execute api calls
* throughout the web client UI.
*/
export function useAPI() {
const toaster = useToaster()
const { mutate } = useSWRConfig() // allows for global mutation
const handlePostError = useCallback(
(toast?: string) => (err: Error) => {
console.error(err)
toast && toaster.show({ variant: "danger", message: toast })
throw err
},
[toaster]
)
/**
* optimisticMutate wraps the SWR `mutate` function to apply some
* type-awareness with the following behavior:
*
* 1. `optimisticData` update is applied immediately on FetchDataType
* throughout the web client UI.
*
* 2. `fetch` data mutation runs.
*
* 3. On completion, FetchDataType is revalidated to exactly reflect the
* updated server state.
*
* The `key` argument is the useSWR key associated with the MutateDataType.
* All `useSWR(key)` consumers throughout the UI will see updates reflected.
*/
const optimisticMutate = useCallback(
<MutateDataType, FetchDataType = any>(
key: string,
fetch: Promise<FetchDataType>,
optimisticData: (current: MutateDataType) => MutateDataType,
revalidate?: boolean // optionally specify whether to run final revalidation (step 3)
): Promise<FetchDataType | undefined> => {
const options: MutatorOptions = {
/**
* populateCache is meant for use when the remote request returns back
* the updated data directly. i.e. When FetchDataType is the same as
* MutateDataType. Most of our data manipulation requests return a 200
* with empty data on success. We turn off populateCache so that the
* cache only gets updated after completion of the remote reqeust when
* the revalidation step runs.
*/
populateCache: false,
optimisticData,
revalidate: revalidate,
}
return mutate(key, fetch, options)
},
[mutate]
)
const api = useCallback(
(t: APIType) => {
switch (t.action) {
/**
* "up" handles authenticating the machine to tailnet.
*/
case "up":
return apiFetch<{ url?: string }>("/up", "POST", t.data)
.then((d) => d.url && window.open(d.url, "_blank")) // "up" login step
.then(() => incrementMetric("web_client_node_connect"))
.then(() => mutate("/data"))
.catch(handlePostError("Failed to login"))
/**
* "logout" handles logging the node out of tailscale, effectively
* expiring its node key.
*/
case "logout":
// For logout, must increment metric before running api call,
// as tailscaled will be unreachable after the call completes.
incrementMetric("web_client_node_disconnect")
return apiFetch("/local/v0/logout", "POST").catch(
handlePostError("Failed to logout")
)
/**
* "new-auth-session" handles creating a new check mode session to
* authorize the viewing user to manage the node via the web client.
*/
case "new-auth-session":
return apiFetch<AuthSessionNewData>("/auth/session/new", "GET").catch(
handlePostError("Failed to create new session")
)
/**
* "update-prefs" handles setting the node's tailscale prefs.
*/
case "update-prefs": {
return optimisticMutate<NodeData>(
"/data",
apiFetch<LocalPrefsData>("/local/v0/prefs", "PATCH", t.data),
(old) => ({
...old,
RunningSSHServer: t.data.RunSSHSet
? Boolean(t.data.RunSSH)
: old.RunningSSHServer,
})
)
.then(
() =>
t.data.RunSSHSet &&
incrementMetric(
t.data.RunSSH
? "web_client_ssh_enable"
: "web_client_ssh_disable"
)
)
.catch(handlePostError("Failed to update node preference"))
}
/**
* "update-routes" handles setting the node's advertised routes.
*/
case "update-routes": {
const body: RoutesData = {
SetRoutes: true,
AdvertiseRoutes: t.data.map((r) => r.Route),
}
return optimisticMutate<NodeData>(
"/data",
apiFetch<void>("/routes", "POST", body),
(old) => ({ ...old, AdvertisedRoutes: t.data })
)
.then(() => incrementMetric("web_client_advertise_routes_change"))
.catch(handlePostError("Failed to update routes"))
}
/**
* "update-exit-node" handles updating the node's state as either
* running as an exit node or using another node as an exit node.
*/
case "update-exit-node": {
const id = t.data.ID
const body: RoutesData = {
SetExitNode: true,
}
if (id !== noExitNode.ID && id !== runAsExitNode.ID) {
body.UseExitNode = id
} else if (id === runAsExitNode.ID) {
body.AdvertiseExitNode = true
}
const metrics: MetricName[] = []
return optimisticMutate<NodeData>(
"/data",
apiFetch<void>("/routes", "POST", body),
(old) => {
// Only update metrics whose values have changed.
if (old.AdvertisingExitNode !== Boolean(body.AdvertiseExitNode)) {
metrics.push(
body.AdvertiseExitNode
? "web_client_advertise_exitnode_enable"
: "web_client_advertise_exitnode_disable"
)
}
if (Boolean(old.UsingExitNode) !== Boolean(body.UseExitNode)) {
metrics.push(
body.UseExitNode
? "web_client_use_exitnode_enable"
: "web_client_use_exitnode_disable"
)
}
return {
...old,
UsingExitNode: Boolean(body.UseExitNode) ? t.data : undefined,
AdvertisingExitNode: Boolean(body.AdvertiseExitNode),
AdvertisingExitNodeApproved: Boolean(body.AdvertiseExitNode)
? true // gets updated in revalidation
: old.AdvertisingExitNodeApproved,
}
},
false // skip final revalidation
)
.then(() => metrics.forEach((m) => incrementMetric(m)))
.catch(handlePostError("Failed to update exit node"))
}
default:
assertNever(t)
}
},
[handlePostError, mutate, optimisticMutate]
)
return api
}
let csrfToken: string
let synoToken: string | undefined // required for synology API requests
let unraidCsrfToken: string | undefined // required for unraid POST requests (#8062)
/**
* apiFetch wraps the standard JS fetch function with csrf header
* management and param additions specific to the web client.
*
* apiFetch adds the `api` prefix to the request URL,
* so endpoint should be provided without the `api` prefix
* (i.e. provide `/data` rather than `api/data`).
*/
export function apiFetch<T>(
endpoint: string,
method: "GET" | "POST" | "PATCH",
body?: any
): Promise<T> {
const urlParams = new URLSearchParams(window.location.search)
const nextParams = new URLSearchParams()
if (synoToken) {
nextParams.set("SynoToken", synoToken)
} else {
const token = urlParams.get("SynoToken")
if (token) {
nextParams.set("SynoToken", token)
}
}
const search = nextParams.toString()
const url = `api${endpoint}${search ? `?${search}` : ""}`
var contentType: string
if (unraidCsrfToken && method === "POST") {
const params = new URLSearchParams()
params.append("csrf_token", unraidCsrfToken)
if (body) {
params.append("ts_data", JSON.stringify(body))
}
body = params.toString()
contentType = "application/x-www-form-urlencoded;charset=UTF-8"
} else {
body = body ? JSON.stringify(body) : undefined
contentType = "application/json"
}
return fetch(url, {
method: method,
headers: {
Accept: "application/json",
"Content-Type": contentType,
"X-CSRF-Token": csrfToken,
},
body: body,
})
.then((r) => {
updateCsrfToken(r)
if (!r.ok) {
return r.text().then((err) => {
throw new Error(err)
})
}
return r
})
.then((r) => {
if (r.headers.get("Content-Type") === "application/json") {
return r.json()
}
})
.then((r) => {
r?.UnraidToken && setUnraidCsrfToken(r.UnraidToken)
return r
})
}
function updateCsrfToken(r: Response) {
const tok = r.headers.get("X-CSRF-Token")
if (tok) {
csrfToken = tok
}
}
export function setSynoToken(token?: string) {
synoToken = token
}
function setUnraidCsrfToken(token?: string) {
unraidCsrfToken = token
}
/**
* incrementMetric hits the client metrics local API endpoint to
* increment the given counter metric by one.
*/
export function incrementMetric(metricName: MetricName) {
const postData: MetricsPOSTData[] = [
{
Name: metricName,
Type: "counter",
Value: 1,
},
]
apiFetch("/local/v0/upload-client-metrics", "POST", postData).catch(
(error) => {
console.error(error)
}
)
}
type MetricsPOSTData = {
Name: MetricName
Type: MetricType
Value: number
}
type MetricType = "counter" | "gauge"
export type MetricName =
| "web_client_advertise_exitnode_enable"
| "web_client_advertise_exitnode_disable"
| "web_client_use_exitnode_enable"
| "web_client_use_exitnode_disable"
| "web_client_ssh_enable"
| "web_client_ssh_disable"
| "web_client_node_connect"
| "web_client_node_disconnect"
| "web_client_advertise_routes_change"

@ -0,0 +1,4 @@
<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 12.5H19" stroke="#706E6D" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 5.5L19 12.5L12 19.5" stroke="#706E6D" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 324 B

@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M16 12L12 8L8 12" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 16V8" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 522 B

@ -0,0 +1,4 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22 11.08V12C21.9988 14.1564 21.3005 16.2547 20.0093 17.9818C18.7182 19.709 16.9033 20.9725 14.8354 21.5839C12.7674 22.1953 10.5573 22.1219 8.53447 21.3746C6.51168 20.6273 4.78465 19.2461 3.61096 17.4371C2.43727 15.628 1.87979 13.4881 2.02168 11.3363C2.16356 9.18455 2.99721 7.13631 4.39828 5.49706C5.79935 3.85781 7.69279 2.71537 9.79619 2.24013C11.8996 1.7649 14.1003 1.98232 16.07 2.85999" stroke="#1EA672" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M22 4L12 14.01L9 11.01" stroke="#1EA672" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 704 B

@ -0,0 +1,3 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M16.6673 5L7.50065 14.1667L3.33398 10" stroke="#706E6D" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 236 B

@ -0,0 +1,3 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5 7.5L10 12.5L15 7.5" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 203 B

@ -0,0 +1,11 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_14876_118476)">
<path d="M8.00065 14.6667C11.6825 14.6667 14.6673 11.6819 14.6673 8.00004C14.6673 4.31814 11.6825 1.33337 8.00065 1.33337C4.31875 1.33337 1.33398 4.31814 1.33398 8.00004C1.33398 11.6819 4.31875 14.6667 8.00065 14.6667Z" stroke="#706E6D" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 4V8L10.6667 9.33333" stroke="#706E6D" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<defs>
<clipPath id="clip0_14876_118476">
<rect width="16" height="16" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 678 B

@ -0,0 +1,4 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M20 9H11C9.89543 9 9 9.89543 9 11V20C9 21.1046 9.89543 22 11 22H20C21.1046 22 22 21.1046 22 20V11C22 9.89543 21.1046 9 20 9Z" stroke="#292828" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5 15H4C3.46957 15 2.96086 14.7893 2.58579 14.4142C2.21071 14.0391 2 13.5304 2 13V4C2 3.46957 2.21071 2.96086 2.58579 2.58579C2.96086 2.21071 3.46957 2 4 2H13C13.5304 2 14.0391 2.21071 14.4142 2.58579C14.7893 2.96086 15 3.46957 15 4V5" stroke="#292828" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 649 B

@ -0,0 +1,11 @@
<svg width="15" height="16" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_15367_14595)">
<path d="M0.625 8C0.625 8 3.125 3 7.5 3C11.875 3 14.375 8 14.375 8C14.375 8 11.875 13 7.5 13C3.125 13 0.625 8 0.625 8Z" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.5 9.875C8.53553 9.875 9.375 9.03553 9.375 8C9.375 6.96447 8.53553 6.125 7.5 6.125C6.46447 6.125 5.625 6.96447 5.625 8C5.625 9.03553 6.46447 9.875 7.5 9.875Z" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<defs>
<clipPath id="clip0_15367_14595">
<rect width="15" height="15" fill="white" transform="translate(0 0.5)"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 738 B

@ -0,0 +1,13 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_14860_117136)">
<path d="M16.666 1.66667H3.33268C2.41221 1.66667 1.66602 2.41286 1.66602 3.33334V6.66667C1.66602 7.58715 2.41221 8.33334 3.33268 8.33334H16.666C17.5865 8.33334 18.3327 7.58715 18.3327 6.66667V3.33334C18.3327 2.41286 17.5865 1.66667 16.666 1.66667Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M16.666 11.6667H3.33268C2.41221 11.6667 1.66602 12.4129 1.66602 13.3333V16.6667C1.66602 17.5871 2.41221 18.3333 3.33268 18.3333H16.666C17.5865 18.3333 18.3327 17.5871 18.3327 16.6667V13.3333C18.3327 12.4129 17.5865 11.6667 16.666 11.6667Z" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5 5H5.01" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5 15H5.01" stroke="black" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<defs>
<clipPath id="clip0_14860_117136">
<rect width="20" height="20" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

@ -0,0 +1,4 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10 4.16663V15.8333" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4.16602 10H15.8327" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 329 B

@ -0,0 +1,4 @@
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.16667 15.8333C12.8486 15.8333 15.8333 12.8486 15.8333 9.16667C15.8333 5.48477 12.8486 2.5 9.16667 2.5C5.48477 2.5 2.5 5.48477 2.5 9.16667C2.5 12.8486 5.48477 15.8333 9.16667 15.8333Z" stroke="#706E6D" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M17.5 17.5L13.875 13.875" stroke="#706E6D" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 500 B

@ -0,0 +1,18 @@
<svg width="26" height="26" viewBox="0 0 26 26" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_13627_11860)">
<path opacity="0.2" d="M3.8696 6.77137C5.56662 6.77137 6.94233 5.39567 6.94233 3.69865C6.94233 2.00163 5.56662 0.625919 3.8696 0.625919C2.17258 0.625919 0.796875 2.00163 0.796875 3.69865C0.796875 5.39567 2.17258 6.77137 3.8696 6.77137Z" fill="black"/>
<path d="M3.8696 15.9327C5.56662 15.9327 6.94233 14.5569 6.94233 12.8599C6.94233 11.1629 5.56662 9.7872 3.8696 9.7872C2.17258 9.7872 0.796875 11.1629 0.796875 12.8599C0.796875 14.5569 2.17258 15.9327 3.8696 15.9327Z" fill="black"/>
<path opacity="0.2" d="M3.8696 25.2646C5.56662 25.2646 6.94233 23.8889 6.94233 22.1919C6.94233 20.4949 5.56662 19.1192 3.8696 19.1192C2.17258 19.1192 0.796875 20.4949 0.796875 22.1919C0.796875 23.8889 2.17258 25.2646 3.8696 25.2646Z" fill="black"/>
<path d="M13.0879 15.9327C14.7849 15.9327 16.1606 14.5569 16.1606 12.8599C16.1606 11.1629 14.7849 9.7872 13.0879 9.7872C11.3908 9.7872 10.0151 11.1629 10.0151 12.8599C10.0151 14.5569 11.3908 15.9327 13.0879 15.9327Z" fill="black"/>
<path d="M13.0879 25.2646C14.7849 25.2646 16.1606 23.8889 16.1606 22.1919C16.1606 20.4949 14.7849 19.1192 13.0879 19.1192C11.3908 19.1192 10.0151 20.4949 10.0151 22.1919C10.0151 23.8889 11.3908 25.2646 13.0879 25.2646Z" fill="black"/>
<path opacity="0.2" d="M13.0879 6.77137C14.7849 6.77137 16.1606 5.39567 16.1606 3.69865C16.1606 2.00163 14.7849 0.625919 13.0879 0.625919C11.3908 0.625919 10.0151 2.00163 10.0151 3.69865C10.0151 5.39567 11.3908 6.77137 13.0879 6.77137Z" fill="black"/>
<path opacity="0.2" d="M22.1919 6.77137C23.8889 6.77137 25.2646 5.39567 25.2646 3.69865C25.2646 2.00163 23.8889 0.625919 22.1919 0.625919C20.4948 0.625919 19.1191 2.00163 19.1191 3.69865C19.1191 5.39567 20.4948 6.77137 22.1919 6.77137Z" fill="black"/>
<path d="M22.1919 15.9327C23.8889 15.9327 25.2646 14.5569 25.2646 12.8599C25.2646 11.1629 23.8889 9.7872 22.1919 9.7872C20.4948 9.7872 19.1191 11.1629 19.1191 12.8599C19.1191 14.5569 20.4948 15.9327 22.1919 15.9327Z" fill="black"/>
<path opacity="0.2" d="M22.1919 25.2646C23.8889 25.2646 25.2646 23.8889 25.2646 22.1919C25.2646 20.4949 23.8889 19.1192 22.1919 19.1192C20.4948 19.1192 19.1191 20.4949 19.1191 22.1919C19.1191 23.8889 20.4948 25.2646 22.1919 25.2646Z" fill="black"/>
</g>
<defs>
<clipPath id="clip0_13627_11860">
<rect width="26" height="26" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

@ -0,0 +1,20 @@
<svg width="121" height="22" viewBox="0 0 121 22" fill="none" xmlns="http://www.w3.org/2000/svg">
<ellipse cx="2.69191" cy="10.7677" rx="2.69191" ry="2.69191" fill="#141414"/>
<ellipse cx="10.7676" cy="10.7677" rx="2.69191" ry="2.69191" fill="#141414"/>
<ellipse opacity="0.2" cx="2.69191" cy="18.8434" rx="2.69191" ry="2.69191" fill="#141414"/>
<circle opacity="0.2" cx="18.8433" cy="18.8434" r="2.69191" fill="#141414"/>
<ellipse cx="10.7676" cy="18.8434" rx="2.69191" ry="2.69191" fill="#141414"/>
<circle cx="18.8433" cy="10.7677" r="2.69191" fill="#141414"/>
<ellipse opacity="0.2" cx="2.69191" cy="2.69191" rx="2.69191" ry="2.69191" fill="#141414"/>
<ellipse opacity="0.2" cx="10.7676" cy="2.69191" rx="2.69191" ry="2.69191" fill="#141414"/>
<circle opacity="0.2" cx="18.8433" cy="2.69191" r="2.69191" fill="#141414"/>
<path d="M37.8847 19.9603C38.6525 19.9603 39.2764 19.8883 40.0202 19.7443V16.9609C39.5643 17.1289 39.0605 17.1769 38.5806 17.1769C37.4048 17.1769 36.9729 16.601 36.9729 15.4973V9.83453H40.0202V7.05116H36.9729V2.92409H33.6137V7.05116H31.4302V9.83453H33.6137V15.8092C33.6137 18.4486 35.0054 19.9603 37.8847 19.9603Z" fill="#141414"/>
<path d="M45.5064 19.9603C47.306 19.9603 48.5057 19.3604 49.1056 18.4246C49.1536 18.8325 49.2975 19.3844 49.4895 19.7203H52.5128C52.3448 19.1444 52.2249 18.2326 52.2249 17.6328V11.0583C52.2249 8.34687 50.2813 6.81121 46.994 6.81121C44.4986 6.81121 42.555 7.747 41.4753 9.1147L43.3949 11.0103C44.2587 10.0505 45.3624 9.5466 46.7061 9.5466C48.3377 9.5466 49.0576 10.0985 49.0576 10.9143C49.0576 11.6101 48.5777 12.09 45.9863 12.09C43.4908 12.09 40.9714 13.1218 40.9714 16.0011C40.9714 18.6645 42.891 19.9603 45.5064 19.9603ZM46.1782 17.4168C44.8825 17.4168 44.2827 16.8649 44.2827 15.8812C44.2827 15.0174 45.0025 14.4415 46.2022 14.4415C48.1218 14.4415 48.6497 14.3215 49.0576 13.9136V14.9454C49.0576 16.3131 47.9058 17.4168 46.1782 17.4168Z" fill="#141414"/>
<path d="M54.4086 5.44352H57.9118V2.30023H54.4086V5.44352ZM54.4805 19.7203H57.8398V7.05116H54.4805V19.7203Z" fill="#141414"/>
<path d="M60.287 19.7203H63.6463V2.68414H60.287V19.7203Z" fill="#141414"/>
<path d="M70.6285 19.9603C74.3237 19.9603 76.2193 18.0167 76.2193 15.9771C76.2193 14.1296 75.2835 12.7619 72.2122 12.21C70.0527 11.8261 68.709 11.3462 68.709 10.6024C68.709 9.95451 69.4768 9.49861 70.7725 9.49861C71.9242 9.49861 72.884 9.88252 73.6038 10.7223L75.7394 8.92274C74.6596 7.57904 72.884 6.81121 70.7725 6.81121C67.5332 6.81121 65.5177 8.53883 65.5177 10.6503C65.5177 12.9538 67.6292 13.9856 69.9087 14.3935C71.8043 14.7294 72.86 15.0893 72.86 15.9052C72.86 16.601 72.1162 17.1769 70.7005 17.1769C69.3088 17.1769 68.2291 16.529 67.7252 15.5692L64.8938 16.9129C65.5897 18.6405 67.9651 19.9603 70.6285 19.9603Z" fill="#141414"/>
<path d="M83.7294 19.9603C86.1288 19.9603 87.8564 19.0005 89.1521 16.841L86.4648 15.4733C85.9609 16.481 85.1451 17.1769 83.7294 17.1769C81.5939 17.1769 80.4421 15.4493 80.4421 13.3617C80.4421 11.2742 81.6658 9.59459 83.7294 9.59459C85.0251 9.59459 85.8889 10.2904 86.3928 11.3462L89.1042 9.90652C88.1924 7.91497 86.3928 6.81121 83.7294 6.81121C79.3384 6.81121 77.0829 10.0265 77.0829 13.3617C77.0829 16.9849 79.8183 19.9603 83.7294 19.9603Z" fill="#141414"/>
<path d="M94.5031 19.9603C96.3027 19.9603 97.5025 19.3604 98.1023 18.4246C98.1503 18.8325 98.2943 19.3844 98.4862 19.7203H101.51C101.342 19.1444 101.222 18.2326 101.222 17.6328V11.0583C101.222 8.34687 99.2781 6.81121 95.9908 6.81121C93.4954 6.81121 91.5518 7.747 90.472 9.1147L92.3916 11.0103C93.2554 10.0505 94.3592 9.5466 95.7029 9.5466C97.3345 9.5466 98.0543 10.0985 98.0543 10.9143C98.0543 11.6101 97.5744 12.09 94.983 12.09C92.4876 12.09 89.9682 13.1218 89.9682 16.0011C89.9682 18.6645 91.8877 19.9603 94.5031 19.9603ZM95.175 17.4168C93.8793 17.4168 93.2794 16.8649 93.2794 15.8812C93.2794 15.0174 93.9992 14.4415 95.199 14.4415C97.1185 14.4415 97.6464 14.3215 98.0543 13.9136V14.9454C98.0543 16.3131 96.9026 17.4168 95.175 17.4168Z" fill="#141414"/>
<path d="M103.196 19.7203H106.555V2.68414H103.196V19.7203Z" fill="#141414"/>
<path d="M114.617 19.9603C117.089 19.9603 119.08 18.9765 120.184 17.2249L117.641 15.5932C116.969 16.649 116.081 17.2249 114.617 17.2249C112.962 17.2249 111.762 16.3131 111.45 14.5375H121V13.3617C121 10.0265 118.96 6.81121 114.593 6.81121C110.442 6.81121 108.187 10.0505 108.187 13.3857C108.187 18.1367 111.762 19.9603 114.617 19.9603ZM111.57 11.8981C112.098 10.2904 113.202 9.5466 114.665 9.5466C116.321 9.5466 117.329 10.5304 117.665 11.8981H111.57Z" fill="#141414"/>
</svg>

After

Width:  |  Height:  |  Size: 4.4 KiB

@ -0,0 +1,4 @@
<svg width="15" height="16" viewBox="0 0 15 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12.5 13.625V12.375C12.5 11.712 12.2366 11.0761 11.7678 10.6072C11.2989 10.1384 10.663 9.875 10 9.875H5C4.33696 9.875 3.70107 10.1384 3.23223 10.6072C2.76339 11.0761 2.5 11.712 2.5 12.375V13.625" stroke="#706E6D" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.5 7.375C8.88071 7.375 10 6.25571 10 4.875C10 3.49429 8.88071 2.375 7.5 2.375C6.11929 2.375 5 3.49429 5 4.875C5 6.25571 6.11929 7.375 7.5 7.375Z" stroke="#706E6D" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 635 B

@ -0,0 +1,5 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="red" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15 9L9 15" stroke="red" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9 9L15 15" stroke="red" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 506 B

@ -0,0 +1,4 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M18 6L6 18" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M6 6L18 18" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 277 B

@ -0,0 +1,28 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import cx from "classnames"
import React from "react"
import Badge from "src/ui/badge"
/**
* ACLTag handles the display of an ACL tag.
*/
export default function ACLTag({
tag,
className,
}: {
tag: string
className?: string
}) {
return (
<Badge
variant="status"
color="outline"
className={cx("flex text-xs items-center", className)}
>
<span className="font-medium">tag:</span>
<span className="text-gray-500">{tag.replace("tag:", "")}</span>
</Badge>
)
}

@ -0,0 +1,133 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import * as Primitive from "@radix-ui/react-popover"
import cx from "classnames"
import React, { useCallback } from "react"
import ChevronDown from "src/assets/icons/chevron-down.svg?react"
import Copy from "src/assets/icons/copy.svg?react"
import NiceIP from "src/components/nice-ip"
import useToaster from "src/hooks/toaster"
import Button from "src/ui/button"
import { copyText } from "src/utils/clipboard"
/**
* AddressCard renders a clickable IP address text that opens a
* dialog with a copyable list of all addresses (IPv4, IPv6, DNS)
* for the machine.
*/
export default function AddressCard({
v4Address,
v6Address,
shortDomain,
fullDomain,
className,
triggerClassName,
}: {
v4Address: string
v6Address: string
shortDomain?: string
fullDomain?: string
className?: string
triggerClassName?: string
}) {
const children = (
<ul className="flex flex-col divide-y rounded-md overflow-hidden">
{shortDomain && <AddressRow label="short domain" value={shortDomain} />}
{fullDomain && <AddressRow label="full domain" value={fullDomain} />}
{v4Address && (
<AddressRow
key={v4Address}
label="IPv4 address"
ip={true}
value={v4Address}
/>
)}
{v6Address && (
<AddressRow
key={v6Address}
label="IPv6 address"
ip={true}
value={v6Address}
/>
)}
</ul>
)
return (
<Primitive.Root>
<Primitive.Trigger asChild>
<Button
variant="minimal"
className={cx("-ml-1 px-1 py-0 font-normal", className)}
suffixIcon={
<ChevronDown className="w-5 h-5" stroke="#232222" /* gray-800 */ />
}
aria-label="See all addresses for this device."
>
<NiceIP className={triggerClassName} ip={v4Address ?? v6Address} />
</Button>
</Primitive.Trigger>
<Primitive.Content
className="shadow-popover origin-radix-popover state-open:animate-scale-in state-closed:animate-scale-out bg-white rounded-md z-50 max-w-sm"
sideOffset={10}
side="top"
>
{children}
</Primitive.Content>
</Primitive.Root>
)
}
function AddressRow({
label,
value,
ip,
}: {
label: string
value: string
ip?: boolean
}) {
const toaster = useToaster()
const onCopyClick = useCallback(() => {
copyText(value)
.then(() => toaster.show({ message: `Copied ${label} to clipboard` }))
.catch(() =>
toaster.show({
message: `Failed to copy ${label} to clipboard`,
variant: "danger",
})
)
}, [label, toaster, value])
return (
<li className="py flex items-center gap-2">
<button
className={cx(
"relative flex group items-center transition-colors",
"focus:outline-none focus-visible:ring",
"disabled:text-text-muted enabled:hover:text-gray-500",
"w-60 text-sm flex-1"
)}
onClick={onCopyClick}
aria-label={`Copy ${value} to your clip board.`}
>
<div className="overflow-hidden pl-3 pr-10 py-2 tabular-nums">
{ip ? (
<NiceIP ip={value} />
) : (
<div className="truncate m-w-full">{value}</div>
)}
</div>
<span
className={cx(
"absolute right-0 pl-6 pr-3 bg-gradient-to-r from-transparent",
"text-gray-900 group-hover:text-gray-600"
)}
>
<Copy className="w-4 h-4" />
</span>
</button>
</li>
)
}

@ -0,0 +1,172 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import React from "react"
import TailscaleIcon from "src/assets/icons/tailscale-icon.svg?react"
import LoginToggle from "src/components/login-toggle"
import DeviceDetailsView from "src/components/views/device-details-view"
import DisconnectedView from "src/components/views/disconnected-view"
import HomeView from "src/components/views/home-view"
import LoginView from "src/components/views/login-view"
import SSHView from "src/components/views/ssh-view"
import SubnetRouterView from "src/components/views/subnet-router-view"
import { UpdatingView } from "src/components/views/updating-view"
import useAuth, { AuthResponse, canEdit } from "src/hooks/auth"
import { Feature, NodeData, featureDescription } from "src/types"
import Card from "src/ui/card"
import EmptyState from "src/ui/empty-state"
import LoadingDots from "src/ui/loading-dots"
import useSWR from "swr"
import { Link, Route, Router, Switch, useLocation } from "wouter"
export default function App() {
const { data: auth, loading: loadingAuth, newSession } = useAuth()
return (
<main className="min-w-sm max-w-lg mx-auto py-4 sm:py-14 px-5">
{loadingAuth || !auth ? (
<LoadingView />
) : (
<WebClient auth={auth} newSession={newSession} />
)}
</main>
)
}
function WebClient({
auth,
newSession,
}: {
auth: AuthResponse
newSession: () => Promise<void>
}) {
const { data: node } = useSWR<NodeData>("/data")
return !node ? (
<LoadingView />
) : node.Status === "NeedsLogin" ||
node.Status === "NoState" ||
node.Status === "Stopped" ? (
// Client not on a tailnet, render login.
<LoginView data={node} />
) : (
// Otherwise render the new web client.
<>
<Router base={node.URLPrefix}>
<Header node={node} auth={auth} newSession={newSession} />
<Switch>
<Route path="/">
<HomeView node={node} auth={auth} />
</Route>
<Route path="/details">
<DeviceDetailsView node={node} auth={auth} />
</Route>
<FeatureRoute path="/subnets" feature="advertise-routes" node={node}>
<SubnetRouterView
readonly={!canEdit("subnets", auth)}
node={node}
/>
</FeatureRoute>
<FeatureRoute path="/ssh" feature="ssh" node={node}>
<SSHView readonly={!canEdit("ssh", auth)} node={node} />
</FeatureRoute>
{/* <Route path="/serve">Share local content</Route> */}
<FeatureRoute path="/update" feature="auto-update" node={node}>
<UpdatingView
versionInfo={node.ClientVersion}
currentVersion={node.IPNVersion}
/>
</FeatureRoute>
<Route path="/disconnected">
<DisconnectedView />
</Route>
<Route>
<Card className="mt-8">
<EmptyState description="Page not found" />
</Card>
</Route>
</Switch>
</Router>
</>
)
}
/**
* FeatureRoute renders a Route component,
* but only displays the child view if the specified feature is
* available for use on this node's platform. If not available,
* a not allowed view is rendered instead.
*/
function FeatureRoute({
path,
node,
feature,
children,
}: {
path: string
node: NodeData
feature: Feature
children: React.ReactNode
}) {
return (
<Route path={path}>
{!node.Features[feature] ? (
<Card className="mt-8">
<EmptyState
description={`${featureDescription(
feature
)} not available on this device.`}
/>
</Card>
) : (
children
)}
</Route>
)
}
function Header({
node,
auth,
newSession,
}: {
node: NodeData
auth: AuthResponse
newSession: () => Promise<void>
}) {
const [loc] = useLocation()
if (loc === "/disconnected") {
// No header on view presented after logout.
return null
}
return (
<>
<div className="flex flex-wrap gap-4 justify-between items-center mb-9 md:mb-12">
<Link to="/" className="flex gap-3 overflow-hidden">
<TailscaleIcon />
<div className="inline text-gray-800 text-lg font-medium leading-snug truncate">
{node.DomainName}
</div>
</Link>
<LoginToggle node={node} auth={auth} newSession={newSession} />
</div>
{loc !== "/" && loc !== "/update" && (
<Link to="/" className="link font-medium block mb-2">
&larr; Back to {node.DeviceName}
</Link>
)}
</>
)
}
/**
* LoadingView fills its container with small animated loading dots
* in the center.
*/
export function LoadingView() {
return (
<LoadingDots className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2" />
)
}

@ -0,0 +1,57 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import React from "react"
import { NodeData } from "src/types"
/**
* AdminContainer renders its contents only if the node's control
* server has an admin panel.
*
* TODO(sonia,will): Similarly, this could also hide the contents
* if the viewing user is a non-admin.
*/
export function AdminContainer({
node,
children,
className,
}: {
node: NodeData
children: React.ReactNode
className?: string
}) {
if (!node.ControlAdminURL.includes("tailscale.com")) {
// Admin panel only exists on Tailscale control servers.
return null
}
return <div className={className}>{children}</div>
}
/**
* AdminLink renders its contents wrapped in a link to the node's control
* server admin panel.
*
* AdminLink is meant for use only inside of a AdminContainer component,
* to avoid rendering a link when the node's control server does not have
* an admin panel.
*/
export function AdminLink({
node,
children,
path,
}: {
node: NodeData
children: React.ReactNode
path: string // admin path, e.g. "/settings/webhooks"
}) {
return (
<a
href={`${node.ControlAdminURL}${path}`}
className="link"
target="_blank"
rel="noreferrer"
>
{children}
</a>
)
}

@ -0,0 +1,584 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import cx from "classnames"
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useAPI } from "src/api"
import Check from "src/assets/icons/check.svg?react"
import ChevronDown from "src/assets/icons/chevron-down.svg?react"
import useExitNodes, {
noExitNode,
runAsExitNode,
trimDNSSuffix,
} from "src/hooks/exit-nodes"
import { ExitNode, NodeData } from "src/types"
import Popover from "src/ui/popover"
import SearchInput from "src/ui/search-input"
import { useSWRConfig } from "swr"
export default function ExitNodeSelector({
className,
node,
disabled,
}: {
className?: string
node: NodeData
disabled?: boolean
}) {
const api = useAPI()
const [open, setOpen] = useState<boolean>(false)
const [selected, setSelected] = useState<ExitNode>(toSelectedExitNode(node))
const [pending, setPending] = useState<boolean>(false)
const { mutate } = useSWRConfig() // allows for global mutation
useEffect(() => setSelected(toSelectedExitNode(node)), [node])
useEffect(() => {
setPending(
node.AdvertisingExitNode && node.AdvertisingExitNodeApproved === false
)
}, [node])
const handleSelect = useCallback(
(n: ExitNode) => {
setOpen(false)
if (n.ID === selected.ID) {
return // no update
}
// Eager clear of pending state to avoid UI oddities
if (n.ID !== runAsExitNode.ID) {
setPending(false)
}
api({ action: "update-exit-node", data: n })
// refresh data after short timeout to pick up any pending approval updates
setTimeout(() => {
mutate("/data")
}, 1000)
},
[api, mutate, selected.ID]
)
const [
none, // not using exit nodes
advertising, // advertising as exit node
using, // using another exit node
offline, // selected exit node node is offline
] = useMemo(
() => [
selected.ID === noExitNode.ID,
selected.ID === runAsExitNode.ID,
selected.ID !== noExitNode.ID && selected.ID !== runAsExitNode.ID,
!selected.Online,
],
[selected.ID, selected.Online]
)
return (
<div
className={cx(
"rounded-md",
{
"bg-red-600": offline,
"bg-yellow-400": pending,
},
className
)}
>
<div
className={cx("p-1.5 rounded-md border flex items-stretch gap-1.5", {
"border-gray-200": none,
"bg-yellow-300 border-yellow-300": advertising && !offline,
"bg-blue-500 border-blue-500": using && !offline,
"bg-red-500 border-red-500": offline,
})}
>
<Popover
open={disabled ? false : open}
onOpenChange={setOpen}
className="overflow-hidden"
side="bottom"
sideOffset={0}
align="start"
content={
<ExitNodeSelectorInner
node={node}
selected={selected}
onSelect={handleSelect}
/>
}
asChild
>
<button
className={cx("flex-1 px-2 py-1.5 rounded-[1px]", {
"bg-white": none,
"hover:bg-gray-100": none && !disabled,
"bg-yellow-300": advertising && !offline,
"hover:bg-yellow-200": advertising && !offline && !disabled,
"bg-blue-500": using && !offline,
"hover:bg-blue-400": using && !offline && !disabled,
"bg-red-500": offline,
"hover:bg-red-400": offline && !disabled,
})}
onClick={() => setOpen(!open)}
disabled={disabled}
>
<p
className={cx(
"text-gray-500 text-xs text-left font-medium uppercase tracking-wide mb-1",
{ "opacity-70 text-white": advertising || using }
)}
>
Exit node{offline && " offline"}
</p>
<div className="flex items-center">
<p
className={cx("text-gray-800", {
"text-white": advertising || using,
})}
>
{selected.Location && (
<>
<CountryFlag code={selected.Location.CountryCode} />{" "}
</>
)}
{selected === runAsExitNode
? "Running as exit node"
: selected.Name}
</p>
{!disabled && (
<ChevronDown
className={cx("ml-1", {
"stroke-gray-800": none,
"stroke-white": advertising || using,
})}
/>
)}
</div>
</button>
</Popover>
{!disabled && (advertising || using) && (
<button
className={cx("px-3 py-2 rounded-sm text-white", {
"hover:bg-yellow-200": advertising && !offline,
"hover:bg-blue-400": using && !offline,
"hover:bg-red-400": offline,
})}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
handleSelect(noExitNode)
}}
>
Disable
</button>
)}
</div>
{offline && (
<p className="text-white p-3">
The selected exit node is currently offline. Your internet traffic is
blocked until you disable the exit node or select a different one.
</p>
)}
{pending && (
<p className="text-white p-3">
Pending approval to run as exit node. This device wont be usable as
an exit node until then.
</p>
)}
</div>
)
}
function toSelectedExitNode(data: NodeData): ExitNode {
if (data.AdvertisingExitNode) {
return runAsExitNode
}
if (data.UsingExitNode) {
// TODO(sonia): also use online status
const node = { ...data.UsingExitNode }
if (node.Location) {
// For mullvad nodes, use location as name.
node.Name = `${node.Location.Country}: ${node.Location.City}`
} else {
// Otherwise use node name w/o DNS suffix.
node.Name = trimDNSSuffix(node.Name, data.TailnetName)
}
return node
}
return noExitNode
}
function ExitNodeSelectorInner({
node,
selected,
onSelect,
}: {
node: NodeData
selected: ExitNode
onSelect: (node: ExitNode) => void
}) {
const [filter, setFilter] = useState<string>("")
const { data: exitNodes } = useExitNodes(node, filter)
const listRef = useRef<HTMLDivElement>(null)
const hasNodes = useMemo(
() => exitNodes.find((n) => n.nodes.length > 0),
[exitNodes]
)
return (
<div className="w-[var(--radix-popover-trigger-width)]">
<SearchInput
name="exit-node-search"
className="px-2"
inputClassName="w-full py-3 !h-auto border-none rounded-b-none !ring-0"
autoFocus
autoCorrect="off"
autoComplete="off"
autoCapitalize="off"
placeholder="Search exit nodes…"
value={filter}
onChange={(e) => {
// Jump list to top when search value changes.
listRef.current?.scrollTo(0, 0)
setFilter(e.target.value)
}}
/>
{/* TODO(sonia): use loading spinner when loading useExitNodes */}
<div
ref={listRef}
className="pt-1 border-t border-gray-200 max-h-60 overflow-y-scroll"
>
{hasNodes ? (
exitNodes.map(
(group) =>
group.nodes.length > 0 && (
<div
key={group.id}
className="pb-1 mb-1 border-b last:border-b-0 border-gray-200 last:mb-0"
>
{group.name && (
<div className="px-4 py-2 text-gray-500 text-xs font-medium uppercase tracking-wide">
{group.name}
</div>
)}
{group.nodes.map((n) => (
<ExitNodeSelectorItem
key={`${n.ID}-${n.Name}`}
node={n}
onSelect={() => onSelect(n)}
isSelected={selected.ID === n.ID}
/>
))}
</div>
)
)
) : (
<div className="text-center truncate text-gray-500 p-5">
{filter
? `No exit nodes matching “${filter}`
: "No exit nodes available"}
</div>
)}
</div>
</div>
)
}
function ExitNodeSelectorItem({
node,
isSelected,
onSelect,
}: {
node: ExitNode
isSelected: boolean
onSelect: () => void
}) {
return (
<button
key={node.ID}
className={cx(
"w-full px-4 py-2 flex justify-between items-center cursor-pointer hover:bg-gray-100",
{
"text-gray-400 cursor-not-allowed": !node.Online,
}
)}
onClick={onSelect}
disabled={!node.Online}
>
<div className="w-full">
{node.Location && (
<>
<CountryFlag code={node.Location.CountryCode} />{" "}
</>
)}
<span className="leading-snug">{node.Name}</span>
</div>
{node.Online || <span className="leading-snug">Offline</span>}
{isSelected && <Check className="ml-1" />}
</button>
)
}
function CountryFlag({ code }: { code: string }) {
return (
<>{countryFlags[code.toLowerCase()]}</> || (
<span className="font-medium text-gray-500 text-xs">
{code.toUpperCase()}
</span>
)
)
}
const countryFlags: { [countryCode: string]: string } = {
ad: "🇦🇩",
ae: "🇦🇪",
af: "🇦🇫",
ag: "🇦🇬",
ai: "🇦🇮",
al: "🇦🇱",
am: "🇦🇲",
ao: "🇦🇴",
aq: "🇦🇶",
ar: "🇦🇷",
as: "🇦🇸",
at: "🇦🇹",
au: "🇦🇺",
aw: "🇦🇼",
ax: "🇦🇽",
az: "🇦🇿",
ba: "🇧🇦",
bb: "🇧🇧",
bd: "🇧🇩",
be: "🇧🇪",
bf: "🇧🇫",
bg: "🇧🇬",
bh: "🇧🇭",
bi: "🇧🇮",
bj: "🇧🇯",
bl: "🇧🇱",
bm: "🇧🇲",
bn: "🇧🇳",
bo: "🇧🇴",
bq: "🇧🇶",
br: "🇧🇷",
bs: "🇧🇸",
bt: "🇧🇹",
bv: "🇧🇻",
bw: "🇧🇼",
by: "🇧🇾",
bz: "🇧🇿",
ca: "🇨🇦",
cc: "🇨🇨",
cd: "🇨🇩",
cf: "🇨🇫",
cg: "🇨🇬",
ch: "🇨🇭",
ci: "🇨🇮",
ck: "🇨🇰",
cl: "🇨🇱",
cm: "🇨🇲",
cn: "🇨🇳",
co: "🇨🇴",
cr: "🇨🇷",
cu: "🇨🇺",
cv: "🇨🇻",
cw: "🇨🇼",
cx: "🇨🇽",
cy: "🇨🇾",
cz: "🇨🇿",
de: "🇩🇪",
dj: "🇩🇯",
dk: "🇩🇰",
dm: "🇩🇲",
do: "🇩🇴",
dz: "🇩🇿",
ec: "🇪🇨",
ee: "🇪🇪",
eg: "🇪🇬",
eh: "🇪🇭",
er: "🇪🇷",
es: "🇪🇸",
et: "🇪🇹",
eu: "🇪🇺",
fi: "🇫🇮",
fj: "🇫🇯",
fk: "🇫🇰",
fm: "🇫🇲",
fo: "🇫🇴",
fr: "🇫🇷",
ga: "🇬🇦",
gb: "🇬🇧",
gd: "🇬🇩",
ge: "🇬🇪",
gf: "🇬🇫",
gg: "🇬🇬",
gh: "🇬🇭",
gi: "🇬🇮",
gl: "🇬🇱",
gm: "🇬🇲",
gn: "🇬🇳",
gp: "🇬🇵",
gq: "🇬🇶",
gr: "🇬🇷",
gs: "🇬🇸",
gt: "🇬🇹",
gu: "🇬🇺",
gw: "🇬🇼",
gy: "🇬🇾",
hk: "🇭🇰",
hm: "🇭🇲",
hn: "🇭🇳",
hr: "🇭🇷",
ht: "🇭🇹",
hu: "🇭🇺",
id: "🇮🇩",
ie: "🇮🇪",
il: "🇮🇱",
im: "🇮🇲",
in: "🇮🇳",
io: "🇮🇴",
iq: "🇮🇶",
ir: "🇮🇷",
is: "🇮🇸",
it: "🇮🇹",
je: "🇯🇪",
jm: "🇯🇲",
jo: "🇯🇴",
jp: "🇯🇵",
ke: "🇰🇪",
kg: "🇰🇬",
kh: "🇰🇭",
ki: "🇰🇮",
km: "🇰🇲",
kn: "🇰🇳",
kp: "🇰🇵",
kr: "🇰🇷",
kw: "🇰🇼",
ky: "🇰🇾",
kz: "🇰🇿",
la: "🇱🇦",
lb: "🇱🇧",
lc: "🇱🇨",
li: "🇱🇮",
lk: "🇱🇰",
lr: "🇱🇷",
ls: "🇱🇸",
lt: "🇱🇹",
lu: "🇱🇺",
lv: "🇱🇻",
ly: "🇱🇾",
ma: "🇲🇦",
mc: "🇲🇨",
md: "🇲🇩",
me: "🇲🇪",
mf: "🇲🇫",
mg: "🇲🇬",
mh: "🇲🇭",
mk: "🇲🇰",
ml: "🇲🇱",
mm: "🇲🇲",
mn: "🇲🇳",
mo: "🇲🇴",
mp: "🇲🇵",
mq: "🇲🇶",
mr: "🇲🇷",
ms: "🇲🇸",
mt: "🇲🇹",
mu: "🇲🇺",
mv: "🇲🇻",
mw: "🇲🇼",
mx: "🇲🇽",
my: "🇲🇾",
mz: "🇲🇿",
na: "🇳🇦",
nc: "🇳🇨",
ne: "🇳🇪",
nf: "🇳🇫",
ng: "🇳🇬",
ni: "🇳🇮",
nl: "🇳🇱",
no: "🇳🇴",
np: "🇳🇵",
nr: "🇳🇷",
nu: "🇳🇺",
nz: "🇳🇿",
om: "🇴🇲",
pa: "🇵🇦",
pe: "🇵🇪",
pf: "🇵🇫",
pg: "🇵🇬",
ph: "🇵🇭",
pk: "🇵🇰",
pl: "🇵🇱",
pm: "🇵🇲",
pn: "🇵🇳",
pr: "🇵🇷",
ps: "🇵🇸",
pt: "🇵🇹",
pw: "🇵🇼",
py: "🇵🇾",
qa: "🇶🇦",
re: "🇷🇪",
ro: "🇷🇴",
rs: "🇷🇸",
ru: "🇷🇺",
rw: "🇷🇼",
sa: "🇸🇦",
sb: "🇸🇧",
sc: "🇸🇨",
sd: "🇸🇩",
se: "🇸🇪",
sg: "🇸🇬",
sh: "🇸🇭",
si: "🇸🇮",
sj: "🇸🇯",
sk: "🇸🇰",
sl: "🇸🇱",
sm: "🇸🇲",
sn: "🇸🇳",
so: "🇸🇴",
sr: "🇸🇷",
ss: "🇸🇸",
st: "🇸🇹",
sv: "🇸🇻",
sx: "🇸🇽",
sy: "🇸🇾",
sz: "🇸🇿",
tc: "🇹🇨",
td: "🇹🇩",
tf: "🇹🇫",
tg: "🇹🇬",
th: "🇹🇭",
tj: "🇹🇯",
tk: "🇹🇰",
tl: "🇹🇱",
tm: "🇹🇲",
tn: "🇹🇳",
to: "🇹🇴",
tr: "🇹🇷",
tt: "🇹🇹",
tv: "🇹🇻",
tw: "🇹🇼",
tz: "🇹🇿",
ua: "🇺🇦",
ug: "🇺🇬",
um: "🇺🇲",
us: "🇺🇸",
uy: "🇺🇾",
uz: "🇺🇿",
va: "🇻🇦",
vc: "🇻🇨",
ve: "🇻🇪",
vg: "🇻🇬",
vi: "🇻🇮",
vn: "🇻🇳",
vu: "🇻🇺",
wf: "🇼🇫",
ws: "🇼🇸",
xk: "🇽🇰",
ye: "🇾🇪",
yt: "🇾🇹",
za: "🇿🇦",
zm: "🇿🇲",
zw: "🇿🇼",
}

@ -0,0 +1,376 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import cx from "classnames"
import React, { useCallback, useMemo, useState } from "react"
import ChevronDown from "src/assets/icons/chevron-down.svg?react"
import Eye from "src/assets/icons/eye.svg?react"
import User from "src/assets/icons/user.svg?react"
import { AuthResponse, hasAnyEditCapabilities } from "src/hooks/auth"
import { useTSWebConnected } from "src/hooks/ts-web-connected"
import { NodeData } from "src/types"
import Button from "src/ui/button"
import Popover from "src/ui/popover"
import ProfilePic from "src/ui/profile-pic"
import { assertNever, isHTTPS } from "src/utils/util"
export default function LoginToggle({
node,
auth,
newSession,
}: {
node: NodeData
auth: AuthResponse
newSession: () => Promise<void>
}) {
const [open, setOpen] = useState<boolean>(false)
const { tsWebConnected, checkTSWebConnection } = useTSWebConnected(
auth.serverMode,
node.IPv4
)
return (
<Popover
className="p-3 bg-white rounded-lg shadow flex flex-col max-w-[317px]"
content={
auth.serverMode === "readonly" ? (
<ReadonlyModeContent auth={auth} />
) : auth.serverMode === "login" ? (
<LoginModeContent
auth={auth}
node={node}
tsWebConnected={tsWebConnected}
checkTSWebConnection={checkTSWebConnection}
/>
) : auth.serverMode === "manage" ? (
<ManageModeContent auth={auth} node={node} newSession={newSession} />
) : (
assertNever(auth.serverMode)
)
}
side="bottom"
align="end"
open={open}
onOpenChange={setOpen}
asChild
>
<div>
{auth.authorized ? (
<TriggerWhenManaging auth={auth} open={open} setOpen={setOpen} />
) : (
<TriggerWhenReading auth={auth} open={open} setOpen={setOpen} />
)}
</div>
</Popover>
)
}
/**
* TriggerWhenManaging is displayed as the trigger for the login popover
* when the user has an active authorized managment session.
*/
function TriggerWhenManaging({
auth,
open,
setOpen,
}: {
auth: AuthResponse
open: boolean
setOpen: (next: boolean) => void
}) {
return (
<div
className={cx(
"w-[34px] h-[34px] p-1 rounded-full justify-center items-center inline-flex hover:bg-gray-300",
{
"bg-transparent": !open,
"bg-gray-300": open,
}
)}
>
<button onClick={() => setOpen(!open)}>
<ProfilePic size="medium" url={auth.viewerIdentity?.profilePicUrl} />
</button>
</div>
)
}
/**
* TriggerWhenReading is displayed as the trigger for the login popover
* when the user is currently in read mode (doesn't have an authorized
* management session).
*/
function TriggerWhenReading({
auth,
open,
setOpen,
}: {
auth: AuthResponse
open: boolean
setOpen: (next: boolean) => void
}) {
return (
<button
className={cx(
"pl-3 py-1 bg-gray-700 rounded-full flex justify-start items-center h-[34px]",
{ "pr-1": auth.viewerIdentity, "pr-3": !auth.viewerIdentity }
)}
onClick={() => setOpen(!open)}
>
<Eye />
<div className="text-white leading-snug ml-2 mr-1">Viewing</div>
<ChevronDown className="stroke-white w-[15px] h-[15px]" />
{auth.viewerIdentity && (
<ProfilePic
className="ml-2"
size="medium"
url={auth.viewerIdentity.profilePicUrl}
/>
)}
</button>
)
}
/**
* PopoverContentHeader is the header for the login popover.
*/
function PopoverContentHeader({ auth }: { auth: AuthResponse }) {
return (
<div className="text-black text-sm font-medium leading-tight mb-1">
{auth.authorized ? "Managing" : "Viewing"}
{auth.viewerIdentity && ` as ${auth.viewerIdentity.loginName}`}
</div>
)
}
/**
* PopoverContentFooter is the footer for the login popover.
*/
function PopoverContentFooter({ auth }: { auth: AuthResponse }) {
return auth.viewerIdentity ? (
<>
<hr className="my-2" />
<div className="flex items-center">
<User className="flex-shrink-0" />
<p className="text-gray-500 text-xs ml-2">
We recognize you because you are accessing this page from{" "}
<span className="font-medium">
{auth.viewerIdentity.nodeName || auth.viewerIdentity.nodeIP}
</span>
</p>
</div>
</>
) : null
}
/**
* ReadonlyModeContent is the body of the login popover when the web
* client is being run in "readonly" server mode.
*/
function ReadonlyModeContent({ auth }: { auth: AuthResponse }) {
return (
<>
<PopoverContentHeader auth={auth} />
<p className="text-gray-500 text-xs">
This web interface is running in read-only mode.{" "}
<a
href="https://tailscale.com/s/web-client-read-only"
className="text-blue-700"
target="_blank"
rel="noreferrer"
>
Learn more &rarr;
</a>
</p>
<PopoverContentFooter auth={auth} />
</>
)
}
/**
* LoginModeContent is the body of the login popover when the web
* client is being run in "login" server mode.
*/
function LoginModeContent({
node,
auth,
tsWebConnected,
checkTSWebConnection,
}: {
node: NodeData
auth: AuthResponse
tsWebConnected: boolean
checkTSWebConnection: () => void
}) {
const https = isHTTPS()
// We can't run the ts web connection test when the webpage is loaded
// over HTTPS. So in this case, we default to presenting a login button
// with some helper text reminding the user to check their connection
// themselves.
const hasACLAccess = https || tsWebConnected
const hasEditCaps = useMemo(() => {
if (!auth.viewerIdentity) {
// If not connected to login client over tailscale, we won't know the viewer's
// identity. So we must assume they may be able to edit something and have the
// management client handle permissions once the user gets there.
return true
}
return hasAnyEditCapabilities(auth)
}, [auth])
const handleLogin = useCallback(() => {
// Must be connected over Tailscale to log in.
// Send user to Tailscale IP and start check mode
const manageURL = `http://${node.IPv4}:5252/?check=now`
if (window.self !== window.top) {
// If we're inside an iframe, open management client in new window.
window.open(manageURL, "_blank")
} else {
window.location.href = manageURL
}
}, [node.IPv4])
return (
<div
onMouseEnter={
hasEditCaps && !hasACLAccess ? checkTSWebConnection : undefined
}
>
<PopoverContentHeader auth={auth} />
{!hasACLAccess || !hasEditCaps ? (
<>
<p className="text-gray-500 text-xs">
{!hasEditCaps ? (
// ACLs allow access, but user isn't allowed to edit any features,
// restricted to readonly. No point in sending them over to the
// tailscaleIP:5252 address.
<>
You dont have permission to make changes to this device, but
you can view most of its details.
</>
) : !node.ACLAllowsAnyIncomingTraffic ? (
// Tailnet ACLs don't allow access to anyone.
<>
The current tailnet policy file does not allow connecting to
this device.
</>
) : (
// ACLs don't allow access to this user specifically.
<>
Cannot access this devices Tailscale IP. Make sure you are
connected to your tailnet, and that your policy file allows
access.
</>
)}{" "}
<a
href="https://tailscale.com/s/web-client-access"
className="text-blue-700"
target="_blank"
rel="noreferrer"
>
Learn more &rarr;
</a>
</p>
</>
) : (
// User can connect to Tailcale IP; sign in when ready.
<>
<p className="text-gray-500 text-xs">
You can see most of this devices details. To make changes, you need
to sign in.
</p>
{https && (
// we don't know if the user can connect over TS, so
// provide extra tips in case they have trouble.
<p className="text-gray-500 text-xs font-semibold pt-2">
Make sure you are connected to your tailnet, and that your policy
file allows access.
</p>
)}
<SignInButton auth={auth} onClick={handleLogin} />
</>
)}
<PopoverContentFooter auth={auth} />
</div>
)
}
/**
* ManageModeContent is the body of the login popover when the web
* client is being run in "manage" server mode.
*/
function ManageModeContent({
auth,
newSession,
}: {
node: NodeData
auth: AuthResponse
newSession: () => void
}) {
const handleLogin = useCallback(() => {
if (window.self !== window.top) {
// If we're inside an iframe, start session in new window.
let url = new URL(window.location.href)
url.searchParams.set("check", "now")
window.open(url, "_blank")
} else {
newSession()
}
}, [newSession])
const hasAnyPermissions = useMemo(() => hasAnyEditCapabilities(auth), [auth])
return (
<>
<PopoverContentHeader auth={auth} />
{!auth.authorized &&
(hasAnyPermissions ? (
// User is connected over Tailscale, but needs to complete check mode.
<>
<p className="text-gray-500 text-xs">
To make changes, sign in to confirm your identity. This extra step
helps us keep your device secure.
</p>
<SignInButton auth={auth} onClick={handleLogin} />
</>
) : (
// User is connected over tailscale, but doesn't have permission to manage.
<p className="text-gray-500 text-xs">
You dont have permission to make changes to this device, but you
can view most of its details.{" "}
<a
href="https://tailscale.com/s/web-client-access"
className="text-blue-700"
target="_blank"
rel="noreferrer"
>
Learn more &rarr;
</a>
</p>
))}
<PopoverContentFooter auth={auth} />
</>
)
}
function SignInButton({
auth,
onClick,
}: {
auth: AuthResponse
onClick: () => void
}) {
return (
<Button
className={cx("text-center w-full mt-2", {
"mb-2": auth.viewerIdentity,
})}
intent="primary"
sizeVariant="small"
onClick={onClick}
>
{auth.viewerIdentity ? "Sign in to confirm identity" : "Sign in"}
</Button>
)
}

@ -0,0 +1,65 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import cx from "classnames"
import React from "react"
import { isTailscaleIPv6 } from "src/utils/util"
type Props = {
ip: string
className?: string
}
/**
* NiceIP displays IP addresses with nice truncation.
*/
export default function NiceIP(props: Props) {
const { ip, className } = props
if (!isTailscaleIPv6(ip)) {
return <span className={className}>{ip}</span>
}
const [trimmable, untrimmable] = splitIPv6(ip)
return (
<span
className={cx("inline-flex justify-start min-w-0 max-w-full", className)}
>
{trimmable.length > 0 && (
<span className="truncate w-fit flex-shrink">{trimmable}</span>
)}
<span className="flex-grow-0 flex-shrink-0">{untrimmable}</span>
</span>
)
}
/**
* Split an IPv6 address into two pieces, to help with truncating the middle.
* Only exported for testing purposes. Do not use.
*/
export function splitIPv6(ip: string): [string, string] {
// We want to split the IPv6 address into segments, but not remove the delimiter.
// So we inject an invalid IPv6 character ("|") as a delimiter into the string,
// then split on that.
const parts = ip.replace(/(:{1,2})/g, "|$1").split("|")
// Then we find the number of end parts that fits within the character limit,
// and join them back together.
const characterLimit = 12
let characterCount = 0
let idxFromEnd = 1
for (let i = parts.length - 1; i >= 0; i--) {
const part = parts[i]
if (characterCount + part.length > characterLimit) {
break
}
characterCount += part.length
idxFromEnd++
}
const start = parts.slice(0, -idxFromEnd).join("")
const end = parts.slice(-idxFromEnd).join("")
return [start, end]
}

@ -0,0 +1,67 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import React from "react"
import { VersionInfo } from "src/types"
import Button from "src/ui/button"
import Card from "src/ui/card"
import { useLocation } from "wouter"
export function UpdateAvailableNotification({
details,
}: {
details: VersionInfo
}) {
const [, setLocation] = useLocation()
return (
<Card>
<h2 className="mb-2">
Update available{" "}
{details.LatestVersion && `(v${details.LatestVersion})`}
</h2>
<p className="text-sm mb-1 mt-1">
{details.LatestVersion
? `Version ${details.LatestVersion}`
: "A new update"}{" "}
is now available. <ChangelogText version={details.LatestVersion} />
</p>
<Button
className="mt-3 inline-block"
sizeVariant="small"
onClick={() => setLocation("/update")}
>
Update now
</Button>
</Card>
)
}
// isStableTrack takes a Tailscale version string
// of form X.Y.Z (or vX.Y.Z) and returns whether
// it is a stable release (even value of Y)
// or unstable (odd value of Y).
// eg. isStableTrack("1.48.0") === true
// eg. isStableTrack("1.49.112") === false
function isStableTrack(ver: string): boolean {
const middle = ver.split(".")[1]
if (middle && Number(middle) % 2 === 0) {
return true
}
return false
}
export function ChangelogText({ version }: { version?: string }) {
if (!version || !isStableTrack(version)) {
return null
}
return (
<>
Check out the{" "}
<a href="https://tailscale.com/changelog/" className="link">
release notes
</a>{" "}
to find out whats new!
</>
)
}

@ -0,0 +1,249 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import cx from "classnames"
import React from "react"
import { useAPI } from "src/api"
import ACLTag from "src/components/acl-tag"
import * as Control from "src/components/control-components"
import NiceIP from "src/components/nice-ip"
import { UpdateAvailableNotification } from "src/components/update-available"
import { AuthResponse, canEdit } from "src/hooks/auth"
import { NodeData } from "src/types"
import Button from "src/ui/button"
import Card from "src/ui/card"
import Dialog from "src/ui/dialog"
import QuickCopy from "src/ui/quick-copy"
import { useLocation } from "wouter"
export default function DeviceDetailsView({
node,
auth,
}: {
node: NodeData
auth: AuthResponse
}) {
return (
<>
<h1 className="mb-10">Device details</h1>
<div className="flex flex-col gap-4">
<Card noPadding className="-mx-5 p-5 details-card">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<h1>{node.DeviceName}</h1>
<div
className={cx("w-2.5 h-2.5 rounded-full", {
"bg-emerald-500": node.Status === "Running",
"bg-gray-300": node.Status !== "Running",
})}
/>
</div>
{canEdit("account", auth) && <DisconnectDialog />}
</div>
</Card>
{node.Features["auto-update"] &&
canEdit("account", auth) &&
node.ClientVersion &&
!node.ClientVersion.RunningLatest && (
<UpdateAvailableNotification details={node.ClientVersion} />
)}
<Card noPadding className="-mx-5 p-5 details-card">
<h2 className="mb-2">General</h2>
<table>
<tbody>
<tr className="flex">
<td>Managed by</td>
<td className="flex gap-1 flex-wrap">
{node.IsTagged
? node.Tags.map((t) => <ACLTag key={t} tag={t} />)
: node.Profile?.DisplayName}
</td>
</tr>
<tr>
<td>Machine name</td>
<td>
<QuickCopy
primaryActionValue={node.DeviceName}
primaryActionSubject="machine name"
>
{node.DeviceName}
</QuickCopy>
</td>
</tr>
<tr>
<td>OS</td>
<td>{node.OS}</td>
</tr>
<tr>
<td>ID</td>
<td>
<QuickCopy
primaryActionValue={node.ID}
primaryActionSubject="ID"
>
{node.ID}
</QuickCopy>
</td>
</tr>
<tr>
<td>Tailscale version</td>
<td>{node.IPNVersion}</td>
</tr>
<tr>
<td>Key expiry</td>
<td>
{node.KeyExpired
? "Expired"
: // TODO: present as relative expiry (e.g. "5 months from now")
node.KeyExpiry
? new Date(node.KeyExpiry).toLocaleString()
: "No expiry"}
</td>
</tr>
</tbody>
</table>
</Card>
<Card noPadding className="-mx-5 p-5 details-card">
<h2 className="mb-2">Addresses</h2>
<table>
<tbody>
<tr>
<td>Tailscale IPv4</td>
<td>
<QuickCopy
primaryActionValue={node.IPv4}
primaryActionSubject="IPv4 address"
>
{node.IPv4}
</QuickCopy>
</td>
</tr>
<tr>
<td>Tailscale IPv6</td>
<td>
<QuickCopy
primaryActionValue={node.IPv6}
primaryActionSubject="IPv6 address"
>
<NiceIP ip={node.IPv6} />
</QuickCopy>
</td>
</tr>
<tr>
<td>Short domain</td>
<td>
<QuickCopy
primaryActionValue={node.DeviceName}
primaryActionSubject="short domain"
>
{node.DeviceName}
</QuickCopy>
</td>
</tr>
<tr>
<td>Full domain</td>
<td>
<QuickCopy
primaryActionValue={`${node.DeviceName}.${node.TailnetName}`}
primaryActionSubject="full domain"
>
{node.DeviceName}.{node.TailnetName}
</QuickCopy>
</td>
</tr>
</tbody>
</table>
</Card>
<Card noPadding className="-mx-5 p-5 details-card">
<h2 className="mb-2">Debug</h2>
<table>
<tbody>
<tr>
<td>TUN Mode</td>
<td>{node.TUNMode ? "Yes" : "No"}</td>
</tr>
{node.IsSynology && (
<tr>
<td>Synology Version</td>
<td>{node.DSMVersion}</td>
</tr>
)}
</tbody>
</table>
</Card>
<footer className="text-gray-500 text-sm leading-tight text-center">
<Control.AdminContainer node={node}>
Want even more details? Visit{" "}
<Control.AdminLink node={node} path={`/machines/${node.IPv4}`}>
this devices page
</Control.AdminLink>{" "}
in the admin console.
</Control.AdminContainer>
<p className="mt-12">
<a
className="link"
href={node.LicensesURL}
target="_blank"
rel="noreferrer"
>
Acknowledgements
</a>{" "}
·{" "}
<a
className="link"
href="https://tailscale.com/privacy-policy/"
target="_blank"
rel="noreferrer"
>
Privacy Policy
</a>{" "}
·{" "}
<a
className="link"
href="https://tailscale.com/terms/"
target="_blank"
rel="noreferrer"
>
Terms of Service
</a>
</p>
<p className="my-2">
WireGuard is a registered trademark of Jason A. Donenfeld.
</p>
<p>
© {new Date().getFullYear()} Tailscale Inc. All rights reserved.
Tailscale is a registered trademark of Tailscale Inc.
</p>
</footer>
</div>
</>
)
}
function DisconnectDialog() {
const api = useAPI()
const [, setLocation] = useLocation()
return (
<Dialog
className="max-w-md"
title="Log out"
trigger={<Button sizeVariant="small">Log out</Button>}
>
<Dialog.Form
cancelButton
submitButton="Log out"
destructive
onSubmit={() => {
api({ action: "logout" })
setLocation("/disconnected")
}}
>
Logging out of this device will disconnect it from your tailnet and
expire its node key. You wont be able to use this web interface until
you re-authenticate the device from either the Tailscale app or the
Tailscale command line interface.
</Dialog.Form>
</Dialog>
)
}

@ -0,0 +1,21 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import React from "react"
import TailscaleIcon from "src/assets/icons/tailscale-icon.svg?react"
/**
* DisconnectedView is rendered after node logout.
*/
export default function DisconnectedView() {
return (
<>
<TailscaleIcon className="mx-auto" />
<p className="mt-12 text-center text-text-muted">
You logged out of this device. To reconnect it you will have to
re-authenticate the device from either the Tailscale app or the
Tailscale command line interface.
</p>
</>
)
}

@ -0,0 +1,189 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
import cx from "classnames"
import React, { useMemo } from "react"
import { apiFetch } from "src/api"
import ArrowRight from "src/assets/icons/arrow-right.svg?react"
import Machine from "src/assets/icons/machine.svg?react"
import AddressCard from "src/components/address-copy-card"
import ExitNodeSelector from "src/components/exit-node-selector"
import { AuthResponse, canEdit } from "src/hooks/auth"
import { NodeData } from "src/types"
import Card from "src/ui/card"
import { pluralize } from "src/utils/util"
import { Link, useLocation } from "wouter"
export default function HomeView({
node,
auth,
}: {
node: NodeData
auth: AuthResponse
}) {
const [allSubnetRoutes, pendingSubnetRoutes] = useMemo(
() => [
node.AdvertisedRoutes?.length,
node.AdvertisedRoutes?.filter((r) => !r.Approved).length,
],
[node.AdvertisedRoutes]
)
return (
<div className="mb-12 w-full">
<h2 className="mb-3">This device</h2>
<Card noPadding className="-mx-5 p-5 mb-9">
<div className="flex justify-between items-center text-lg mb-5">
<Link className="flex items-center" to="/details">
<div className="w-10 h-10 bg-gray-100 rounded-full justify-center items-center inline-flex">
<Machine />
</div>
<div className="ml-3">
<div className="text-gray-800 text-lg font-medium leading-snug">
{node.DeviceName}
</div>
<p className="text-gray-500 text-sm leading-[18.20px] flex items-center gap-2">
<span
className={cx("w-2 h-2 inline-block rounded-full", {
"bg-green-300": node.Status === "Running",
"bg-gray-300": node.Status !== "Running",
})}
/>
{node.Status === "Running" ? "Connected" : "Offline"}
</p>
</div>
</Link>
<AddressCard
className="-mr-2"
triggerClassName="relative text-gray-800 text-lg leading-[25.20px]"
v4Address={node.IPv4}
v6Address={node.IPv6}
shortDomain={node.DeviceName}
fullDomain={`${node.DeviceName}.${node.TailnetName}`}
/>
</div>
{(node.Features["advertise-exit-node"] ||
node.Features["use-exit-node"]) && (
<ExitNodeSelector
className="mb-5"
node={node}
disabled={!canEdit("exitnodes", auth)}
/>
)}
<Link
className="link font-medium"
to="/details"
onClick={() => apiFetch("/device-details-click", "POST")}
>
View device details &rarr;
</Link>
</Card>
<h2 className="mb-3">Settings</h2>
<div className="grid gap-3">
{node.Features["advertise-routes"] && (
<SettingsCard
link="/subnets"
title="Subnet router"
body="Add devices to your tailnet without installing Tailscale on them."
badge={
allSubnetRoutes
? {
text: `${allSubnetRoutes} ${pluralize(
"route",
"routes",
allSubnetRoutes
)}`,
}
: undefined
}
footer={
pendingSubnetRoutes
? `${pendingSubnetRoutes} ${pluralize(
"route",
"routes",
pendingSubnetRoutes
)} pending approval`
: undefined
}
/>
)}
{node.Features["ssh"] && (
<SettingsCard
link="/ssh"
title="Tailscale SSH server"
body="Run a Tailscale SSH server on this device and allow other devices in your tailnet to SSH into it."
badge={
node.RunningSSHServer
? {
text: "Running",
icon: <div className="w-2 h-2 bg-green-300 rounded-full" />,
}
: undefined
}
/>
)}
{/* TODO(sonia,will): hiding unimplemented settings pages until implemented */}
{/* <SettingsCard
link="/serve"
title="Share local content"
body="Share local ports, services, and content to your Tailscale network or to the broader internet."
/> */}
</div>
</div>
)
}
function SettingsCard({
title,
link,
body,
badge,
footer,
className,
}: {
title: string
link: string
body: string
badge?: {
text: string
icon?: JSX.Element
}
footer?: string
className?: string
}) {
const [, setLocation] = useLocation()
return (
<button onClick={() => setLocation(link)}>
<Card noPadding className={cx("-mx-5 p-5", className)}>
<div className="flex justify-between items-center">
<div>
<div className="flex gap-2">
<p className="text-gray-800 font-medium leading-tight mb-2">
{title}
</p>
{badge && (
<div className="h-5 px-2 bg-gray-100 rounded-full flex items-center gap-2">
{badge.icon}
<div className="text-gray-500 text-xs font-medium">
{badge.text}
</div>
</div>
)}
</div>
<p className="text-gray-500 text-sm leading-tight">{body}</p>
</div>
<div>
<ArrowRight className="ml-3" />
</div>
</div>
{footer && (
<>
<hr className="my-3" />
<div className="text-gray-500 text-sm leading-tight">{footer}</div>
</>
)}
</Card>
</button>
)
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save