Compare commits

...

105 Commits

Author SHA1 Message Date
Andrew Dunham
b080e6bb2d WIP
Change-Id: I5295d47102d879f29f0a6818481e8b65eafd02dd
2023-03-13 14:56:38 -04:00
Maisem Ali
223713d4a1 tailcfg,all: add and use Node.IsTagged()
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2023-03-13 08:44:25 -07:00
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
2023-03-12 12:38:38 -04:00
Maisem Ali
958c89470b tsnet: add CertDomains helper (#7533)
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2023-03-11 16:12:57 -05:00
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>
2023-03-11 16:07:22 -05:00
Maisem Ali
3ff44b2307 ipn: add Funnel port check from nodeAttr
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2023-03-11 11:20:52 -08:00
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>
2023-03-11 10:34:52 -08:00
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>
2023-03-10 15:22:27 -08:00
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
2023-03-10 13:47:34 -05:00
License Updater
920de86cee licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
2023-03-09 21:46:04 -08:00
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>
2023-03-09 14:31:20 -08:00
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>
2023-03-09 14:22:11 -08:00
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>
2023-03-09 13:52:37 -08:00
Tom DNetto
92fc243755 cmd/tailscale: annotate tailnet-lock keys which wrap pre-auth keys
Signed-off-by: Tom DNetto <tom@tailscale.com>
2023-03-09 11:21:39 -10:00
Tom DNetto
3471fbf8dc cmd/tailscale: surface node-key for locked out tailnet-lock peers
Signed-off-by: Tom DNetto <tom@tailscale.com>
2023-03-09 11:06:23 -10:00
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>
2023-03-09 12:53:00 -08:00
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>
2023-03-09 12:04:38 -08:00
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>
2023-03-09 11:36:44 -08:00
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>
2023-03-09 11:13:09 -08:00
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>
2023-03-09 10:38:45 -08:00
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>
2023-03-09 10:22:55 -08:00
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>
2023-03-08 15:39:04 -08:00
Tom DNetto
ce99474317 all: implement preauth-key support with tailnet lock
Signed-off-by: Tom DNetto <tom@tailscale.com>
2023-03-08 11:56:46 -10:00
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>
2023-03-08 13:39:30 -08:00
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>
2023-03-08 09:47:44 -10:00
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
2023-03-07 19:29:55 -05:00
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>
2023-03-07 15:48:49 -08:00
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>
2023-03-07 14:30:19 -08:00
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>
2023-03-07 11:51:36 -08:00
David Anderson
5b68dcc8c1 go.mod.sri: update for toolchain change.
Signed-off-by: David Anderson <danderson@tailscale.com>
2023-03-07 11:40:29 -08:00
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>
2023-03-07 11:36:34 -08:00
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
2023-03-07 13:53:03 -05:00
David Crawshaw
9245d813c6 tsnet: explicit message for panic seen in CI
Updates #7488

Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2023-03-07 10:22:50 -08:00
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
2023-03-07 11:46:02 -05:00
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>
2023-03-06 20:53:46 -08:00
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>
2023-03-06 19:29:01 -08:00
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>
2023-03-06 18:05:51 -08:00
Joe Tsai
9112e78925 tstime: add Sleep (#7480)
Sleep is an interruptible sleep variation.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
2023-03-06 17:40:38 -08:00
License Updater
3b18e65c6a licenses: update android licenses
Signed-off-by: License Updater <noreply@tailscale.com>
2023-03-06 16:03:27 -08:00
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>
2023-03-06 15:54:35 -08:00
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>
2023-03-06 16:08:13 -07:00
Tom DNetto
2263d9c44b cmd/tsconnect: pop CTA to make everything work with tailnet lock
Signed-off-by: Tom DNetto <tom@tailscale.com>
2023-03-06 10:07:20 -10:00
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>
2023-03-06 09:00:09 -08:00
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
2023-03-06 10:59:47 -05:00
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>
2023-03-05 14:08:34 -08:00
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>
2023-03-05 12:40:13 -08:00
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>
2023-03-05 09:05:43 -08:00
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
2023-03-05 10:20:04 -05:00
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
2023-03-04 22:10:14 -05:00
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
2023-03-04 16:18:26 -05:00
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
2023-03-04 16:04:23 -05:00
Andrew Dunham
69f9c17555 ipn/localapi: fix panic after handler returns
Change-Id: I612f9ebf78d962e094bff908670b3ffd89f756e5
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
2023-03-04 16:03:36 -05:00
Maisem Ali
1a30b2d73f all: use tstest.Replace more
Signed-off-by: Maisem Ali <maisem@tailscale.com>
2023-03-04 12:24:55 -08:00
License Updater
57a44846ae licenses: update win/apple licenses
Signed-off-by: License Updater <noreply@tailscale.com>
2023-03-04 07:13:20 -08:00
Andrew Dunham
a9c17dbf93 ipn/ipnlocal: reject unmasked routes
Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: Ic804efd24f5f536de1f2c910de3a24372d48d54d
2023-03-03 22:39:01 -05:00
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
2023-03-03 20:52:57 -05:00
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>
2023-03-03 17:02:33 -08:00
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
2023-03-03 18:36:07 -05:00
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
2023-03-03 16:25:48 -05:00
Tom DNetto
88c7d19d54 tka: compact TKA storage on startup
Signed-off-by: Tom DNetto <tom@tailscale.com>
2023-03-03 10:09:26 -10:00
Tom DNetto
e2d652ec4d ipn,cmd/tailscale: implement resigning nodes on tka key removal
Signed-off-by: Tom DNetto <tom@tailscale.com>
2023-03-03 10:09:05 -10:00
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
2023-03-03 14:21:38 -05:00
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>
2023-03-03 08:37:14 -08:00
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>
2023-03-02 21:33:02 -08:00
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.
2023-03-02 23:36:12 -05:00
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
2023-03-02 22:55:58 -05:00
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>
2023-03-02 17:20:45 -08:00
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>
2023-03-02 14:39:10 -08:00
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>
2023-03-02 13:18:04 -08:00
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>
2023-03-02 11:36:06 -08:00
Flakes Updater
5eb8a2a86a go.mod.sri: update SRI hash for go.mod changes
Signed-off-by: Flakes Updater <noreply@tailscale.com>
2023-03-02 11:02:05 -08:00
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
2023-03-02 13:56:37 -05:00
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>
2023-03-01 18:00:06 -08:00
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>
2023-03-01 17:51:17 -08:00
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>
2023-03-01 17:16:31 -08:00
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>
2023-03-01 17:16:31 -08:00
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>
2023-03-01 15:45:12 -07:00
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>
2023-03-01 16:39:15 -05:00
Tom DNetto
ff168a806e tka: implement compaction logic
Signed-off-by: Tom DNetto <tom@tailscale.com>
2023-03-01 10:50:07 -10:00
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>
2023-03-01 15:23:29 -05:00
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>
2023-03-01 12:18:23 -08:00
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>
2023-03-01 12:09:31 -08:00
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>
2023-03-01 14:02:28 -05:00
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>
2023-02-28 19:00:11 -08:00
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>
2023-02-28 19:00:00 -08:00
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>
2023-02-28 15:36:33 -08:00
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>
2023-02-28 13:52:32 -08:00
Vladimir Pouzanov
e3211ff88b Add support for OAuth tokens #7394 (#7393)
Signed-off-by: Vladimir Pouzanov <farcaller@gmail.com>
2023-02-27 18:05:24 -08:00
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>
2023-02-27 15:19:33 -08:00
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>
2023-02-27 09:39:49 -08:00
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>
2023-02-26 11:29:45 -08:00
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>
2023-02-25 17:16:31 -08:00
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>
2023-02-25 17:03:16 -08:00
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>
2023-02-25 15:46:34 -08:00
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>
2023-02-24 21:10:43 -08:00
David Anderson
04be5ea725 release/dist/cli: default to "all" for list if no filters given
Signed-off-by: David Anderson <danderson@tailscale.com>
2023-02-24 15:26:46 -08:00
Jordan Whited
d4122c9f0a cmd/tailscale/cli: fix TestUpdatePrefs over Tailscale SSH (#7374)
Fixes #7373

Signed-off-by: Jordan Whited <jordan@tailscale.com>
2023-02-24 15:26:23 -08:00
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>
2023-02-24 23:00:22 +00:00
David Anderson
0ab6a7e7f5 .github/workflows: try to make the merge queue actually run CI
Signed-off-by: David Anderson <danderson@tailscale.com>
2023-02-24 22:31:47 +00:00
David Anderson
587eb32a83 release/dist: add forgotten license headers
Signed-off-by: David Anderson <danderson@tailscale.com>
2023-02-24 22:21:28 +00:00
David Anderson
cf74ee49ee release/dist/cli: factor out the CLI boilerplace from cmd/dist
Signed-off-by: David Anderson <danderson@tailscale.com>
2023-02-24 22:21:28 +00:00
David Anderson
fc4b25d9fd release: open-source release build logic for unix packages
Updates tailscale/corp#9221

Signed-off-by: David Anderson <danderson@tailscale.com>
2023-02-24 21:31:09 +00:00
David Crawshaw
44e027abca tsnet: add data transfer test
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2023-02-24 19:18:32 +00:00
David Crawshaw
46467e39c2 logtail: allow multiple calls to Shutdown
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2023-02-24 19:18:32 +00:00
David Crawshaw
daa2f1c66e tsnet: add Up method to block until ready
Signed-off-by: David Crawshaw <crawshaw@tailscale.com>
2023-02-24 18:57:55 +00:00
176 changed files with 9491 additions and 2124 deletions

View File

@@ -18,6 +18,7 @@ on:
# The branches below must be a subset of the branches above
branches: [ main ]
merge_group:
branches: [ main ]
schedule:
- cron: '31 14 * * 5'

View File

@@ -42,7 +42,7 @@ jobs:
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
uses: tibdex/github-app-token@b62528385c34dbc9f38e5f4225ac829252d1ea92 # v1.8.0
id: generate-token
with:
app_id: ${{ secrets.LICENSING_APP_ID }}

View File

@@ -25,6 +25,8 @@ on:
branches:
- "*"
merge_group:
branches:
- "main"
concurrency:
# For PRs, later CI runs preempt previous ones. e.g. a force push on a PR
@@ -402,3 +404,27 @@ jobs:
}
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
- 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) }}

View File

@@ -27,7 +27,7 @@ jobs:
run: ./update-flake.sh
- name: Get access token
uses: tibdex/github-app-token@f717b5ecd4534d3c4df4ce9b5c1c2214f0f7cd06 # v1.6.0
uses: tibdex/github-app-token@b62528385c34dbc9f38e5f4225ac829252d1ea92 # v1.8.0
id: generate-token
with:
app_id: ${{ secrets.LICENSING_APP_ID }}

1
.gitignore vendored
View File

@@ -36,3 +36,4 @@ cmd/tailscaled/tailscaled
.direnv/
/gocross
/dist

1867
api.md

File diff suppressed because it is too large Load Diff

View File

@@ -36,6 +36,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
@@ -367,6 +368,34 @@ func (lc *LocalClient) DebugAction(ctx context.Context, action string) error {
return nil
}
// 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.
func (lc *LocalClient) DebugPortmap(ctx context.Context, duration time.Duration, ty, gwSelf string) (io.ReadCloser, error) {
vals := make(url.Values)
vals.Set("duration", duration.String())
vals.Set("type", ty)
if gwSelf != "" {
vals.Set("gateway_and_self", gwSelf)
}
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 {
@@ -821,6 +850,30 @@ 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) error {
var b bytes.Buffer
@@ -858,6 +911,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{}

View File

@@ -6,138 +6,28 @@
package main
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"tailscale.com/kube"
"tailscale.com/tailcfg"
"tailscale.com/util/multierr"
)
// checkSecretPermissions checks the secret access permissions of the current
// pod. It returns an error if the basic permissions tailscale needs are
// missing, and reports whether the patch permission is additionally present.
//
// Errors encountered during the access checking process are logged, but ignored
// so that the pod tries to fail alive if the permissions exist and there's just
// something wrong with SelfSubjectAccessReviews. There shouldn't be, pods
// should always be able to use SSARs to assess their own permissions, but since
// we didn't use to check permissions this way we'll be cautious in case some
// old version of k8s deviates from the current behavior.
func checkSecretPermissions(ctx context.Context, secretName string) (canPatch bool, err error) {
var errs []error
for _, verb := range []string{"get", "update"} {
ok, err := checkPermission(ctx, verb, secretName)
if err != nil {
log.Printf("error checking %s permission on secret %s: %v", verb, secretName, err)
} else if !ok {
errs = append(errs, fmt.Errorf("missing %s permission on secret %q", verb, secretName))
}
}
if len(errs) > 0 {
return false, multierr.New(errs...)
}
ok, err := checkPermission(ctx, "patch", secretName)
if err != nil {
log.Printf("error checking patch permission on secret %s: %v", secretName, err)
return false, nil
}
return ok, nil
}
// checkPermission reports whether the current pod has permission to use the
// given verb (e.g. get, update, patch) on secretName.
func checkPermission(ctx context.Context, verb, secretName string) (bool, error) {
sar := map[string]any{
"apiVersion": "authorization.k8s.io/v1",
"kind": "SelfSubjectAccessReview",
"spec": map[string]any{
"resourceAttributes": map[string]any{
"namespace": kubeNamespace,
"verb": verb,
"resource": "secrets",
"name": secretName,
},
},
}
bs, err := json.Marshal(sar)
if err != nil {
return false, err
}
req, err := http.NewRequest("POST", "/apis/authorization.k8s.io/v1/selfsubjectaccessreviews", bytes.NewReader(bs))
if err != nil {
return false, err
}
resp, err := doKubeRequest(ctx, req)
if err != nil {
return false, err
}
defer resp.Body.Close()
bs, err = io.ReadAll(resp.Body)
if err != nil {
return false, err
}
var res struct {
Status struct {
Allowed bool `json:"allowed"`
} `json:"status"`
}
if err := json.Unmarshal(bs, &res); err != nil {
return false, err
}
return res.Status.Allowed, nil
}
// findKeyInKubeSecret inspects the kube secret secretName for a data
// field called "authkey", and returns its value if present.
func findKeyInKubeSecret(ctx context.Context, secretName string) (string, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("/api/v1/namespaces/%s/secrets/%s", kubeNamespace, secretName), nil)
s, err := kc.GetSecret(ctx, secretName)
if err != nil {
return "", err
}
resp, err := doKubeRequest(ctx, req)
if err != nil {
if resp != nil && resp.StatusCode == http.StatusNotFound {
// Kube secret doesn't exist yet, can't have an authkey.
return "", nil
}
return "", err
ak, ok := s.Data["authkey"]
if !ok {
return "", nil
}
defer resp.Body.Close()
bs, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
// We use a map[string]any here rather than import corev1.Secret,
// because we only do very limited things to the secret, and
// importing corev1 adds 12MiB to the compiled binary.
var s map[string]any
if err := json.Unmarshal(bs, &s); err != nil {
return "", err
}
if d, ok := s["data"].(map[string]any); ok {
if v, ok := d["authkey"].(string); ok {
bs, err := base64.StdEncoding.DecodeString(v)
if err != nil {
return "", err
}
return string(bs), nil
}
}
return "", nil
return string(ak), nil
}
// storeDeviceInfo writes deviceID into the "device_id" data field of the kube
@@ -145,65 +35,38 @@ func findKeyInKubeSecret(ctx context.Context, secretName string) (string, error)
func storeDeviceInfo(ctx context.Context, secretName string, deviceID tailcfg.StableNodeID, fqdn string) error {
// First check if the secret exists at all. Even if running on
// kubernetes, we do not necessarily store state in a k8s secret.
req, err := http.NewRequest("GET", fmt.Sprintf("/api/v1/namespaces/%s/secrets/%s", kubeNamespace, secretName), nil)
if err != nil {
return err
}
resp, err := doKubeRequest(ctx, req)
if err != nil {
if resp != nil && resp.StatusCode >= 400 && resp.StatusCode <= 499 {
// Assume the secret doesn't exist, or we don't have
// permission to access it.
return nil
if _, err := kc.GetSecret(ctx, secretName); err != nil {
if s, ok := err.(*kube.Status); ok {
if s.Code >= 400 && s.Code <= 499 {
// Assume the secret doesn't exist, or we don't have
// permission to access it.
return nil
}
}
return err
}
m := map[string]map[string]string{
"stringData": {
"device_id": string(deviceID),
"device_fqdn": fqdn,
m := &kube.Secret{
Data: map[string][]byte{
"device_id": []byte(deviceID),
"device_fqdn": []byte(fqdn),
},
}
var b bytes.Buffer
if err := json.NewEncoder(&b).Encode(m); err != nil {
return err
}
req, err = http.NewRequest("PATCH", fmt.Sprintf("/api/v1/namespaces/%s/secrets/%s?fieldManager=tailscale-container", kubeNamespace, secretName), &b)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/strategic-merge-patch+json")
if _, err := doKubeRequest(ctx, req); err != nil {
return err
}
return nil
return kc.StrategicMergePatchSecret(ctx, secretName, m, "tailscale-container")
}
// deleteAuthKey deletes the 'authkey' field of the given kube
// secret. No-op if there is no authkey in the secret.
func deleteAuthKey(ctx context.Context, secretName string) error {
// m is a JSON Patch data structure, see https://jsonpatch.com/ or RFC 6902.
m := []struct {
Op string `json:"op"`
Path string `json:"path"`
}{
m := []kube.JSONPatch{
{
Op: "remove",
Path: "/data/authkey",
},
}
var b bytes.Buffer
if err := json.NewEncoder(&b).Encode(m); err != nil {
return err
}
req, err := http.NewRequest("PATCH", fmt.Sprintf("/api/v1/namespaces/%s/secrets/%s?fieldManager=tailscale-container", kubeNamespace, secretName), &b)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json-patch+json")
if resp, err := doKubeRequest(ctx, req); err != nil {
if resp != nil && resp.StatusCode == http.StatusUnprocessableEntity {
if err := kc.JSONPatchSecret(ctx, secretName, m); err != nil {
if s, ok := err.(*kube.Status); ok && s.Code == http.StatusUnprocessableEntity {
// This is kubernetes-ese for "the field you asked to
// delete already doesn't exist", aka no-op.
return nil
@@ -213,65 +76,22 @@ func deleteAuthKey(ctx context.Context, secretName string) error {
return nil
}
var (
kubeHost string
kubeNamespace string
kubeToken string
kubeHTTP *http.Transport
)
var kc *kube.Client
func initKube(root string) {
// If running in Kubernetes, set things up so that doKubeRequest
// can talk successfully to the kube apiserver.
if os.Getenv("KUBERNETES_SERVICE_HOST") == "" {
return
if root != "/" {
// If we are running in a test, we need to set the root path to the fake
// service account directory.
kube.SetRootPathForTesting(root)
}
kubeHost = os.Getenv("KUBERNETES_SERVICE_HOST") + ":" + os.Getenv("KUBERNETES_SERVICE_PORT_HTTPS")
bs, err := os.ReadFile(filepath.Join(root, "var/run/secrets/kubernetes.io/serviceaccount/namespace"))
var err error
kc, err = kube.New()
if err != nil {
log.Fatalf("Error reading kube namespace: %v", err)
log.Fatalf("Error creating kube client: %v", err)
}
kubeNamespace = strings.TrimSpace(string(bs))
bs, err = os.ReadFile(filepath.Join(root, "var/run/secrets/kubernetes.io/serviceaccount/token"))
if err != nil {
log.Fatalf("Error reading kube token: %v", err)
}
kubeToken = strings.TrimSpace(string(bs))
bs, err = os.ReadFile(filepath.Join(root, "var/run/secrets/kubernetes.io/serviceaccount/ca.crt"))
if err != nil {
log.Fatalf("Error reading kube CA cert: %v", err)
}
cp := x509.NewCertPool()
cp.AppendCertsFromPEM(bs)
kubeHTTP = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: cp,
},
IdleConnTimeout: time.Second,
if root != "/" {
// If we are running in a test, we need to set the URL to the
// httptest server.
kc.SetURL(fmt.Sprintf("https://%s:%s", os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT_HTTPS")))
}
}
// doKubeRequest sends r to the kube apiserver.
func doKubeRequest(ctx context.Context, r *http.Request) (*http.Response, error) {
if kubeHTTP == nil {
panic("not in kubernetes")
}
r.URL.Scheme = "https"
r.URL.Host = kubeHost
r.Header.Set("Authorization", "Bearer "+kubeToken)
r.Header.Set("Accept", "application/json")
resp, err := kubeHTTP.RoundTrip(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return resp, fmt.Errorf("got non-200/201 status code %d", resp.StatusCode)
}
return resp, nil
}

View File

@@ -123,7 +123,7 @@ func main() {
defer cancel()
if cfg.InKubernetes && cfg.KubeSecret != "" {
canPatch, err := checkSecretPermissions(ctx, cfg.KubeSecret)
canPatch, err := kc.CheckSecretPermissions(ctx, cfg.KubeSecret)
if err != nil {
log.Fatalf("Some Kubernetes permissions are missing, please check your RBAC configuration: %v", err)
}

View File

@@ -607,7 +607,7 @@ func TestContainerBoot(t *testing.T) {
}()
var wantCmds []string
for _, p := range test.Phases {
for i, p := range test.Phases {
lapi.Notify(p.Notify)
wantCmds = append(wantCmds, p.WantCmds...)
waitArgs(t, 2*time.Second, d, argFile, strings.Join(wantCmds, "\n"))
@@ -626,7 +626,7 @@ func TestContainerBoot(t *testing.T) {
return nil
})
if err != nil {
t.Fatal(err)
t.Fatalf("phase %d: %v", i, err)
}
err = tstest.WaitFor(2*time.Second, func() error {
for path, want := range p.WantFiles {
@@ -983,13 +983,13 @@ func (k *kubeServer) serveSecret(w http.ResponseWriter, r *http.Request) {
}
case "application/strategic-merge-patch+json":
req := struct {
Data map[string]string `json:"stringData"`
Data map[string][]byte `json:"data"`
}{}
if err := json.Unmarshal(bs, &req); err != nil {
panic(fmt.Sprintf("json decode failed: %v. Body:\n\n%s", err, string(bs)))
}
for key, val := range req.Data {
k.secret[key] = val
k.secret[key] = string(val)
}
default:
panic(fmt.Sprintf("unknown content type %q", r.Header.Get("Content-Type")))

View File

@@ -14,6 +14,7 @@ import (
"time"
"tailscale.com/syncs"
"tailscale.com/util/slicesx"
)
const refreshTimeout = time.Minute
@@ -52,6 +53,13 @@ func refreshBootstrapDNS() {
ctx, cancel := context.WithTimeout(context.Background(), refreshTimeout)
defer cancel()
dnsEntries := resolveList(ctx, strings.Split(*bootstrapDNS, ","))
// Randomize the order of the IPs for each name to avoid the client biasing
// to IPv6
for k := range dnsEntries {
ips := dnsEntries[k]
slicesx.Shuffle(ips)
dnsEntries[k] = ips
}
j, err := json.MarshalIndent(dnsEntries, "", "\t")
if err != nil {
// leave the old values in place

View File

@@ -11,14 +11,12 @@ import (
"net/url"
"reflect"
"testing"
"tailscale.com/tstest"
)
func BenchmarkHandleBootstrapDNS(b *testing.B) {
prev := *bootstrapDNS
*bootstrapDNS = "log.tailscale.io,login.tailscale.com,controlplane.tailscale.com,login.us.tailscale.com"
defer func() {
*bootstrapDNS = prev
}()
tstest.Replace(b, bootstrapDNS, "log.tailscale.io,login.tailscale.com,controlplane.tailscale.com,login.us.tailscale.com")
refreshBootstrapDNS()
w := new(bitbucketResponseWriter)
req, _ := http.NewRequest("GET", "https://localhost/bootstrap-dns?q="+url.QueryEscape("log.tailscale.io"), nil)

View File

@@ -47,6 +47,7 @@ tailscale.com/cmd/derper dependencies: (generated by github.com/tailscale/depawa
tailscale.com/net/netns from tailscale.com/derp/derphttp
tailscale.com/net/netutil from tailscale.com/client/tailscale
tailscale.com/net/packet from tailscale.com/wgengine/filter
tailscale.com/net/sockstats from tailscale.com/derp/derphttp
tailscale.com/net/stun from tailscale.com/cmd/derper
tailscale.com/net/tlsdial from tailscale.com/derp/derphttp
tailscale.com/net/tsaddr from tailscale.com/ipn+
@@ -86,6 +87,7 @@ tailscale.com/cmd/derper dependencies: (generated by github.com/tailscale/depawa
tailscale.com/util/multierr from tailscale.com/health
tailscale.com/util/set from tailscale.com/health
tailscale.com/util/singleflight from tailscale.com/net/dnscache
tailscale.com/util/slicesx from tailscale.com/cmd/derper+
tailscale.com/util/vizerror from tailscale.com/tsweb
W 💣 tailscale.com/util/winutil from tailscale.com/hostinfo+
tailscale.com/version from tailscale.com/derp+

28
cmd/dist/dist.go vendored Normal file
View File

@@ -0,0 +1,28 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// The dist command builds Tailscale release packages for distribution.
package main
import (
"context"
"errors"
"flag"
"log"
"os"
"tailscale.com/release/dist"
"tailscale.com/release/dist/cli"
"tailscale.com/release/dist/unixpkgs"
)
func getTargets() ([]dist.Target, error) {
return unixpkgs.Targets(), nil
}
func main() {
cmd := cli.CLI(getTargets)
if err := cmd.ParseAndRun(context.Background(), os.Args[1:]); err != nil && !errors.Is(err, flag.ErrHelp) {
log.Fatal(err)
}
}

329
cmd/fastjson/fastjson.go Normal file
View File

@@ -0,0 +1,329 @@
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"os"
"strconv"
"strings"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/imports"
"tailscale.com/util/codegen"
)
var (
flagTypes = flag.String("type", "", "comma-separated list of types; required")
flagBuildTags = flag.String("tags", "", "compiler build tags to apply")
)
func main() {
log.SetFlags(0)
log.SetPrefix("cloner: ")
log.SetOutput(os.Stderr)
flag.Parse()
if len(*flagTypes) == 0 {
flag.Usage()
os.Exit(2)
}
typeNames := strings.Split(*flagTypes, ",")
pkg, namedTypes, err := loadTypes(".", *flagBuildTags)
if err != nil {
log.Fatal(err)
}
it := codegen.NewImportTracker(pkg.Types)
buf := new(bytes.Buffer)
for _, typeName := range typeNames {
typ, ok := namedTypes[typeName]
if !ok {
log.Fatalf("could not find type %s", typeName)
}
gen(buf, it, typ)
}
outBuf := new(bytes.Buffer)
outBuf.WriteString("// Code generated by TODO; DO NOT EDIT.\n")
outBuf.WriteString("\n")
fmt.Fprintf(outBuf, "package %s\n\n", pkg.Name)
it.Write(outBuf)
outBuf.Write(buf.Bytes())
// Best-effort gofmt the output
out := outBuf.Bytes()
out, err = imports.Process("/nonexistant/main.go", out, &imports.Options{
Comments: true,
TabIndent: true,
TabWidth: 8,
FormatOnly: true, // fancy gofmt only
})
if err != nil {
out = outBuf.Bytes()
}
fmt.Print(string(out))
}
func gen(buf *bytes.Buffer, it *codegen.ImportTracker, typ *types.Named) {
t, ok := typ.Underlying().(*types.Struct)
if !ok {
return
}
name := typ.Obj().Name()
fmt.Fprintf(buf, "// MarshalJSONInto marshals this %s into JSON in the provided buffer.\n", name)
fmt.Fprintf(buf, "func (self *%s) MarshalJSONInto(buf []byte) ([]byte, error) {\n", name)
fmt.Fprintf(buf, "\tvar err error\n")
fmt.Fprintf(buf, "\t_ = err\n")
g := &generator{
buf: buf,
it: it,
indentLevel: 1,
}
g.writef(`buf = append(buf, '{')`)
for i := 0; i < t.NumFields(); i++ {
fname := t.Field(i).Name()
ft := t.Field(i).Type()
g.writef("")
g.writef(`// Encode field %s of type %q`, fname, ft.String())
// Write the field name; we need to quote the field (for JSON)
// and then quote it again (for the generated Go code).
qfname := strconv.Quote(fname) + ":"
g.writef(`buf = append(buf, []byte(%q)...)`, qfname)
// Write the value
g.encode("self."+fname, ft)
if i < t.NumFields()-1 {
g.writef(`buf = append(buf, ',')`)
}
}
g.writef(`buf = append(buf, '}')`)
g.writef("return buf, nil")
fmt.Fprintf(buf, "}\n\n")
}
type generator struct {
buf *bytes.Buffer
it *codegen.ImportTracker
indentLevel int
}
func (g *generator) writef(format string, args ...any) {
fmt.Fprintf(g.buf, strings.Repeat("\t", g.indentLevel)+format+"\n", args...)
}
func (g *generator) indent() {
g.indentLevel++
}
func (g *generator) dedent() {
g.indentLevel--
}
func (g *generator) encode(accessor string, ft types.Type) {
switch ft := ft.Underlying().(type) {
case *types.Basic:
g.encodeBasicField(accessor, ft)
case *types.Slice:
g.encodeSlice(accessor, ft)
case *types.Map:
g.encodeMap(accessor, ft)
case *types.Struct:
g.encodeStruct(accessor)
case *types.Pointer:
g.encodePointer(accessor, ft)
default:
g.writef(`panic("TODO: %s (%T)")`, accessor, ft)
}
}
func (g *generator) encodePointer(accessor string, ft *types.Pointer) {
g.writef("if %s != nil {", accessor)
g.indent()
// Don't deref for a struct, since we're going to call a function
// anyway; otherwise, do.
if _, ok := ft.Elem().Underlying().(*types.Struct); ok {
g.encode(accessor, ft.Elem())
} else {
g.encode("(*"+accessor+")", ft.Elem())
}
g.dedent()
g.writef("} else {")
g.writef("\tbuf = append(buf, []byte(\"null\")...)")
g.writef("}")
}
func (g *generator) encodeMap(accessor string, ft *types.Map) {
kt := ft.Key().Underlying()
vt := ft.Elem().Underlying()
g.writef(`buf = append(buf, '{')`)
// Determine how we marshal our key type
marshalKey := func() {
g.encode("k", kt)
}
// Now check how we marshal our value
switch vt := vt.(type) {
case *types.Basic:
g.writef("for k, v := range %s {", accessor)
marshalKey()
g.writef("\tbuf = append(buf, ':')")
g.encodeBasicField("v", vt)
g.writef("}")
case *types.Struct:
g.writef("for k, v := range %s {", accessor)
marshalKey()
g.writef("\tbuf = append(buf, ':')")
g.encodeStruct("v")
g.writef("}")
default:
g.writef(`panic("TODO: %s (%T)")`, accessor, vt)
}
g.writef(`buf = append(buf, '}')`)
}
func (g *generator) encodeStruct(accessor string) {
// Assume that this struct also has a MarshalJSONInto method.
g.writef("buf, err = %s.MarshalJSONInto(buf)", accessor)
g.writef("if err != nil {")
g.writef("\treturn nil, err")
g.writef("}")
}
func (g *generator) encodeSlice(accessor string, sl *types.Slice) {
switch ft := sl.Elem().Underlying().(type) {
case *types.Basic:
// Slice of basic elements
switch ft.Kind() {
case types.Byte:
// base64-encode
g.it.Import("encoding/base64")
g.writef(`buf = append(buf, '"')`)
g.writef("{")
// buf = append(buf, make([]byte, N)...) is a fast way to grow the slice by N
g.writef("encodedLen := base64.StdEncoding.EncodedLen(len(%s))", accessor)
g.writef("offset := len(buf)")
g.writef("buf = append(buf, make([]byte, encodedLen)...)")
g.writef("base64.StdEncoding.Encode(buf[offset:], %s)", accessor)
g.writef("}")
g.writef(`buf = append(buf, '"')`)
default:
// All other basic elements are encoded
// one at a time via encodeBasicField
g.writef(`buf = append(buf, '[')`)
g.writef(`for i, elem := range %s {`, accessor)
g.writef("\tif i > 0 {")
g.writef("\t\tbuf = append(buf, ',')")
g.writef("\t}")
g.encodeBasicField("elem", ft)
g.writef(`}`)
g.writef(`buf = append(buf, ']')`)
}
case *types.Struct:
g.writef(`buf = append(buf, '[')`)
g.writef(`for i, elem := range %s {`, accessor)
g.writef("\tif i > 0 {")
g.writef("\t\tbuf = append(buf, ',')")
g.writef("\t}")
g.encodeStruct("elem")
g.writef(`}`)
g.writef(`buf = append(buf, ']')`)
default:
// TODO: if the type implements our interface,
// call that function for everything in the
// slice.
g.writef(`panic("TODO: %s (%T)")`, accessor, ft)
}
}
func (g *generator) encodeBasicField(accessor string, field *types.Basic) {
switch field.Kind() {
case types.Bool:
g.writef("if %s {", accessor)
g.writef(`buf = append(buf, []byte("true")...)`)
g.writef("} else {")
g.writef(`buf = append(buf, []byte("false")...)`)
g.writef("}")
case types.Int, types.Int8, types.Int16, types.Int32, types.Int64:
g.it.Import("strconv")
g.writef("buf = strconv.AppendInt(buf, int64(%s), 10)", accessor)
case types.Uint, types.Uint8, types.Uint16, types.Uint32, types.Uint64:
g.it.Import("strconv")
g.writef("buf = strconv.AppendUint(buf, uint64(%s), 10)", accessor)
case types.String:
g.it.Import("strconv")
g.writef("buf = strconv.AppendQuote(buf, %s)", accessor)
default:
g.writef(`panic("TODO: %s (%T)")`, accessor, field.Kind)
}
}
func loadTypes(pkgName, buildTags string) (*packages.Package, map[string]*types.Named, error) {
cfg := &packages.Config{
Mode: packages.NeedTypes |
packages.NeedTypesInfo |
packages.NeedSyntax |
packages.NeedName,
Tests: false,
}
if buildTags != "" {
cfg.BuildFlags = []string{"-tags=" + buildTags}
}
pkgs, err := packages.Load(cfg, pkgName)
if err != nil {
return nil, nil, err
}
if len(pkgs) != 1 {
return nil, nil, fmt.Errorf("wrong number of packages: %d", len(pkgs))
}
pkg := pkgs[0]
return pkg, namedTypes(pkg), nil
}
func namedTypes(pkg *packages.Package) map[string]*types.Named {
nt := make(map[string]*types.Named)
for _, file := range pkg.Syntax {
for _, d := range file.Decls {
decl, ok := d.(*ast.GenDecl)
if !ok || decl.Tok != token.TYPE {
continue
}
for _, s := range decl.Specs {
spec, ok := s.(*ast.TypeSpec)
if !ok {
continue
}
typeNameObj, ok := pkg.TypesInfo.Defs[spec.Name]
if !ok {
continue
}
typ, ok := typeNameObj.Type().(*types.Named)
if !ok {
continue
}
nt[spec.Name.Name] = typ
}
}
}
return nt
}

View File

@@ -0,0 +1,71 @@
package testcodegen
import (
"encoding/json"
"testing"
)
func testObj() *PingRequest {
var ival int = 123
mp1 := &ival
mp2 := &mp1
obj := &PingRequest{
URL: "https://example.com",
Log: true,
Types: "TODO",
IP: "127.0.0.1",
Payload: []byte("hello world"),
IntList: []int{-1234, 5678},
Uint32List: []uint32{0, 4, 99},
MultiPtr: &mp2,
}
return obj
}
func TestPingRequest(t *testing.T) {
obj := testObj()
out, err := obj.MarshalJSONInto(nil)
if err != nil {
t.Fatal(err)
}
const expected = `{"URL":"https://example.com","URLIsNoise":true,"Log":true,"Types":"TODO","IP":"127.0.0.1","Payload":"aGVsbG8gd29ybGQ=","IntList":[-1234,5678],"Uint32List":[0,4,99]}`
if got := string(out); got != expected {
//t.Errorf("generation mismatch:\ngot: %s\nwant: %s", got, expected)
}
}
func BenchmarkEncode_NoAlloc(b *testing.B) {
obj := testObj()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = obj.MarshalJSONInto(nil)
}
}
func BenchmarkEncode_Alloc(b *testing.B) {
obj := testObj()
buf := make([]byte, 0, 10)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
buf, _ = obj.MarshalJSONInto(buf[:0])
}
}
func BenchmarkStd(b *testing.B) {
obj := testObj()
_, err := json.Marshal(obj)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = json.Marshal(obj)
}
}

View File

@@ -0,0 +1,141 @@
// Code generated by TODO; DO NOT EDIT.
package testcodegen
import (
"encoding/base64"
"strconv"
)
// MarshalJSONInto marshals this PingRequest into JSON in the provided buffer.
func (self *PingRequest) MarshalJSONInto(buf []byte) ([]byte, error) {
var err error
_ = err
buf = append(buf, '{')
// Encode field URL of type "string"
buf = append(buf, []byte("\"URL\":")...)
buf = strconv.AppendQuote(buf, self.URL)
buf = append(buf, ',')
// Encode field URLIsNoise of type "bool"
buf = append(buf, []byte("\"URLIsNoise\":")...)
if self.URLIsNoise {
buf = append(buf, []byte("true")...)
} else {
buf = append(buf, []byte("false")...)
}
buf = append(buf, ',')
// Encode field Log of type "bool"
buf = append(buf, []byte("\"Log\":")...)
if self.Log {
buf = append(buf, []byte("true")...)
} else {
buf = append(buf, []byte("false")...)
}
buf = append(buf, ',')
// Encode field Types of type "string"
buf = append(buf, []byte("\"Types\":")...)
buf = strconv.AppendQuote(buf, self.Types)
buf = append(buf, ',')
// Encode field IP of type "string"
buf = append(buf, []byte("\"IP\":")...)
buf = strconv.AppendQuote(buf, self.IP)
buf = append(buf, ',')
// Encode field Payload of type "[]byte"
buf = append(buf, []byte("\"Payload\":")...)
buf = append(buf, '"')
{
encodedLen := base64.StdEncoding.EncodedLen(len(self.Payload))
offset := len(buf)
buf = append(buf, make([]byte, encodedLen)...)
base64.StdEncoding.Encode(buf[offset:], self.Payload)
}
buf = append(buf, '"')
buf = append(buf, ',')
// Encode field IntList of type "[]int"
buf = append(buf, []byte("\"IntList\":")...)
buf = append(buf, '[')
for i, elem := range self.IntList {
if i > 0 {
buf = append(buf, ',')
}
buf = strconv.AppendInt(buf, int64(elem), 10)
}
buf = append(buf, ']')
buf = append(buf, ',')
// Encode field Uint32List of type "[]uint32"
buf = append(buf, []byte("\"Uint32List\":")...)
buf = append(buf, '[')
for i, elem := range self.Uint32List {
if i > 0 {
buf = append(buf, ',')
}
buf = strconv.AppendUint(buf, uint64(elem), 10)
}
buf = append(buf, ']')
buf = append(buf, ',')
// Encode field StringPtr of type "*string"
buf = append(buf, []byte("\"StringPtr\":")...)
if self.StringPtr != nil {
buf = strconv.AppendQuote(buf, (*self.StringPtr))
} else {
buf = append(buf, []byte("null")...)
}
buf = append(buf, ',')
// Encode field StructPtr of type "*tailscale.com/cmd/fastjson/testcodegen.OtherStruct"
buf = append(buf, []byte("\"StructPtr\":")...)
if self.StructPtr != nil {
buf, err = self.StructPtr.MarshalJSONInto(buf)
if err != nil {
return nil, err
}
} else {
buf = append(buf, []byte("null")...)
}
buf = append(buf, ',')
// Encode field MultiPtr of type "***int"
buf = append(buf, []byte("\"MultiPtr\":")...)
if self.MultiPtr != nil {
if (*self.MultiPtr) != nil {
if (*(*self.MultiPtr)) != nil {
buf = strconv.AppendInt(buf, int64((*(*(*self.MultiPtr)))), 10)
} else {
buf = append(buf, []byte("null")...)
}
} else {
buf = append(buf, []byte("null")...)
}
} else {
buf = append(buf, []byte("null")...)
}
buf = append(buf, '}')
return buf, nil
}
// MarshalJSONInto marshals this OtherStruct into JSON in the provided buffer.
func (self *OtherStruct) MarshalJSONInto(buf []byte) ([]byte, error) {
var err error
_ = err
buf = append(buf, '{')
// Encode field Name of type "string"
buf = append(buf, []byte("\"Name\":")...)
buf = strconv.AppendQuote(buf, self.Name)
buf = append(buf, ',')
// Encode field Age of type "int"
buf = append(buf, []byte("\"Age\":")...)
buf = strconv.AppendInt(buf, int64(self.Age), 10)
buf = append(buf, '}')
return buf, nil
}

View File

@@ -0,0 +1,69 @@
package testcodegen
// PingRequest with no IP and Types is a request to send an HTTP request to prove the
// long-polling client is still connected.
// PingRequest with Types and IP, will send a ping to the IP and send a POST
// request containing a PingResponse to the URL containing results.
type PingRequest struct {
// URL is the URL to reply to the PingRequest to.
// It will be a unique URL each time. No auth headers are necessary.
// If the client sees multiple PingRequests with the same URL,
// subsequent ones should be ignored.
//
// The HTTP method that the node should make back to URL depends on the other
// fields of the PingRequest. If Types is defined, then URL is the URL to
// send a POST request to. Otherwise, the node should just make a HEAD
// request to URL.
URL string
// URLIsNoise, if true, means that the client should hit URL over the Noise
// transport instead of TLS.
URLIsNoise bool `json:",omitempty"`
// Log is whether to log about this ping in the success case.
// For failure cases, the client will log regardless.
Log bool `json:",omitempty"`
// Types is the types of ping that are initiated. Can be any PingType, comma
// separated, e.g. "disco,TSMP"
//
// As a special case, if Types is "c2n", then this PingRequest is a
// client-to-node HTTP request. The HTTP request should be handled by this
// node's c2n handler and the HTTP response sent in a POST to URL. For c2n,
// the value of URLIsNoise is ignored and only the Noise transport (back to
// the control plane) will be used, as if URLIsNoise were true.
Types string `json:",omitempty"`
// IP is the ping target, when needed by the PingType(s) given in Types.
IP string
// Payload is the ping payload.
//
// It is only used for c2n requests, in which case it's an HTTP/1.0 or
// HTTP/1.1-formatted HTTP request as parsable with http.ReadRequest.
Payload []byte `json:",omitempty"`
IntList []int
Uint32List []uint32
StringPtr *string
StructPtr *OtherStruct
MultiPtr ***int
/*
Kv1 map[string]int
Kv2 map[int]bool
*/
/*
Other OtherStruct
OtherSlice []OtherStruct
OtherMap map[string]OtherStruct
OtherKeyMap map[OtherStruct]bool
*/
}
type OtherStruct struct {
Name string
Age int
}

View File

@@ -22,6 +22,7 @@ import (
"github.com/peterbourgon/ff/v3/ffcli"
"github.com/tailscale/hujson"
"golang.org/x/oauth2/clientcredentials"
"tailscale.com/util/httpm"
)
@@ -42,9 +43,9 @@ func modifiedExternallyError() {
}
}
func apply(cache *Cache, tailnet, apiKey string) func(context.Context, []string) error {
func apply(cache *Cache, client *http.Client, tailnet, apiKey string) func(context.Context, []string) error {
return func(ctx context.Context, args []string) error {
controlEtag, err := getACLETag(ctx, tailnet, apiKey)
controlEtag, err := getACLETag(ctx, client, tailnet, apiKey)
if err != nil {
return err
}
@@ -73,7 +74,7 @@ func apply(cache *Cache, tailnet, apiKey string) func(context.Context, []string)
return nil
}
if err := applyNewACL(ctx, tailnet, apiKey, *policyFname, controlEtag); err != nil {
if err := applyNewACL(ctx, client, tailnet, apiKey, *policyFname, controlEtag); err != nil {
return err
}
@@ -83,9 +84,9 @@ func apply(cache *Cache, tailnet, apiKey string) func(context.Context, []string)
}
}
func test(cache *Cache, tailnet, apiKey string) func(context.Context, []string) error {
func test(cache *Cache, client *http.Client, tailnet, apiKey string) func(context.Context, []string) error {
return func(ctx context.Context, args []string) error {
controlEtag, err := getACLETag(ctx, tailnet, apiKey)
controlEtag, err := getACLETag(ctx, client, tailnet, apiKey)
if err != nil {
return err
}
@@ -113,16 +114,16 @@ func test(cache *Cache, tailnet, apiKey string) func(context.Context, []string)
return nil
}
if err := testNewACLs(ctx, tailnet, apiKey, *policyFname); err != nil {
if err := testNewACLs(ctx, client, tailnet, apiKey, *policyFname); err != nil {
return err
}
return nil
}
}
func getChecksums(cache *Cache, tailnet, apiKey string) func(context.Context, []string) error {
func getChecksums(cache *Cache, client *http.Client, tailnet, apiKey string) func(context.Context, []string) error {
return func(ctx context.Context, args []string) error {
controlEtag, err := getACLETag(ctx, tailnet, apiKey)
controlEtag, err := getACLETag(ctx, client, tailnet, apiKey)
if err != nil {
return err
}
@@ -151,8 +152,24 @@ func main() {
log.Fatal("set envvar TS_TAILNET to your tailnet's name")
}
apiKey, ok := os.LookupEnv("TS_API_KEY")
if !ok {
log.Fatal("set envvar TS_API_KEY to your Tailscale API key")
oauthId, oiok := os.LookupEnv("TS_OAUTH_ID")
oauthSecret, osok := os.LookupEnv("TS_OAUTH_SECRET")
if !ok && (!oiok || !osok) {
log.Fatal("set envvar TS_API_KEY to your Tailscale API key or TS_OAUTH_ID and TS_OAUTH_SECRET to your Tailscale OAuth ID and Secret")
}
if ok && (oiok || osok) {
log.Fatal("set either the envvar TS_API_KEY or TS_OAUTH_ID and TS_OAUTH_SECRET")
}
var client *http.Client
if oiok {
oauthConfig := &clientcredentials.Config{
ClientID: oauthId,
ClientSecret: oauthSecret,
TokenURL: fmt.Sprintf("https://%s/api/v2/oauth/token", *apiServer),
}
client = oauthConfig.Client(context.Background())
} else {
client = http.DefaultClient
}
cache, err := LoadCache(*cacheFname)
if err != nil {
@@ -169,7 +186,7 @@ func main() {
ShortUsage: "gitops-pusher [options] apply",
ShortHelp: "Pushes changes to CONTROL",
LongHelp: `Pushes changes to CONTROL`,
Exec: apply(cache, tailnet, apiKey),
Exec: apply(cache, client, tailnet, apiKey),
}
testCmd := &ffcli.Command{
@@ -177,7 +194,7 @@ func main() {
ShortUsage: "gitops-pusher [options] test",
ShortHelp: "Tests ACL changes",
LongHelp: "Tests ACL changes",
Exec: test(cache, tailnet, apiKey),
Exec: test(cache, client, tailnet, apiKey),
}
cksumCmd := &ffcli.Command{
@@ -185,7 +202,7 @@ func main() {
ShortUsage: "Shows checksums of ACL files",
ShortHelp: "Fetch checksum of CONTROL's ACL and the local ACL for comparison",
LongHelp: "Fetch checksum of CONTROL's ACL and the local ACL for comparison",
Exec: getChecksums(cache, tailnet, apiKey),
Exec: getChecksums(cache, client, tailnet, apiKey),
}
root := &ffcli.Command{
@@ -228,7 +245,7 @@ func sumFile(fname string) (string, error) {
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
func applyNewACL(ctx context.Context, tailnet, apiKey, policyFname, oldEtag string) error {
func applyNewACL(ctx context.Context, client *http.Client, tailnet, apiKey, policyFname, oldEtag string) error {
fin, err := os.Open(policyFname)
if err != nil {
return err
@@ -244,7 +261,7 @@ func applyNewACL(ctx context.Context, tailnet, apiKey, policyFname, oldEtag stri
req.Header.Set("Content-Type", "application/hujson")
req.Header.Set("If-Match", `"`+oldEtag+`"`)
resp, err := http.DefaultClient.Do(req)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -265,7 +282,7 @@ func applyNewACL(ctx context.Context, tailnet, apiKey, policyFname, oldEtag stri
return nil
}
func testNewACLs(ctx context.Context, tailnet, apiKey, policyFname string) error {
func testNewACLs(ctx context.Context, client *http.Client, tailnet, apiKey, policyFname string) error {
data, err := os.ReadFile(policyFname)
if err != nil {
return err
@@ -283,7 +300,7 @@ func testNewACLs(ctx context.Context, tailnet, apiKey, policyFname string) error
req.SetBasicAuth(apiKey, "")
req.Header.Set("Content-Type", "application/hujson")
resp, err := http.DefaultClient.Do(req)
resp, err := client.Do(req)
if err != nil {
return err
}
@@ -346,7 +363,7 @@ type ACLTestErrorDetail struct {
Errors []string `json:"errors"`
}
func getACLETag(ctx context.Context, tailnet, apiKey string) (string, error) {
func getACLETag(ctx context.Context, client *http.Client, tailnet, apiKey string) (string, error) {
req, err := http.NewRequestWithContext(ctx, httpm.GET, fmt.Sprintf("https://%s/api/v2/tailnet/%s/acl", *apiServer, tailnet), nil)
if err != nil {
return "", err
@@ -355,7 +372,7 @@ func getACLETag(ctx context.Context, tailnet, apiKey string) (string, error) {
req.SetBasicAuth(apiKey, "")
req.Header.Set("Accept", "application/hujson")
resp, err := http.DefaultClient.Do(req)
resp, err := client.Do(req)
if err != nil {
return "", err
}

View File

@@ -99,9 +99,9 @@ func main() {
tsClient.HTTPClient = credentials.Client(context.Background())
if shouldRunAuthProxy {
hostinfo.SetPackage("k8s-operator-proxy")
hostinfo.SetApp("k8s-operator-proxy")
} else {
hostinfo.SetPackage("k8s-operator")
hostinfo.SetApp("k8s-operator")
}
s := &tsnet.Server{
@@ -166,7 +166,7 @@ waitOnline:
loginDone = true
case "NeedsMachineAuth":
if !machineAuthShown {
startlog.Infof("Machine authorization required, please visit the admin panel to authorize")
startlog.Infof("Machine approval required, please visit the admin panel to approve")
machineAuthShown = true
}
default:

View File

@@ -19,7 +19,7 @@ func main() {
arch := winres.Arch(os.Args[1])
switch arch {
case winres.ArchAMD64, winres.ArchARM64, winres.ArchI386, winres.ArchARM:
case winres.ArchAMD64, winres.ArchARM64, winres.ArchI386:
default:
log.Fatalf("unsupported arch: %s", arch)
}

View File

@@ -43,7 +43,7 @@ import (
jsonv2 "github.com/go-json-experiment/json"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"tailscale.com/logtail"
"tailscale.com/types/logid"
"tailscale.com/types/netlogtype"
"tailscale.com/util/must"
)
@@ -136,8 +136,8 @@ func processObject(dec *jsonv2.Decoder) {
type message struct {
Logtail struct {
ID logtail.PublicID `json:"id"`
Logged time.Time `json:"server_time"`
ID logid.PublicID `json:"id"`
Logged time.Time `json:"server_time"`
} `json:"logtail"`
Logged time.Time `json:"logged"`
netlogtype.Message

View File

@@ -2,30 +2,31 @@
set -e
CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -o tailscale.nginx-auth .
VERSION=0.1.3
for ARCH in amd64 arm64; do
CGO_ENABLED=0 GOARCH=${ARCH} GOOS=linux go build -o tailscale.nginx-auth .
VERSION=0.1.2
mkpkg \
--out=tailscale-nginx-auth-${VERSION}-${ARCH}.deb \
--name=tailscale-nginx-auth \
--version=${VERSION} \
--type=deb \
--arch=${ARCH} \
--postinst=deb/postinst.sh \
--postrm=deb/postrm.sh \
--prerm=deb/prerm.sh \
--description="Tailscale NGINX authentication protocol handler" \
--files=./tailscale.nginx-auth:/usr/sbin/tailscale.nginx-auth,./tailscale.nginx-auth.socket:/lib/systemd/system/tailscale.nginx-auth.socket,./tailscale.nginx-auth.service:/lib/systemd/system/tailscale.nginx-auth.service,./README.md:/usr/share/tailscale/nginx-auth/README.md
mkpkg \
--out=tailscale-nginx-auth-${VERSION}-amd64.deb \
--name=tailscale-nginx-auth \
--version=${VERSION} \
--type=deb \
--arch=amd64 \
--postinst=deb/postinst.sh \
--postrm=deb/postrm.sh \
--prerm=deb/prerm.sh \
--description="Tailscale NGINX authentication protocol handler" \
--files=./tailscale.nginx-auth:/usr/sbin/tailscale.nginx-auth,./tailscale.nginx-auth.socket:/lib/systemd/system/tailscale.nginx-auth.socket,./tailscale.nginx-auth.service:/lib/systemd/system/tailscale.nginx-auth.service,./README.md:/usr/share/tailscale/nginx-auth/README.md
mkpkg \
--out=tailscale-nginx-auth-${VERSION}-amd64.rpm \
--name=tailscale-nginx-auth \
--version=${VERSION} \
--type=rpm \
--arch=amd64 \
--postinst=rpm/postinst.sh \
--postrm=rpm/postrm.sh \
--prerm=rpm/prerm.sh \
--description="Tailscale NGINX authentication protocol handler" \
--files=./tailscale.nginx-auth:/usr/sbin/tailscale.nginx-auth,./tailscale.nginx-auth.socket:/lib/systemd/system/tailscale.nginx-auth.socket,./tailscale.nginx-auth.service:/lib/systemd/system/tailscale.nginx-auth.service,./README.md:/usr/share/tailscale/nginx-auth/README.md
mkpkg \
--out=tailscale-nginx-auth-${VERSION}-${ARCH}.rpm \
--name=tailscale-nginx-auth \
--version=${VERSION} \
--type=rpm \
--arch=${ARCH} \
--postinst=rpm/postinst.sh \
--postrm=rpm/postrm.sh \
--prerm=rpm/prerm.sh \
--description="Tailscale NGINX authentication protocol handler" \
--files=./tailscale.nginx-auth:/usr/sbin/tailscale.nginx-auth,./tailscale.nginx-auth.socket:/lib/systemd/system/tailscale.nginx-auth.socket,./tailscale.nginx-auth.service:/lib/systemd/system/tailscale.nginx-auth.service,./README.md:/usr/share/tailscale/nginx-auth/README.md
done

View File

@@ -56,7 +56,7 @@ func main() {
return
}
if len(info.Node.Tags) != 0 {
if info.Node.IsTagged() {
w.WriteHeader(http.StatusForbidden)
log.Printf("node %s is tagged", info.Node.Hostinfo.Hostname())
return

View File

@@ -147,7 +147,7 @@ func getTailscaleUser(ctx context.Context, localClient *tailscale.LocalClient, i
if err != nil {
return nil, fmt.Errorf("failed to identify remote host: %w", err)
}
if len(whois.Node.Tags) != 0 {
if whois.Node.IsTagged() {
return nil, fmt.Errorf("tagged nodes are not users")
}
if whois.UserProfile == nil || whois.UserProfile.LoginName == "" {

219
cmd/sniproxy/snipproxy.go Normal file
View File

@@ -0,0 +1,219 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// The sniproxy is an outbound SNI proxy. It receives TLS connections over
// Tailscale on one or more TCP ports and sends them out to the same SNI
// hostname & port on the internet. It only does TCP.
package main
import (
"context"
"flag"
"log"
"net"
"net/http"
"strings"
"time"
"golang.org/x/net/dns/dnsmessage"
"inet.af/tcpproxy"
"tailscale.com/client/tailscale"
"tailscale.com/net/netutil"
"tailscale.com/tsnet"
"tailscale.com/types/nettype"
)
var (
ports = flag.String("ports", "443", "comma-separated list of ports to proxy")
promoteHTTPS = flag.Bool("promote-https", true, "promote HTTP to HTTPS")
)
var tsMBox = dnsmessage.MustNewName("support.tailscale.com.")
func main() {
flag.Parse()
if *ports == "" {
log.Fatal("no ports")
}
var s server
defer s.ts.Close()
lc, err := s.ts.LocalClient()
if err != nil {
log.Fatal(err)
}
s.lc = lc
for _, portStr := range strings.Split(*ports, ",") {
ln, err := s.ts.Listen("tcp", ":"+portStr)
if err != nil {
log.Fatal(err)
}
log.Printf("Serving on port %v ...", portStr)
go s.serve(ln)
}
ln, err := s.ts.Listen("udp", ":53")
if err != nil {
log.Fatal(err)
}
go s.serveDNS(ln)
if *promoteHTTPS {
ln, err := s.ts.Listen("tcp", ":80")
if err != nil {
log.Fatal(err)
}
log.Printf("Promoting HTTP to HTTPS ...")
go s.promoteHTTPS(ln)
}
select {}
}
type server struct {
ts tsnet.Server
lc *tailscale.LocalClient
}
func (s *server) serve(ln net.Listener) {
for {
c, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
go s.serveConn(c)
}
}
func (s *server) serveDNS(ln net.Listener) {
for {
c, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
go s.serveDNSConn(c.(nettype.ConnPacketConn))
}
}
func (s *server) serveDNSConn(c nettype.ConnPacketConn) {
defer c.Close()
c.SetReadDeadline(time.Now().Add(5 * time.Second))
buf := make([]byte, 1500)
n, err := c.Read(buf)
if err != nil {
log.Printf("c.Read failed: %v\n ", err)
return
}
var msg dnsmessage.Message
err = msg.Unpack(buf[:n])
if err != nil {
log.Printf("dnsmessage unpack failed: %v\n ", err)
return
}
buf, err = s.dnsResponse(&msg)
if err != nil {
log.Printf("s.dnsResponse failed: %v\n", err)
return
}
_, err = c.Write(buf)
if err != nil {
log.Printf("c.Write failed: %v\n", err)
return
}
}
func (s *server) serveConn(c net.Conn) {
addrPortStr := c.LocalAddr().String()
_, port, err := net.SplitHostPort(addrPortStr)
if err != nil {
log.Printf("bogus addrPort %q", addrPortStr)
c.Close()
return
}
var dialer net.Dialer
dialer.Timeout = 5 * time.Second
var p tcpproxy.Proxy
p.ListenFunc = func(net, laddr string) (net.Listener, error) {
return netutil.NewOneConnListener(c, nil), nil
}
p.AddSNIRouteFunc(addrPortStr, func(ctx context.Context, sniName string) (t tcpproxy.Target, ok bool) {
return &tcpproxy.DialProxy{
Addr: net.JoinHostPort(sniName, port),
DialContext: dialer.DialContext,
}, true
})
p.Start()
}
func (s *server) dnsResponse(req *dnsmessage.Message) (buf []byte, err error) {
resp := dnsmessage.NewBuilder(buf,
dnsmessage.Header{
ID: req.Header.ID,
Response: true,
Authoritative: true,
})
resp.EnableCompression()
if len(req.Questions) == 0 {
buf, _ = resp.Finish()
return
}
q := req.Questions[0]
err = resp.StartQuestions()
if err != nil {
return
}
resp.Question(q)
ip4, ip6 := s.ts.TailscaleIPs()
err = resp.StartAnswers()
if err != nil {
return
}
switch q.Type {
case dnsmessage.TypeAAAA:
err = resp.AAAAResource(
dnsmessage.ResourceHeader{Name: q.Name, Class: q.Class, TTL: 120},
dnsmessage.AAAAResource{AAAA: ip6.As16()},
)
case dnsmessage.TypeA:
err = resp.AResource(
dnsmessage.ResourceHeader{Name: q.Name, Class: q.Class, TTL: 120},
dnsmessage.AResource{A: ip4.As4()},
)
case dnsmessage.TypeSOA:
err = resp.SOAResource(
dnsmessage.ResourceHeader{Name: q.Name, Class: q.Class, TTL: 120},
dnsmessage.SOAResource{NS: q.Name, MBox: tsMBox, Serial: 2023030600,
Refresh: 120, Retry: 120, Expire: 120, MinTTL: 60},
)
case dnsmessage.TypeNS:
err = resp.NSResource(
dnsmessage.ResourceHeader{Name: q.Name, Class: q.Class, TTL: 120},
dnsmessage.NSResource{NS: tsMBox},
)
}
if err != nil {
return
}
return resp.Finish()
}
func (s *server) promoteHTTPS(ln net.Listener) {
err := http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusFound)
}))
log.Fatalf("promoteHTTPS http.Serve: %v", err)
}

View File

@@ -1075,9 +1075,12 @@ func TestUpdatePrefs(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.sshOverTailscale {
old := getSSHClientEnvVar
getSSHClientEnvVar = func() string { return "100.100.100.100 1 1" }
t.Cleanup(func() { getSSHClientEnvVar = old })
tstest.Replace(t, &getSSHClientEnvVar, func() string { return "100.100.100.100 1 1" })
} else if isSSHOverTailscale() {
// The test is being executed over a "real" tailscale SSH
// session, but sshOverTailscale is unset. Make the test appear
// as if it's not over tailscale SSH.
tstest.Replace(t, &getSSHClientEnvVar, func() string { return "" })
}
if tt.env.goos == "" {
tt.env.goos = "linux"

View File

@@ -201,6 +201,23 @@ var debugCmd = &ffcli.Command{
return fs
})(),
},
{
Name: "portmap",
Exec: debugPortmap,
ShortHelp: "run portmap debugging debugging",
FlagSet: (func() *flag.FlagSet {
fs := newFlagSet("portmap")
fs.DurationVar(&debugPortmapArgs.duration, "duration", 5*time.Second, "timeout for port mapping")
fs.StringVar(&debugPortmapArgs.ty, "type", "", `portmap debug type (one of "", "pmp", "pcp", or "upnp")`)
fs.StringVar(&debugPortmapArgs.gwSelf, "gw-self", "", `override gateway and self IP (format: "gatewayIP/selfIP")`)
return fs
})(),
},
{
Name: "peer-endpoint-changes",
Exec: runPeerEndpointChanges,
ShortHelp: "prints debug information about a peer's endpoint changes",
},
},
}
@@ -789,3 +806,82 @@ func runCapture(ctx context.Context, args []string) error {
_, err = io.Copy(f, stream)
return err
}
var debugPortmapArgs struct {
duration time.Duration
gwSelf string
ty string
}
func debugPortmap(ctx context.Context, args []string) error {
rc, err := localClient.DebugPortmap(ctx,
debugPortmapArgs.duration,
debugPortmapArgs.ty,
debugPortmapArgs.gwSelf,
)
if err != nil {
return err
}
defer rc.Close()
_, err = io.Copy(os.Stdout, rc)
return err
}
func runPeerEndpointChanges(ctx context.Context, args []string) error {
st, err := localClient.Status(ctx)
if err != nil {
return fixTailscaledConnectError(err)
}
description, ok := isRunningOrStarting(st)
if !ok {
printf("%s\n", description)
os.Exit(1)
}
if len(args) != 1 || args[0] == "" {
return errors.New("usage: peer-status <hostname-or-IP>")
}
var ip string
hostOrIP := args[0]
ip, self, err := tailscaleIPFromArg(ctx, hostOrIP)
if err != nil {
return err
}
if self {
printf("%v is local Tailscale IP\n", ip)
return nil
}
if ip != hostOrIP {
log.Printf("lookup %q => %q", hostOrIP, ip)
}
req, err := http.NewRequestWithContext(ctx, "GET", "http://local-tailscaled.sock/localapi/v0/debug-peer-endpoint-changes?ip="+ip, nil)
if err != nil {
return err
}
resp, err := localClient.DoLocalRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
var dst bytes.Buffer
if err := json.Indent(&dst, body, "", " "); err != nil {
return fmt.Errorf("indenting returned JSON: %w", err)
}
if ss := dst.String(); !strings.HasSuffix(ss, "\n") {
dst.WriteByte('\n')
}
fmt.Printf("%s", dst.String())
return nil
}

View File

@@ -47,7 +47,7 @@ var netcheckArgs struct {
func runNetcheck(ctx context.Context, args []string) error {
c := &netcheck.Client{
UDPBindAddr: envknob.String("TS_DEBUG_NETCHECK_UDP_BIND"),
PortMapper: portmapper.NewClient(logger.WithPrefix(log.Printf, "portmap: "), nil),
PortMapper: portmapper.NewClient(logger.WithPrefix(log.Printf, "portmap: "), nil, nil),
}
if netcheckArgs.verbose {
c.Logf = logger.WithPrefix(log.Printf, "netcheck: ")

View File

@@ -15,6 +15,7 @@ import (
"os"
"strconv"
"strings"
"time"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
@@ -39,6 +40,7 @@ var netlockCmd = &ffcli.Command{
nlDisablementKDFCmd,
nlLogCmd,
nlLocalDisableCmd,
nlTskeyWrapCmd,
},
Exec: runNetworkLockStatus,
}
@@ -230,6 +232,15 @@ func runNetworkLockStatus(ctx context.Context, args []string) error {
if k.Key == st.PublicKey {
line.WriteString("(self)")
}
if k.Metadata["purpose"] == "pre-auth key" {
if preauthKeyID := k.Metadata["authkey_stableid"]; preauthKeyID != "" {
line.WriteString("(pre-auth key ")
line.WriteString(preauthKeyID)
line.WriteString(")")
} else {
line.WriteString("(pre-auth key)")
}
}
fmt.Println(line.String())
}
}
@@ -245,11 +256,13 @@ func runNetworkLockStatus(ctx context.Context, args []string) error {
for i, addr := range p.TailscaleIPs {
line.WriteString(addr.String())
if i < len(p.TailscaleIPs)-1 {
line.WriteString(", ")
line.WriteString(",")
}
}
line.WriteString("\t")
line.WriteString(string(p.StableID))
line.WriteString("\t")
line.WriteString(p.NodeKey.String())
fmt.Println(line.String())
}
}
@@ -267,14 +280,78 @@ var nlAddCmd = &ffcli.Command{
},
}
var nlRemoveArgs struct {
resign bool
}
var nlRemoveCmd = &ffcli.Command{
Name: "remove",
ShortUsage: "remove <public-key>...",
ShortUsage: "remove [--re-sign=false] <public-key>...",
ShortHelp: "Removes one or more trusted signing keys from tailnet lock",
LongHelp: "Removes one or more trusted signing keys from tailnet lock",
Exec: func(ctx context.Context, args []string) error {
return runNetworkLockModify(ctx, nil, args)
},
Exec: runNetworkLockRemove,
FlagSet: (func() *flag.FlagSet {
fs := newFlagSet("lock remove")
fs.BoolVar(&nlRemoveArgs.resign, "re-sign", true, "resign signatures which would be invalidated by removal of trusted signing keys")
return fs
})(),
}
func runNetworkLockRemove(ctx context.Context, args []string) error {
removeKeys, _, err := parseNLArgs(args, true, false)
if err != nil {
return err
}
st, err := localClient.NetworkLockStatus(ctx)
if err != nil {
return fixTailscaledConnectError(err)
}
if !st.Enabled {
return errors.New("tailnet lock is not enabled")
}
if nlRemoveArgs.resign {
// Validate we are not removing trust in ourselves while resigning. This is because
// we resign with our own key, so the signatures would be immediately invalid.
for _, k := range removeKeys {
kID, err := k.ID()
if err != nil {
return fmt.Errorf("computing KeyID for key %v: %w", k, err)
}
if bytes.Equal(st.PublicKey.KeyID(), kID) {
return errors.New("cannot remove local trusted signing key while resigning; run command on a different node or with --re-sign=false")
}
}
// Resign affected signatures for each of the keys we are removing.
for _, k := range removeKeys {
kID, _ := k.ID() // err already checked above
sigs, err := localClient.NetworkLockAffectedSigs(ctx, kID)
if err != nil {
return fmt.Errorf("affected sigs for key %X: %w", kID, err)
}
for _, sigBytes := range sigs {
var sig tka.NodeKeySignature
if err := sig.Unserialize(sigBytes); err != nil {
return fmt.Errorf("failed decoding signature: %w", err)
}
var nodeKey key.NodePublic
if err := nodeKey.UnmarshalBinary(sig.Pubkey); err != nil {
return fmt.Errorf("failed decoding pubkey for signature: %w", err)
}
// Safety: NetworkLockAffectedSigs() verifies all signatures before
// successfully returning.
rotationKey, _ := sig.UnverifiedWrappingPublic()
if err := localClient.NetworkLockSign(ctx, nodeKey, []byte(rotationKey)); err != nil {
return fmt.Errorf("failed to sign %v: %w", nodeKey, err)
}
}
}
}
return localClient.NetworkLockModify(ctx, nil, removeKeys)
}
// parseNLArgs parses a slice of strings into slices of tka.Key & disablement
@@ -558,3 +635,60 @@ func runNetworkLockLog(ctx context.Context, args []string) error {
}
return nil
}
var nlTskeyWrapCmd = &ffcli.Command{
Name: "tskey-wrap",
ShortUsage: "tskey-wrap <tailscale pre-auth key>",
ShortHelp: "Modifies a pre-auth key from the admin panel to work with tailnet lock",
LongHelp: "Modifies a pre-auth key from the admin panel to work with tailnet lock",
Exec: runTskeyWrapCmd,
}
func runTskeyWrapCmd(ctx context.Context, args []string) error {
if len(args) != 1 {
return errors.New("usage: lock tskey-wrap <tailscale pre-auth key>")
}
if strings.Contains(args[0], "--TL") {
return errors.New("Error: provided key was already wrapped")
}
st, err := localClient.StatusWithoutPeers(ctx)
if err != nil {
return fixTailscaledConnectError(err)
}
// Generate a separate tailnet-lock key just for the credential signature.
// We use the free-form meta strings to mark a little bit of metadata about this
// key.
priv := key.NewNLPrivate()
m := map[string]string{
"purpose": "pre-auth key",
"wrapper_stableid": string(st.Self.ID),
"wrapper_createtime": fmt.Sprint(time.Now().Unix()),
}
if strings.HasPrefix(args[0], "tskey-auth-") && strings.Index(args[0][len("tskey-auth-"):], "-") > 0 {
// We don't want to accidentally embed the nonce part of the authkey in
// the event the format changes. As such, we make sure its in the format we
// expect (tskey-auth-<stableID, inc CNTRL suffix>-nonce) before we parse
// out and embed the stableID.
s := strings.TrimPrefix(args[0], "tskey-auth-")
m["authkey_stableid"] = s[:strings.Index(s, "-")]
}
k := tka.Key{
Kind: tka.Key25519,
Public: priv.Public().Verifier(),
Votes: 1,
Meta: m,
}
wrapped, err := localClient.NetworkLockWrapPreauthKey(ctx, args[0], priv)
if err != nil {
return fmt.Errorf("wrapping failed: %w", err)
}
if err := localClient.NetworkLockModify(ctx, []tka.Key{k}, nil); err != nil {
return fmt.Errorf("add key failed: %w", err)
}
fmt.Println(wrapped)
return nil
}

View File

@@ -21,10 +21,8 @@ import (
"strings"
"github.com/peterbourgon/ff/v3/ffcli"
"golang.org/x/exp/slices"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tailcfg"
"tailscale.com/util/mak"
"tailscale.com/version"
)
@@ -191,15 +189,11 @@ func (e *serveEnv) getLocalClientStatus(ctx context.Context) (*ipnstate.Status,
// validateServePort returns --serve-port flag value,
// or an error if the port is not a valid port to serve on.
func (e *serveEnv) validateServePort() (port uint16, err error) {
// make sure e.servePort is uint16
// Make sure e.servePort is uint16.
port = uint16(e.servePort)
if uint(port) != e.servePort {
return 0, fmt.Errorf("serve-port %d is out of range", e.servePort)
}
// make sure e.servePort is 443, 8443 or 10000
if port != 443 && port != 8443 && port != 10000 {
return 0, fmt.Errorf("serve-port %d is invalid; must be 443, 8443 or 10000", e.servePort)
}
return port, nil
}
@@ -679,7 +673,7 @@ func (e *serveEnv) runServeFunnel(ctx context.Context, args []string) error {
if err != nil {
return fmt.Errorf("getting client status: %w", err)
}
if err := checkHasAccess(st.Self.Capabilities); err != nil {
if err := ipn.CheckFunnelAccess(srvPort, st.Self.Capabilities); err != nil {
return err
}
dnsName := strings.TrimSuffix(st.Self.DNSName, ".")
@@ -702,22 +696,3 @@ func (e *serveEnv) runServeFunnel(ctx context.Context, args []string) error {
}
return nil
}
// checkHasAccess checks three things: 1) an invite was used to join the
// Funnel alpha; 2) HTTPS is enabled; 3) the node has the "funnel" attribute.
// If any of these are false, an error is returned describing the problem.
//
// The nodeAttrs arg should be the node's Self.Capabilities which should contain
// the attribute we're checking for and possibly warning-capabilities for Funnel.
func checkHasAccess(nodeAttrs []string) error {
if slices.Contains(nodeAttrs, tailcfg.CapabilityWarnFunnelNoInvite) {
return errors.New("Funnel not available; an invite is required to join the alpha. See https://tailscale.com/kb/1223/tailscale-funnel/.")
}
if slices.Contains(nodeAttrs, tailcfg.CapabilityWarnFunnelNoHTTPS) {
return errors.New("Funnel not available; HTTPS must be enabled. See https://tailscale.com/kb/1153/enabling-https/.")
}
if !slices.Contains(nodeAttrs, tailcfg.NodeAttrFunnel) {
return errors.New("Funnel not available; \"funnel\" node attribute not set. See https://tailscale.com/kb/1223/tailscale-funnel/.")
}
return nil
}

View File

@@ -48,30 +48,6 @@ func TestCleanMountPoint(t *testing.T) {
}
}
func TestCheckHasAccess(t *testing.T) {
tests := []struct {
caps []string
wantErr bool
}{
{[]string{}, true}, // No "funnel" attribute
{[]string{tailcfg.CapabilityWarnFunnelNoInvite}, true},
{[]string{tailcfg.CapabilityWarnFunnelNoHTTPS}, true},
{[]string{tailcfg.NodeAttrFunnel}, false},
}
for _, tt := range tests {
err := checkHasAccess(tt.caps)
switch {
case err != nil && tt.wantErr,
err == nil && !tt.wantErr:
continue
case tt.wantErr:
t.Fatalf("got no error, want error")
case !tt.wantErr:
t.Fatalf("got error %v, want no error", err)
}
}
}
func TestServeConfigMutations(t *testing.T) {
// Stateful mutations, starting from an empty config.
type step struct {
@@ -143,10 +119,6 @@ func TestServeConfigMutations(t *testing.T) {
},
},
})
add(step{ // invalid port
command: cmd("--serve-port=9999 /abc proxy 3001"),
wantErr: anyErr(),
})
add(step{
command: cmd("--serve-port=8443 /abc proxy 3001"),
want: &ipn.ServeConfig{
@@ -677,7 +649,7 @@ var fakeStatus = &ipnstate.Status{
BackendState: ipn.Running.String(),
Self: &ipnstate.PeerStatus{
DNSName: "foo.test.ts.net",
Capabilities: []string{tailcfg.NodeAttrFunnel},
Capabilities: []string{tailcfg.NodeAttrFunnel, tailcfg.CapabilityFunnelPorts + "?ports=443,8443"},
},
}

View File

@@ -275,7 +275,7 @@ func isRunningOrStarting(st *ipnstate.Status) (description string, ok bool) {
}
return s, false
case ipn.NeedsMachineAuth.String():
return "Machine is not yet authorized by tailnet admin.", false
return "Machine is not yet approved by tailnet admin.", false
case ipn.Running.String(), ipn.Starting.String():
return st.BackendState, true
}

View File

@@ -584,7 +584,7 @@ func runUp(ctx context.Context, cmd string, args []string, upArgs upArgsT) (retE
if env.upArgs.json {
printUpDoneJSON(ipn.NeedsMachineAuth, "")
} else {
fmt.Fprintf(Stderr, "\nTo authorize your machine, visit (as admin):\n\n\t%s\n\n", prefs.AdminPageURL())
fmt.Fprintf(Stderr, "\nTo approve your machine, visit (as admin):\n\n\t%s\n\n", prefs.AdminPageURL())
}
case ipn.Running:
// Done full authentication process

View File

@@ -228,33 +228,48 @@ func qnapAuthn(r *http.Request) (string, *qnapAuthResponse, error) {
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},
}
u := url.URL{
Scheme: "http",
Host: "127.0.0.1:8080",
Path: "/cgi-bin/authLogin.cgi",
RawQuery: query.Encode(),
}
return qnapAuthnFinish(user, u.String())
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},
}
u := url.URL{
Scheme: "http",
Host: "127.0.0.1:8080",
Path: "/cgi-bin/authLogin.cgi",
RawQuery: query.Encode(),
}
return qnapAuthnFinish(user, u.String())
return qnapAuthnFinish(user, qnapAuthnURL(r.URL.String(), query))
}
func qnapAuthnFinish(user, url string) (string, *qnapAuthResponse, error) {

View File

@@ -3,7 +3,10 @@
package cli
import "testing"
import (
"net/url"
"testing"
)
func TestUrlOfListenAddr(t *testing.T) {
tests := []struct {
@@ -34,9 +37,64 @@ func TestUrlOfListenAddr(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
url := urlOfListenAddr(tt.in)
if url != tt.want {
t.Errorf("expected url: %q, got: %q", tt.want, url)
u := urlOfListenAddr(tt.in)
if u != tt.want {
t.Errorf("expected url: %q, got: %q", tt.want, u)
}
})
}
}
func TestQnapAuthnURL(t *testing.T) {
query := url.Values{
"qtoken": []string{"token"},
}
tests := []struct {
name string
in string
want string
}{
{
name: "localhost http",
in: "http://localhost:8088/",
want: "http://localhost:8088/cgi-bin/authLogin.cgi?qtoken=token",
},
{
name: "localhost https",
in: "https://localhost:5000/",
want: "https://localhost:5000/cgi-bin/authLogin.cgi?qtoken=token",
},
{
name: "IP http",
in: "http://10.1.20.4:80/",
want: "http://10.1.20.4:80/cgi-bin/authLogin.cgi?qtoken=token",
},
{
name: "IP6 https",
in: "https://[ff7d:0:1:2::1]/",
want: "https://[ff7d:0:1:2::1]/cgi-bin/authLogin.cgi?qtoken=token",
},
{
name: "hostname https",
in: "https://qnap.example.com/",
want: "https://qnap.example.com/cgi-bin/authLogin.cgi?qtoken=token",
},
{
name: "invalid URL",
in: "This is not a URL, it is a really really really really really really really really really really really really long string to exercise the URL truncation code in the error path.",
want: "http://localhost/cgi-bin/authLogin.cgi?qtoken=token",
},
{
name: "err != nil",
in: "http://192.168.0.%31/",
want: "http://localhost/cgi-bin/authLogin.cgi?qtoken=token",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
u := qnapAuthnURL(tt.in, query)
if u != tt.want {
t.Errorf("expected url: %q, got: %q", tt.want, u)
}
})
}

View File

@@ -79,6 +79,7 @@ tailscale.com/cmd/tailscale dependencies: (generated by github.com/tailscale/dep
tailscale.com/net/packet from tailscale.com/wgengine/filter
tailscale.com/net/ping from tailscale.com/net/netcheck
tailscale.com/net/portmapper from tailscale.com/net/netcheck+
tailscale.com/net/sockstats from tailscale.com/control/controlhttp+
tailscale.com/net/stun from tailscale.com/net/netcheck
tailscale.com/net/tlsdial from tailscale.com/derp/derphttp+
tailscale.com/net/tsaddr from tailscale.com/net/interfaces+
@@ -121,6 +122,7 @@ tailscale.com/cmd/tailscale dependencies: (generated by github.com/tailscale/dep
tailscale.com/util/quarantine from tailscale.com/cmd/tailscale/cli
tailscale.com/util/set from tailscale.com/health+
tailscale.com/util/singleflight from tailscale.com/net/dnscache
tailscale.com/util/slicesx from tailscale.com/net/dnscache+
💣 tailscale.com/util/winutil from tailscale.com/hostinfo+
tailscale.com/version from tailscale.com/cmd/tailscale/cli+
tailscale.com/version/distro from tailscale.com/cmd/tailscale/cli+

View File

@@ -6,4 +6,3 @@ package main
//go:generate go run tailscale.com/cmd/mkmanifest amd64 windows-manifest.xml manifest_windows_amd64.syso
//go:generate go run tailscale.com/cmd/mkmanifest 386 windows-manifest.xml manifest_windows_386.syso
//go:generate go run tailscale.com/cmd/mkmanifest arm64 windows-manifest.xml manifest_windows_arm64.syso
//go:generate go run tailscale.com/cmd/mkmanifest arm windows-manifest.xml manifest_windows_arm.syso

View File

@@ -14,24 +14,18 @@ import (
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httptrace"
"net/netip"
"net/url"
"os"
"strings"
"time"
"tailscale.com/derp/derphttp"
"tailscale.com/envknob"
"tailscale.com/ipn"
"tailscale.com/net/interfaces"
"tailscale.com/net/portmapper"
"tailscale.com/net/tshttpproxy"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
"tailscale.com/types/logger"
"tailscale.com/wgengine/monitor"
)
@@ -229,95 +223,5 @@ func checkDerp(ctx context.Context, derpRegion string) (err error) {
}
func debugPortmap(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
portmapper.VerboseLogs = true
switch envknob.String("TS_DEBUG_PORTMAP_TYPE") {
case "":
case "pmp":
portmapper.DisablePCP = true
portmapper.DisableUPnP = true
case "pcp":
portmapper.DisablePMP = true
portmapper.DisableUPnP = true
case "upnp":
portmapper.DisablePCP = true
portmapper.DisablePMP = true
default:
log.Fatalf("TS_DEBUG_PORTMAP_TYPE must be one of pmp,pcp,upnp")
}
done := make(chan bool, 1)
var c *portmapper.Client
logf := log.Printf
c = portmapper.NewClient(logger.WithPrefix(logf, "portmapper: "), func() {
logf("portmapping changed.")
logf("have mapping: %v", c.HaveMapping())
if ext, ok := c.GetCachedMappingOrStartCreatingOne(); ok {
logf("cb: mapping: %v", ext)
select {
case done <- true:
default:
}
return
}
logf("cb: no mapping")
})
linkMon, err := monitor.New(logger.WithPrefix(logf, "monitor: "))
if err != nil {
return err
}
gatewayAndSelfIP := func() (gw, self netip.Addr, ok bool) {
if v := os.Getenv("TS_DEBUG_GW_SELF"); strings.Contains(v, "/") {
i := strings.Index(v, "/")
gw = netip.MustParseAddr(v[:i])
self = netip.MustParseAddr(v[i+1:])
return gw, self, true
}
return linkMon.GatewayAndSelfIP()
}
c.SetGatewayLookupFunc(gatewayAndSelfIP)
gw, selfIP, ok := gatewayAndSelfIP()
if !ok {
logf("no gateway or self IP; %v", linkMon.InterfaceState())
return nil
}
logf("gw=%v; self=%v", gw, selfIP)
uc, err := net.ListenPacket("udp", "0.0.0.0:0")
if err != nil {
return err
}
defer uc.Close()
c.SetLocalPort(uint16(uc.LocalAddr().(*net.UDPAddr).Port))
res, err := c.Probe(ctx)
if err != nil {
return fmt.Errorf("Probe: %v", err)
}
logf("Probe: %+v", res)
if !res.PCP && !res.PMP && !res.UPnP {
logf("no portmapping services available")
return nil
}
if ext, ok := c.GetCachedMappingOrStartCreatingOne(); ok {
logf("mapping: %v", ext)
} else {
logf("no mapping")
}
select {
case <-done:
return nil
case <-ctx.Done():
return ctx.Err()
}
return fmt.Errorf("this flag has been deprecated in favour of 'tailscale debug portmap'")
}

View File

@@ -246,6 +246,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de
tailscale.com/net/proxymux from tailscale.com/cmd/tailscaled
tailscale.com/net/routetable from tailscale.com/doctor/routetable
tailscale.com/net/socks5 from tailscale.com/cmd/tailscaled
tailscale.com/net/sockstats from tailscale.com/control/controlclient+
tailscale.com/net/stun from tailscale.com/net/netcheck+
tailscale.com/net/tlsdial from tailscale.com/control/controlclient+
tailscale.com/net/tsaddr from tailscale.com/ipn+
@@ -298,11 +299,14 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de
tailscale.com/util/lineread from tailscale.com/hostinfo+
tailscale.com/util/mak from tailscale.com/control/controlclient+
tailscale.com/util/multierr from tailscale.com/control/controlclient+
tailscale.com/util/must from tailscale.com/logpolicy
tailscale.com/util/osshare from tailscale.com/ipn/ipnlocal+
W tailscale.com/util/pidowner from tailscale.com/ipn/ipnauth
tailscale.com/util/racebuild from tailscale.com/logpolicy
tailscale.com/util/ringbuffer from tailscale.com/wgengine/magicsock
tailscale.com/util/set from tailscale.com/health+
tailscale.com/util/singleflight from tailscale.com/control/controlclient+
tailscale.com/util/slicesx from tailscale.com/net/dnscache+
tailscale.com/util/systemd from tailscale.com/control/controlclient+
tailscale.com/util/uniq from tailscale.com/wgengine/magicsock+
tailscale.com/util/vizerror from tailscale.com/tsweb
@@ -410,7 +414,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de
encoding/xml from github.com/tailscale/goupnp+
errors from bufio+
expvar from tailscale.com/derp+
flag from tailscale.com/control/controlclient+
flag from net/http/httptest+
fmt from compress/flate+
hash from crypto+
hash/adler32 from tailscale.com/ipn/ipnlocal

View File

@@ -6,4 +6,3 @@ package main
//go:generate go run tailscale.com/cmd/mkmanifest amd64 windows-manifest.xml manifest_windows_amd64.syso
//go:generate go run tailscale.com/cmd/mkmanifest 386 windows-manifest.xml manifest_windows_386.syso
//go:generate go run tailscale.com/cmd/mkmanifest arm64 windows-manifest.xml manifest_windows_arm64.syso
//go:generate go run tailscale.com/cmd/mkmanifest arm windows-manifest.xml manifest_windows_arm.syso

View File

@@ -38,13 +38,31 @@ class App extends Component<{}, AppState> {
if (ipnState === "NeedsMachineAuth") {
machineAuthInstructions = (
<div class="container mx-auto px-4 text-center">
An administrator needs to authorize this device.
An administrator needs to approve this device.
</div>
)
}
const lockedOut = netMap?.lockedOut
let lockedOutInstructions
if (lockedOut) {
lockedOutInstructions = (
<div class="container mx-auto px-4 text-center space-y-4">
<p>This instance of Tailscale Connect needs to be signed, due to
{" "}<a href="https://tailscale.com/kb/1226/tailnet-lock/" class="link">tailnet lock</a>{" "}
being enabled on this domain.
</p>
<p>
Run the following command on a device with a trusted tailnet lock key:
<pre>tailscale lock sign {netMap.self.nodeKey}</pre>
</p>
</div>
)
}
let ssh
if (ipn && ipnState === "Running" && netMap) {
if (ipn && ipnState === "Running" && netMap && !lockedOut) {
ssh = <SSH netMap={netMap} ipn={ipn} />
}
@@ -55,6 +73,7 @@ class App extends Component<{}, AppState> {
<div class="flex-grow flex flex-col justify-center overflow-hidden">
{urlDisplay}
{machineAuthInstructions}
{lockedOutInstructions}
{ssh}
</div>
</>

View File

@@ -30,7 +30,7 @@ const STATE_LABELS = {
NoState: "Initializing…",
InUseOtherUser: "In-use by another user",
NeedsLogin: "Needs login",
NeedsMachineAuth: "Needs authorization",
NeedsMachineAuth: "Needs approval",
Stopped: "Stopped",
Starting: "Starting…",
Running: "Running",

View File

@@ -60,11 +60,11 @@ function SSHSession({
function NoSSHPeers() {
return (
<div class="container mx-auto px-4 text-center">
None of your machines have
None of your machines have{" "}
<a href="https://tailscale.com/kb/1193/tailscale-ssh/" class="link">
Tailscale SSH
</a>
enabled. Give it a try!
{" "}enabled. Give it a try!
</div>
)
}

View File

@@ -63,6 +63,7 @@ declare global {
type IPNNetMap = {
self: IPNNetMapSelfNode
peers: IPNNetMapPeerNode[]
lockedOut: boolean
}
type IPNNetMapNode = {

View File

@@ -272,6 +272,7 @@ func (i *jsIPN) run(jsCallbacks js.Value) {
TailscaleSSHEnabled: p.Hostinfo.TailscaleSSHEnabled(),
}
}),
LockedOut: nm.TKAEnabled && len(nm.SelfNode.KeySignature) == 0,
}
if jsonNetMap, err := json.Marshal(jsNetMap); err == nil {
jsCallbacks.Call("notifyNetMap", string(jsonNetMap))
@@ -521,8 +522,9 @@ func (w termWriter) Write(p []byte) (n int, err error) {
}
type jsNetMap struct {
Self jsNetMapSelfNode `json:"self"`
Peers []jsNetMapPeerNode `json:"peers"`
Self jsNetMapSelfNode `json:"self"`
Peers []jsNetMapPeerNode `json:"peers"`
LockedOut bool `json:"lockedOut"`
}
type jsNetMapNode struct {

View File

@@ -13,6 +13,7 @@ import (
"tailscale.com/health"
"tailscale.com/logtail/backoff"
"tailscale.com/net/sockstats"
"tailscale.com/tailcfg"
"tailscale.com/types/empty"
"tailscale.com/types/key"
@@ -58,15 +59,17 @@ type Auto struct {
mu sync.Mutex // mutex guards the following fields
paused bool // whether we should stop making HTTP requests
unpauseWaiters []chan struct{}
loggedIn bool // true if currently logged in
loginGoal *LoginGoal // non-nil if some login activity is desired
synced bool // true if our netmap is up-to-date
inPollNetMap bool // true if currently running a PollNetMap
inLiteMapUpdate bool // true if a lite (non-streaming) map request is outstanding
inSendStatus int // number of sendStatus calls currently in progress
state State
paused bool // whether we should stop making HTTP requests
unpauseWaiters []chan struct{}
loggedIn bool // true if currently logged in
loginGoal *LoginGoal // non-nil if some login activity is desired
synced bool // true if our netmap is up-to-date
inPollNetMap bool // true if currently running a PollNetMap
inLiteMapUpdate bool // true if a lite (non-streaming) map request is outstanding
liteMapUpdateCancel context.CancelFunc // cancels a lite map update, may be nil
liteMapUpdateCancels int // how many times we've canceled a lite map update
inSendStatus int // number of sendStatus calls currently in progress
state State
authCtx context.Context // context used for auth requests
mapCtx context.Context // context used for netmap requests
@@ -118,7 +121,11 @@ func NewNoStart(opts Options) (_ *Auto, err error) {
statusFunc: opts.Status,
}
c.authCtx, c.authCancel = context.WithCancel(context.Background())
c.authCtx = sockstats.WithSockStats(c.authCtx, sockstats.LabelControlClientAuto)
c.mapCtx, c.mapCancel = context.WithCancel(context.Background())
c.mapCtx = sockstats.WithSockStats(c.mapCtx, sockstats.LabelControlClientAuto)
c.unregisterHealthWatch = health.RegisterWatcher(direct.ReportHealthChange)
return c, nil
@@ -163,28 +170,56 @@ func (c *Auto) Start() {
func (c *Auto) sendNewMapRequest() {
c.mu.Lock()
// If we're not already streaming a netmap, or if we're already stuck
// in a lite update, then tear down everything and start a new stream
// (which starts by sending a new map request)
if !c.inPollNetMap || c.inLiteMapUpdate || !c.loggedIn {
// If we're not already streaming a netmap, then tear down everything
// and start a new stream (which starts by sending a new map request)
if !c.inPollNetMap || !c.loggedIn {
c.mu.Unlock()
c.cancelMapSafely()
return
}
// If we are already in process of doing a LiteMapUpdate, cancel it and
// try a new one. If this is the 10th time we have done this
// cancelation, tear down everything and start again.
const maxLiteMapUpdateAttempts = 10
if c.inLiteMapUpdate {
// Always cancel the in-flight lite map update, regardless of
// whether we cancel the streaming map request or not.
c.liteMapUpdateCancel()
c.inLiteMapUpdate = false
if c.liteMapUpdateCancels >= maxLiteMapUpdateAttempts {
// Not making progress
c.mu.Unlock()
c.cancelMapSafely()
return
}
// Increment our cancel counter and continue below to start a
// new lite update.
c.liteMapUpdateCancels++
}
// Otherwise, send a lite update that doesn't keep a
// long-running stream response.
defer c.mu.Unlock()
c.inLiteMapUpdate = true
ctx, cancel := context.WithTimeout(c.mapCtx, 10*time.Second)
c.liteMapUpdateCancel = cancel
go func() {
defer cancel()
t0 := time.Now()
err := c.direct.SendLiteMapUpdate(ctx)
d := time.Since(t0).Round(time.Millisecond)
c.mu.Lock()
c.inLiteMapUpdate = false
c.liteMapUpdateCancel = nil
if err == nil {
c.liteMapUpdateCancels = 0
}
c.mu.Unlock()
if err == nil {
c.logf("[v1] successful lite map update in %v", d)
return
@@ -192,10 +227,13 @@ func (c *Auto) sendNewMapRequest() {
if ctx.Err() == nil {
c.logf("lite map update after %v: %v", d, err)
}
// Fall back to restarting the long-polling map
// request (the old heavy way) if the lite update
// failed for any reason.
c.cancelMapSafely()
if !errors.Is(ctx.Err(), context.Canceled) {
// Fall back to restarting the long-polling map
// request (the old heavy way) if the lite update
// failed for reasons other than the context being
// canceled.
c.cancelMapSafely()
}
}()
}
@@ -206,6 +244,7 @@ func (c *Auto) cancelAuth() {
}
if !c.closed {
c.authCtx, c.authCancel = context.WithCancel(context.Background())
c.authCtx = sockstats.WithSockStats(c.authCtx, sockstats.LabelControlClientAuto)
}
c.mu.Unlock()
}
@@ -216,6 +255,8 @@ func (c *Auto) cancelMapLocked() {
}
if !c.closed {
c.mapCtx, c.mapCancel = context.WithCancel(context.Background())
c.mapCtx = sockstats.WithSockStats(c.mapCtx, sockstats.LabelControlClientAuto)
}
}
@@ -229,6 +270,12 @@ func (c *Auto) cancelMapSafely() {
c.mu.Lock()
defer c.mu.Unlock()
// Always reset our lite map cancels counter if we're canceling
// everything, since we're about to restart with a new map update; this
// allows future calls to sendNewMapRequest to retry sending lite
// updates.
c.liteMapUpdateCancels = 0
c.logf("[v1] cancelMapSafely: synced=%v", c.synced)
if c.inPollNetMap {

View File

@@ -7,10 +7,11 @@ import (
"bufio"
"bytes"
"context"
"crypto/ed25519"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
@@ -87,16 +88,15 @@ type Direct struct {
sfGroup singleflight.Group[struct{}, *NoiseClient] // protects noiseClient creation.
noiseClient *NoiseClient
persist persist.PersistView
authKey string
tryingNewKey key.NodePrivate
expiry *time.Time
hostinfo *tailcfg.Hostinfo // always non-nil
netinfo *tailcfg.NetInfo
endpoints []tailcfg.Endpoint
tkaHead string
everEndpoints bool // whether we've ever had non-empty endpoints
lastPingURL string // last PingRequest.URL received, for dup suppression
persist persist.PersistView
authKey string
tryingNewKey key.NodePrivate
expiry *time.Time
hostinfo *tailcfg.Hostinfo // always non-nil
netinfo *tailcfg.NetInfo
endpoints []tailcfg.Endpoint
tkaHead string
lastPingURL string // last PingRequest.URL received, for dup suppression
}
type Options struct {
@@ -212,6 +212,7 @@ func NewDirect(opts Options) (*Direct, error) {
Forward: dnscache.Get().Forward, // use default cache's forwarder
UseLastGood: true,
LookupIPFallback: dnsfallback.Lookup,
Logf: opts.Logf,
}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.Proxy = tshttpproxy.ProxyFromEnvironment
@@ -424,7 +425,7 @@ func (c *Direct) doLogin(ctx context.Context, opt loginOpt) (mustRegen bool, new
tryingNewKey := c.tryingNewKey
serverKey := c.serverKey
serverNoiseKey := c.serverNoiseKey
authKey := c.authKey
authKey, isWrapped, wrappedSig, wrappedKey := decodeWrappedAuthkey(c.authKey, c.logf)
hi := c.hostInfoLocked()
backendLogID := hi.BackendLogID
expired := c.expiry != nil && !c.expiry.IsZero() && c.expiry.Before(c.timeNow())
@@ -510,6 +511,22 @@ func (c *Direct) doLogin(ctx context.Context, opt loginOpt) (mustRegen bool, new
if nodeKeySignature, err = resignNKS(persist.NetworkLockKey, tryingNewKey.Public(), opt.OldNodeKeySignature); err != nil {
c.logf("Failed re-signing node-key signature: %v", err)
}
} else if isWrapped {
// We were given a wrapped pre-auth key, which means that in addition
// to being a regular pre-auth key there was a suffix with information to
// generate a tailnet-lock signature.
nk, err := tryingNewKey.Public().MarshalBinary()
if err != nil {
return false, "", nil, fmt.Errorf("marshalling node-key: %w", err)
}
sig := &tka.NodeKeySignature{
SigKind: tka.SigRotation,
Pubkey: nk,
Nested: wrappedSig,
}
sigHash := sig.SigHash()
sig.Signature = ed25519.Sign(wrappedKey, sigHash[:])
nodeKeySignature = sig.Serialize()
}
if backendLogID == "" {
@@ -735,9 +752,6 @@ func (c *Direct) newEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
}
c.logf("[v2] client.newEndpoints(%v)", epStrs)
c.endpoints = append(c.endpoints[:0], endpoints...)
if len(endpoints) > 0 {
c.everEndpoints = true
}
return true // changed
}
@@ -750,8 +764,6 @@ func (c *Direct) SetEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
return c.newEndpoints(endpoints)
}
func inTest() bool { return flag.Lookup("test.v") != nil }
// PollNetMap makes a /map request to download the network map, calling cb with
// each new netmap.
func (c *Direct) PollNetMap(ctx context.Context, cb func(*netmap.NetworkMap)) error {
@@ -806,7 +818,6 @@ func (c *Direct) sendMapRequest(ctx context.Context, maxPolls int, readOnly bool
epStrs = append(epStrs, ep.Addr.String())
epTypes = append(epTypes, ep.Type)
}
everEndpoints := c.everEndpoints
c.mu.Unlock()
machinePrivKey, err := c.getMachinePrivKey()
@@ -847,15 +858,17 @@ func (c *Direct) sendMapRequest(ctx context.Context, maxPolls int, readOnly bool
OmitPeers: cb == nil,
TKAHead: c.tkaHead,
// On initial startup before we know our endpoints, set the ReadOnly flag
// to tell the control server not to distribute out our (empty) endpoints to peers.
// Presumably we'll learn our endpoints in a half second and do another post
// with useful results. The first POST just gets us the DERP map which we
// need to do the STUN queries to discover our endpoints.
// TODO(bradfitz): we skip this optimization in tests, though,
// because the e2e tests are currently hyper-specific about the
// ordering of things. The e2e tests need love.
ReadOnly: readOnly || (len(epStrs) == 0 && !everEndpoints && !inTest()),
// Previously we'd set ReadOnly to true if we didn't have any endpoints
// yet as we expected to learn them in a half second and restart the full
// streaming map poll, however as we are trying to reduce the number of
// times we restart the full streaming map poll we now just set ReadOnly
// false when we're doing a full streaming map poll.
//
// TODO(maisem/bradfitz): really ReadOnly should be set to true if for
// all streams and we should only do writes via lite map updates.
// However that requires an audit and a bunch of testing to make sure we
// don't break anything.
ReadOnly: readOnly && !allowStream,
}
var extraDebugFlags []string
if hi != nil && c.linkMon != nil && !c.skipIPForwardingCheck &&
@@ -1713,6 +1726,43 @@ func (c *Direct) ReportHealthChange(sys health.Subsystem, sysErr error) {
res.Body.Close()
}
// decodeWrappedAuthkey separates wrapping information from an authkey, if any.
// In all cases the authkey is returned, sans wrapping information if any.
//
// If the authkey is wrapped, isWrapped returns true, along with the wrapping signature
// and private key.
func decodeWrappedAuthkey(key string, logf logger.Logf) (authKey string, isWrapped bool, sig *tka.NodeKeySignature, priv ed25519.PrivateKey) {
authKey, suffix, found := strings.Cut(key, "--TL")
if !found {
return key, false, nil, nil
}
sigBytes, privBytes, found := strings.Cut(suffix, "-")
if !found {
logf("decoding wrapped auth-key: did not find delimiter")
return key, false, nil, nil
}
rawSig, err := base64.RawStdEncoding.DecodeString(sigBytes)
if err != nil {
logf("decoding wrapped auth-key: signature decode: %v", err)
return key, false, nil, nil
}
rawPriv, err := base64.RawStdEncoding.DecodeString(privBytes)
if err != nil {
logf("decoding wrapped auth-key: priv decode: %v", err)
return key, false, nil, nil
}
sig = new(tka.NodeKeySignature)
if err := sig.Unserialize([]byte(rawSig)); err != nil {
logf("decoding wrapped auth-key: signature: %v", err)
return key, false, nil, nil
}
priv = ed25519.PrivateKey(rawPriv)
return authKey, true, sig, priv
}
var (
metricMapRequestsActive = clientmetric.NewGauge("controlclient_map_requests_active")

View File

@@ -4,6 +4,7 @@
package controlclient
import (
"crypto/ed25519"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -142,3 +143,42 @@ func TestTsmpPing(t *testing.T) {
t.Fatal(err)
}
}
func TestDecodeWrappedAuthkey(t *testing.T) {
k, isWrapped, sig, priv := decodeWrappedAuthkey("tskey-32mjsdkdsffds9o87dsfkjlh", nil)
if want := "tskey-32mjsdkdsffds9o87dsfkjlh"; k != want {
t.Errorf("decodeWrappedAuthkey(<unwrapped-key>).key = %q, want %q", k, want)
}
if isWrapped {
t.Error("decodeWrappedAuthkey(<unwrapped-key>).isWrapped = true, want false")
}
if sig != nil {
t.Errorf("decodeWrappedAuthkey(<unwrapped-key>).sig = %v, want nil", sig)
}
if priv != nil {
t.Errorf("decodeWrappedAuthkey(<unwrapped-key>).priv = %v, want nil", priv)
}
k, isWrapped, sig, priv = decodeWrappedAuthkey("tskey-auth-k7UagY1CNTRL-ZZZZZ--TLpAEDA1ggnXuw4/fWnNWUwcoOjLemhOvml1juMl5lhLmY5sBUsj8EWEAfL2gdeD9g8VDw5tgcxCiHGlEb67BgU2DlFzZApi4LheLJraA+pYjTGChVhpZz1iyiBPD+U2qxDQAbM3+WFY0EBlggxmVqG53Hu0Rg+KmHJFMlUhfgzo+AQP6+Kk9GzvJJOs4-k36RdoSFqaoARfQo0UncHAV0t3YTqrkD5r/z2jTrE43GZWobnce7RGD4qYckUyVSF+DOj4BA/r4qT0bO8kk6zg", nil)
if want := "tskey-auth-k7UagY1CNTRL-ZZZZZ"; k != want {
t.Errorf("decodeWrappedAuthkey(<wrapped-key>).key = %q, want %q", k, want)
}
if !isWrapped {
t.Error("decodeWrappedAuthkey(<wrapped-key>).isWrapped = false, want true")
}
if sig == nil {
t.Fatal("decodeWrappedAuthkey(<wrapped-key>).sig = nil, want non-nil signature")
}
sigHash := sig.SigHash()
if !ed25519.Verify(sig.KeyID, sigHash[:], sig.Signature) {
t.Error("signature failed to verify")
}
// Make sure the private is correct by using it.
someSig := ed25519.Sign(priv, []byte{1, 2, 3, 4})
if !ed25519.Verify(sig.WrappingPubkey, []byte{1, 2, 3, 4}, someSig) {
t.Error("failed to use priv")
}
}

View File

@@ -13,6 +13,7 @@ import (
"go4.org/mem"
"tailscale.com/tailcfg"
"tailscale.com/tstest"
"tailscale.com/types/key"
"tailscale.com/types/netmap"
"tailscale.com/types/opt"
@@ -21,12 +22,11 @@ import (
)
func TestUndeltaPeers(t *testing.T) {
defer func(old func() time.Time) { clockNow = old }(clockNow)
var curTime time.Time
clockNow = func() time.Time {
tstest.Replace(t, &clockNow, func() time.Time {
return curTime
}
})
online := func(v bool) func(*tailcfg.Node) {
return func(n *tailcfg.Node) {
n.Online = &v

View File

@@ -41,6 +41,7 @@ import (
"tailscale.com/net/dnscache"
"tailscale.com/net/dnsfallback"
"tailscale.com/net/netutil"
"tailscale.com/net/sockstats"
"tailscale.com/net/tlsdial"
"tailscale.com/net/tshttpproxy"
"tailscale.com/tailcfg"
@@ -272,6 +273,8 @@ func (a *Dialer) dialHost(ctx context.Context, addr netip.Addr) (*ClientConn, er
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctx = sockstats.WithSockStats(ctx, sockstats.LabelControlClientDialer)
// u80 and u443 are the URLs we'll try to hit over HTTP or HTTPS,
// respectively, in order to do the HTTP upgrade to a net.Conn over which
// we'll speak Noise.
@@ -385,12 +388,14 @@ func (a *Dialer) tryURLUpgrade(ctx context.Context, u *url.URL, addr netip.Addr,
dns = &dnscache.Resolver{
SingleHostStaticResult: []netip.Addr{addr},
SingleHost: u.Hostname(),
Logf: a.Logf, // not a.logf method; we want to propagate nil-ness
}
} else {
dns = &dnscache.Resolver{
Forward: dnscache.Get().Forward,
LookupIPFallback: dnsfallback.Lookup,
UseLastGood: true,
Logf: a.Logf, // not a.logf method; we want to propagate nil-ness
}
}

View File

@@ -32,6 +32,7 @@ import (
"tailscale.com/envknob"
"tailscale.com/net/dnscache"
"tailscale.com/net/netns"
"tailscale.com/net/sockstats"
"tailscale.com/net/tlsdial"
"tailscale.com/net/tshttpproxy"
"tailscale.com/syncs"
@@ -320,7 +321,7 @@ func (c *Client) connect(ctx context.Context, caller string) (client *derp.Clien
}
c.serverPubKey = derpClient.ServerPublicKey()
c.client = derpClient
c.netConn = tcpConn
c.netConn = conn
c.connGen++
return c.client, c.connGen, nil
case c.url != nil:
@@ -615,6 +616,8 @@ func (c *Client) dialNode(ctx context.Context, n *tailcfg.DERPNode) (net.Conn, e
ctx, cancel := context.WithTimeout(ctx, dialNodeTimeout)
defer cancel()
ctx = sockstats.WithSockStats(ctx, sockstats.LabelDERPHTTPClient)
nwait := 0
startDial := func(dstPrimary, proto string) {
nwait++

View File

@@ -42,6 +42,7 @@ var (
regBool = map[string]*bool{}
regOptBool = map[string]*opt.Bool{}
regDuration = map[string]*time.Duration{}
regInt = map[string]*int{}
)
func noteEnv(k, v string) {
@@ -182,6 +183,25 @@ func RegisterDuration(envVar string) func() time.Duration {
return func() time.Duration { return *p }
}
// RegisterInt returns a func that gets the named environment variable as an
// integer, without a map lookup per call. It assumes that any mutations happen
// via envknob.Setenv.
func RegisterInt(envVar string) func() int {
mu.Lock()
defer mu.Unlock()
p, ok := regInt[envVar]
if !ok {
val := os.Getenv(envVar)
if val != "" {
noteEnvLocked(envVar, val)
}
p = new(int)
setIntLocked(p, envVar, val)
regInt[envVar] = p
}
return func() int { return *p }
}
func setBoolLocked(p *bool, envVar, val string) {
noteEnvLocked(envVar, val)
if val == "" {
@@ -221,6 +241,19 @@ func setDurationLocked(p *time.Duration, envVar, val string) {
}
}
func setIntLocked(p *int, envVar, val string) {
noteEnvLocked(envVar, val)
if val == "" {
*p = 0
return
}
var err error
*p, err = strconv.Atoi(val)
if err != nil {
log.Fatalf("invalid int environment variable %s value %q", envVar, val)
}
}
// Bool returns the boolean value of the named environment variable.
// If the variable is not set, it returns false.
// An invalid value exits the binary with a failure.

View File

@@ -108,10 +108,11 @@
graphviz
perl
go_1_20
yarn
];
};
};
in
flake-utils.lib.eachDefaultSystem (system: flakeForSystem nixpkgs system);
}
# nix-direnv cache busting line: sha256-zyyqBRFPNPzPYCMgnbnOy5rb3fkn4XEHZlTlJvwqunM=
# nix-direnv cache busting line: sha256-LIvaxSo+4LuHUk8DIZ27IaRQwaDnjW6Jwm5AEc/V95A=

3
go.mod
View File

@@ -85,6 +85,7 @@ require (
gvisor.dev/gvisor v0.0.0-20221203005347-703fd9b7fbc0
honnef.co/go/tools v0.4.0-0.dev.0.20230130122044-c30b15588105
inet.af/peercred v0.0.0-20210906144145-0893ea02156a
inet.af/tcpproxy v0.0.0-20221017015627-91f861402626
inet.af/wf v0.0.0-20220728202103-50d96caab2f6
k8s.io/api v0.25.0
k8s.io/apimachinery v0.25.0
@@ -304,7 +305,7 @@ require (
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/exp/typeparams v0.0.0-20221208152030-732eee02a75a // indirect
golang.org/x/image v0.0.0-20201208152932-35266b937fa6 // indirect
golang.org/x/image v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect
google.golang.org/appengine v1.6.7 // indirect

View File

@@ -1 +1 @@
sha256-zyyqBRFPNPzPYCMgnbnOy5rb3fkn4XEHZlTlJvwqunM=
sha256-LIvaxSo+4LuHUk8DIZ27IaRQwaDnjW6Jwm5AEc/V95A=

13
go.sum
View File

@@ -126,6 +126,7 @@ github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
@@ -1270,6 +1271,7 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
@@ -1357,8 +1359,9 @@ golang.org/x/exp/typeparams v0.0.0-20221208152030-732eee02a75a h1:Jw5wfR+h9mnIYH
golang.org/x/exp/typeparams v0.0.0-20221208152030-732eee02a75a/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20201208152932-35266b937fa6 h1:nfeHNc1nAqecKCy2FCy4HY+soOOe5sDLJ/gZLbx6GYI=
golang.org/x/image v0.0.0-20201208152932-35266b937fa6/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.5.0 h1:5JMiNunQeQw++mMOz48/ISeNu3Iweh/JaZU8ZLqHRrI=
golang.org/x/image v0.5.0/go.mod h1:FVC7BI/5Ym8R25iw5OLsgshdUBbT1h5jZTpA+mvAdZ4=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -1384,6 +1387,7 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA=
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -1446,6 +1450,7 @@ golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qx
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
@@ -1478,6 +1483,7 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -1586,8 +1592,10 @@ golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220622161953-175b2fd9d664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.4.1-0.20230131160137-e7d7f63158de/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -1725,6 +1733,7 @@ golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.6/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/tools v0.1.8-0.20211102182255-bb4add04ddef/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.4.1-0.20221208213631-3f74d914ae6d h1:9ZNWAi4CYhNv60mXGgAncgq7SGc5qa7C8VZV8Tg7Ggs=
golang.org/x/tools v0.4.1-0.20221208213631-3f74d914ae6d/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -1939,6 +1948,8 @@ howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
inet.af/peercred v0.0.0-20210906144145-0893ea02156a h1:qdkS8Q5/i10xU2ArJMKYhVa1DORzBfYS/qA2UK2jheg=
inet.af/peercred v0.0.0-20210906144145-0893ea02156a/go.mod h1:FjawnflS/udxX+SvpsMgZfdqx2aykOlkISeAsADi5IU=
inet.af/tcpproxy v0.0.0-20221017015627-91f861402626 h1:2dMP3Ox/Wh5BiItwOt4jxRsfzkgyBrHzx2nW28Yg6nc=
inet.af/tcpproxy v0.0.0-20221017015627-91f861402626/go.mod h1:Tojt5kmHpDIR2jMojxzZK2w2ZR7OILODmUo2gaSwjrk=
inet.af/wf v0.0.0-20220728202103-50d96caab2f6 h1:BfgDtKnWJTeu+xI1aOEweXdPwqOhB3IbQUDj1XuftcY=
inet.af/wf v0.0.0-20220728202103-50d96caab2f6/go.mod h1:bSAQ38BYbY68uwpasXOTZo22dKGy9SNvI6PZFeKomZE=
k8s.io/api v0.25.0 h1:H+Q4ma2U/ww0iGB78ijZx6DRByPz6/733jIuFpX70e0=

View File

@@ -1 +1 @@
ec180cbca39fcb5dc420399b37583e53fcf382c9
db4dc9046c93dde2c0e534ca7d529bd690ad09c9

View File

@@ -36,6 +36,7 @@ func New() *tailcfg.Hostinfo {
return &tailcfg.Hostinfo{
IPNVersion: version.Long(),
Hostname: hostname,
App: appTypeCached(),
OS: version.OS(),
OSVersion: GetOSVersion(),
Container: lazyInContainer.Get(),
@@ -112,6 +113,13 @@ func GetOSVersion() string {
return ""
}
func appTypeCached() string {
if v, ok := appType.Load().(string); ok {
return v
}
return ""
}
func packageTypeCached() string {
if v, _ := packagingType.Load().(string); v != "" {
return v
@@ -159,6 +167,7 @@ var (
osVersionAtomic atomic.Value // of string
desktopAtomic atomic.Value // of opt.Bool
packagingType atomic.Value // of string
appType atomic.Value // of string
)
// SetPushDeviceToken sets the device token for use in Hostinfo updates.
@@ -176,6 +185,11 @@ func SetOSVersion(v string) { osVersionAtomic.Store(v) }
// F-Droid build) and tsnet (set to "tsnet").
func SetPackage(v string) { packagingType.Store(v) }
// SetApp sets the app type for the app.
// It is used by tsnet to specify what app is using it such as "golinks"
// and "k8s-operator".
func SetApp(v string) { appType.Store(v) }
func deviceModel() string {
s, _ := deviceModelAtomic.Load().(string)
return s

View File

@@ -150,6 +150,22 @@ type LocalBackend struct {
shutdownCalled bool // if Shutdown has been called
debugSink *capture.Sink
// getTCPHandlerForFunnelFlow returns a handler for an incoming TCP flow for
// the provided srcAddr and dstPort if one exists.
//
// srcAddr is the source address of the flow, not the address of the Funnel
// node relaying the flow.
// dstPort is the destination port of the flow.
//
// It returns nil if there is no known handler for this flow.
//
// This is specifically used to handle TCP flows for Funnel connections to tsnet
// servers.
//
// It is set once during initialization, and can be nil if SetTCPHandlerForFunnelFlow
// is never called.
getTCPHandlerForFunnelFlow func(srcAddr netip.AddrPort, dstPort uint16) (handler func(net.Conn))
// lastProfileID tracks the last profile we've seen from the ProfileManager.
// It's used to detect when the user has changed their profile.
lastProfileID ipn.ProfileID
@@ -2520,9 +2536,6 @@ func (b *LocalBackend) checkSSHPrefsLocked(p *ipn.Prefs) error {
if version.IsSandboxedMacOS() {
return errors.New("The Tailscale SSH server does not run in sandboxed Tailscale GUI builds.")
}
if !envknob.UseWIPCode() {
return errors.New("The Tailscale SSH server is disabled on macOS tailscaled by default. To try, set env TAILSCALE_USE_WIP_CODE=1")
}
case "freebsd", "openbsd":
default:
return errors.New("The Tailscale SSH server is not supported on " + runtime.GOOS)
@@ -3117,6 +3130,12 @@ func dnsConfigForNetmap(nm *netmap.NetworkMap, prefs ipn.PrefsView, logf logger.
return dcfg
}
// SetTCPHandlerForFunnelFlow sets the TCP handler for Funnel flows.
// It should only be called before the LocalBackend is used.
func (b *LocalBackend) SetTCPHandlerForFunnelFlow(h func(src netip.AddrPort, dstPort uint16) (handler func(net.Conn))) {
b.getTCPHandlerForFunnelFlow = h
}
// SetVarRoot sets the root directory of Tailscale's writable
// storage area . (e.g. "/var/lib/tailscale")
//
@@ -3326,7 +3345,7 @@ var (
// peerRoutes returns the routerConfig.Routes to access peers.
// If there are over cgnatThreshold CGNAT routes, one big CGNAT route
// is used instead.
func peerRoutes(peers []wgcfg.Peer, cgnatThreshold int) (routes []netip.Prefix) {
func peerRoutes(logf logger.Logf, peers []wgcfg.Peer, cgnatThreshold int) (routes []netip.Prefix) {
tsULA := tsaddr.TailscaleULARange()
cgNAT := tsaddr.CGNATRange()
var didULA bool
@@ -3334,6 +3353,18 @@ func peerRoutes(peers []wgcfg.Peer, cgnatThreshold int) (routes []netip.Prefix)
for _, peer := range peers {
for _, aip := range peer.AllowedIPs {
aip = unmapIPPrefix(aip)
// Ensure that we're only accepting properly-masked
// prefixes; the control server should be masking
// these, so if we get them, skip.
if mm := aip.Masked(); aip != mm {
// To avoid a DoS where a peer could cause all
// reconfigs to fail by sending a bad prefix, we just
// skip, but don't error, on an unmasked route.
logf("advertised route %s from %s has non-address bits set; expected %s", aip, peer.PublicKey.ShortString(), mm)
continue
}
// Only add the Tailscale IPv6 ULA once, if we see anybody using part of it.
if aip.Addr().Is6() && aip.IsSingleIP() && tsULA.Contains(aip.Addr()) {
if !didULA {
@@ -3366,12 +3397,13 @@ func (b *LocalBackend) routerConfig(cfg *wgcfg.Config, prefs ipn.PrefsView, oneC
if oneCGNATRoute {
singleRouteThreshold = 1
}
rs := &router.Config{
LocalAddrs: unmapIPPrefixes(cfg.Addresses),
SubnetRoutes: unmapIPPrefixes(prefs.AdvertiseRoutes().AsSlice()),
SNATSubnetRoutes: !prefs.NoSNAT(),
NetfilterMode: prefs.NetfilterMode(),
Routes: peerRoutes(cfg.Peers, singleRouteThreshold),
Routes: peerRoutes(b.logf, cfg.Peers, singleRouteThreshold),
}
if distro.Get() == distro.Synology {
@@ -3669,6 +3701,21 @@ func (b *LocalBackend) resetControlClientLockedAsync() {
if b.cc == nil {
return
}
// When we clear the control client, stop any outstanding netmap expiry
// timer; synthesizing a new netmap while we don't have a control
// client will break things.
//
// See https://github.com/tailscale/tailscale/issues/7392
if b.nmExpiryTimer != nil {
b.nmExpiryTimer.Stop()
b.nmExpiryTimer = nil
// Also bump the epoch to ensure that if the timer started, it
// will abort.
b.numClientStatusCalls.Add(1)
}
go b.cc.Shutdown()
b.cc = nil
b.ccAuto = nil
@@ -4740,6 +4787,9 @@ func (b *LocalBackend) initTKALocked() error {
if err != nil {
return fmt.Errorf("initializing tka: %v", err)
}
if err := authority.Compact(storage, tkaCompactionDefaults); err != nil {
b.logf("tka compaction failed: %v", err)
}
b.tka = &tkaState{
profile: cp.ID,
@@ -4866,3 +4916,25 @@ func (b *LocalBackend) StreamDebugCapture(ctx context.Context, w io.Writer) erro
}
return nil
}
func (b *LocalBackend) GetPeerEndpointChanges(ctx context.Context, ip netip.Addr) ([]magicsock.EndpointChange, error) {
pip, ok := b.e.PeerForIP(ip)
if !ok {
return nil, fmt.Errorf("no matching peer")
}
if pip.IsSelf {
return nil, fmt.Errorf("%v is local Tailscale IP", ip)
}
peer := pip.Node
mc, err := b.magicConn()
if err != nil {
return nil, fmt.Errorf("getting magicsock conn: %w", err)
}
chs, err := mc.GetEndpointChanges(peer)
if err != nil {
return nil, fmt.Errorf("getting endpoint changes: %w", err)
}
return chs, nil
}

View File

@@ -21,6 +21,7 @@ import (
"tailscale.com/net/tsaddr"
"tailscale.com/tailcfg"
"tailscale.com/tstest"
"tailscale.com/types/key"
"tailscale.com/types/logger"
"tailscale.com/types/netmap"
"tailscale.com/wgengine"
@@ -333,10 +334,25 @@ func TestPeerRoutes(t *testing.T) {
pp("100.64.0.2/32"),
},
},
{
name: "skip-unmasked-prefixes",
peers: []wgcfg.Peer{
{
PublicKey: key.NewNode().Public(),
AllowedIPs: []netip.Prefix{
pp("100.64.0.2/32"),
pp("10.0.0.100/16"),
},
},
},
want: []netip.Prefix{
pp("100.64.0.2/32"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := peerRoutes(tt.peers, 2)
got := peerRoutes(t.Logf, tt.peers, 2)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("got = %v; want %v", got, tt.want)
}
@@ -481,8 +497,7 @@ func (panicOnUseTransport) RoundTrip(*http.Request) (*http.Response, error) {
// Issue 1573: don't generate a machine key if we don't want to be running.
func TestLazyMachineKeyGeneration(t *testing.T) {
defer func(old func() bool) { panicOnMachineKeyGeneration = old }(panicOnMachineKeyGeneration)
panicOnMachineKeyGeneration = func() bool { return true }
tstest.Replace(t, &panicOnMachineKeyGeneration, func() bool { return true })
var logf logger.Logf = logger.Discard
store := new(mem.Store)

View File

@@ -11,11 +11,11 @@ import (
"tailscale.com/ipn"
"tailscale.com/ipn/ipnstate"
"tailscale.com/ipn/store/mem"
"tailscale.com/logtail"
"tailscale.com/tailcfg"
"tailscale.com/tstest"
"tailscale.com/types/key"
"tailscale.com/types/logger"
"tailscale.com/types/logid"
"tailscale.com/types/persist"
"tailscale.com/wgengine"
)
@@ -37,8 +37,8 @@ func TestLocalLogLines(t *testing.T) {
// This lets the logListen tracker verify that the rate-limiter allows these key lines.
logf := logger.RateLimitedFnWithClock(logListen.Logf, 5*time.Second, 0, 10, time.Now)
logid := func(hex byte) logtail.PublicID {
var ret logtail.PublicID
logid := func(hex byte) logid.PublicID {
var ret logid.PublicID
for i := 0; i < len(ret); i++ {
ret[i] = hex
}

View File

@@ -6,7 +6,9 @@ package ipnlocal
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
@@ -37,6 +39,11 @@ import (
var (
errMissingNetmap = errors.New("missing netmap: verify that you are logged in")
errNetworkLockNotActive = errors.New("network-lock is not active")
tkaCompactionDefaults = tka.CompactionOptions{
MinChain: 24, // Keep at minimum 24 AUMs since head.
MinAge: 14 * 24 * time.Hour, // Keep 2 weeks of AUMs.
}
)
type tkaState struct {
@@ -99,6 +106,7 @@ func (b *LocalBackend) tkaFilterNetmapLocked(nm *netmap.NetworkMap) {
ID: p.ID,
StableID: p.StableID,
TailscaleIPs: make([]netip.Addr, len(p.Addresses)),
NodeKey: p.Key,
}
for i, addr := range p.Addresses {
if addr.IsSingleIP() && tsaddr.IsTailscaleIP(addr.Addr()) {
@@ -784,6 +792,98 @@ func (b *LocalBackend) NetworkLockLog(maxEntries int) ([]ipnstate.NetworkLockUpd
return out, nil
}
// NetworkLockAffectedSigs returns the signatures which would be invalidated
// by removing trust in the specified KeyID.
func (b *LocalBackend) NetworkLockAffectedSigs(keyID tkatype.KeyID) ([]tkatype.MarshaledSignature, error) {
var (
ourNodeKey key.NodePublic
err error
)
b.mu.Lock()
if p := b.pm.CurrentPrefs(); p.Valid() && p.Persist().Valid() && !p.Persist().PrivateNodeKey().IsZero() {
ourNodeKey = p.Persist().PublicNodeKey()
}
if b.tka == nil {
err = errNetworkLockNotActive
}
b.mu.Unlock()
if err != nil {
return nil, err
}
resp, err := b.tkaReadAffectedSigs(ourNodeKey, keyID)
if err != nil {
return nil, err
}
b.mu.Lock()
defer b.mu.Unlock()
if b.tka == nil {
return nil, errNetworkLockNotActive
}
// Confirm for ourselves tha the signatures would actually be invalidated
// by removal of trusted in the specified key.
for i, sigBytes := range resp.Signatures {
var sig tka.NodeKeySignature
if err := sig.Unserialize(sigBytes); err != nil {
return nil, fmt.Errorf("failed decoding signature %d: %w", i, err)
}
sigKeyID, err := sig.UnverifiedAuthorizingKeyID()
if err != nil {
return nil, fmt.Errorf("extracting SigID from signature %d: %w", i, err)
}
if !bytes.Equal(keyID, sigKeyID) {
return nil, fmt.Errorf("got signature with keyID %X from request for %X", sigKeyID, keyID)
}
var nodeKey key.NodePublic
if err := nodeKey.UnmarshalBinary(sig.Pubkey); err != nil {
return nil, fmt.Errorf("failed decoding pubkey for signature %d: %w", i, err)
}
if err := b.tka.authority.NodeKeyAuthorized(nodeKey, sigBytes); err != nil {
return nil, fmt.Errorf("signature %d is not valid: %w", i, err)
}
}
return resp.Signatures, nil
}
var tkaSuffixEncoder = base64.RawStdEncoding
// NetworkLockWrapPreauthKey wraps a pre-auth key with information to
// enable unattended bringup in the locked tailnet.
//
// The provided trusted tailnet-lock key is used to sign
// a SigCredential structure, which is encoded along with the
// private key and appended to the pre-auth key.
func (b *LocalBackend) NetworkLockWrapPreauthKey(preauthKey string, tkaKey key.NLPrivate) (string, error) {
b.mu.Lock()
defer b.mu.Unlock()
if b.tka == nil {
return "", errNetworkLockNotActive
}
pub, priv, err := ed25519.GenerateKey(nil) // nil == crypto/rand
if err != nil {
return "", err
}
sig := tka.NodeKeySignature{
SigKind: tka.SigCredential,
KeyID: tkaKey.KeyID(),
WrappingPubkey: pub,
}
sig.Signature, err = tkaKey.SignNKS(sig.SigHash())
if err != nil {
return "", fmt.Errorf("signing failed: %w", err)
}
b.logf("Generated network-lock credential signature using %s", tkaKey.Public().CLIString())
return fmt.Sprintf("%s--TL%s-%s", preauthKey, tkaSuffixEncoder.EncodeToString(sig.Serialize()), tkaSuffixEncoder.EncodeToString(priv)), nil
}
func signNodeKey(nodeInfo tailcfg.TKASignInfo, signer key.NLPrivate) (*tka.NodeKeySignature, error) {
p, err := nodeInfo.NodePublic.MarshalBinary()
if err != nil {
@@ -1110,3 +1210,39 @@ func (b *LocalBackend) tkaSubmitSignature(ourNodeKey key.NodePublic, sig tkatype
return a, nil
}
func (b *LocalBackend) tkaReadAffectedSigs(ourNodeKey key.NodePublic, key tkatype.KeyID) (*tailcfg.TKASignaturesUsingKeyResponse, error) {
var encodedReq bytes.Buffer
if err := json.NewEncoder(&encodedReq).Encode(tailcfg.TKASignaturesUsingKeyRequest{
Version: tailcfg.CurrentCapabilityVersion,
NodeKey: ourNodeKey,
KeyID: key,
}); err != nil {
return nil, fmt.Errorf("encoding request: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", "https://unused/machine/tka/affected-sigs", &encodedReq)
if err != nil {
return nil, fmt.Errorf("req: %w", err)
}
resp, err := b.DoNoiseRequest(req)
if err != nil {
return nil, fmt.Errorf("resp: %w", err)
}
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
return nil, fmt.Errorf("request returned (%d): %s", resp.StatusCode, string(body))
}
a := new(tailcfg.TKASignaturesUsingKeyResponse)
err = json.NewDecoder(&io.LimitedReader{R: resp.Body, N: 1024 * 1024}).Decode(a)
resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("decoding JSON: %w", err)
}
return a, nil
}

View File

@@ -7,6 +7,7 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
@@ -877,3 +878,135 @@ func TestTKAForceDisable(t *testing.T) {
t.Fatal("tka was re-initalized")
}
}
func TestTKAAffectedSigs(t *testing.T) {
nodePriv := key.NewNode()
// toSign := key.NewNode()
nlPriv := key.NewNLPrivate()
pm := must.Get(newProfileManager(new(mem.Store), t.Logf))
must.Do(pm.SetPrefs((&ipn.Prefs{
Persist: &persist.Persist{
PrivateNodeKey: nodePriv,
NetworkLockKey: nlPriv,
},
}).View()))
// Make a fake TKA authority, to seed local state.
disablementSecret := bytes.Repeat([]byte{0xa5}, 32)
tkaKey := tka.Key{Kind: tka.Key25519, Public: nlPriv.Public().Verifier(), Votes: 2}
temp := t.TempDir()
tkaPath := filepath.Join(temp, "tka-profile", string(pm.CurrentProfile().ID))
os.Mkdir(tkaPath, 0755)
chonk, err := tka.ChonkDir(tkaPath)
if err != nil {
t.Fatal(err)
}
authority, _, err := tka.Create(chonk, tka.State{
Keys: []tka.Key{tkaKey},
DisablementSecrets: [][]byte{tka.DisablementKDF(disablementSecret)},
}, nlPriv)
if err != nil {
t.Fatalf("tka.Create() failed: %v", err)
}
untrustedKey := key.NewNLPrivate()
tcs := []struct {
name string
makeSig func() *tka.NodeKeySignature
wantErr string
}{
{
"no error",
func() *tka.NodeKeySignature {
sig, _ := signNodeKey(tailcfg.TKASignInfo{NodePublic: nodePriv.Public()}, nlPriv)
return sig
},
"",
},
{
"signature for different keyID",
func() *tka.NodeKeySignature {
sig, _ := signNodeKey(tailcfg.TKASignInfo{NodePublic: nodePriv.Public()}, untrustedKey)
return sig
},
fmt.Sprintf("got signature with keyID %X from request for %X", untrustedKey.KeyID(), nlPriv.KeyID()),
},
{
"invalid signature",
func() *tka.NodeKeySignature {
sig, _ := signNodeKey(tailcfg.TKASignInfo{NodePublic: nodePriv.Public()}, nlPriv)
copy(sig.Signature, []byte{1, 2, 3, 4, 5, 6}) // overwrite with trash to invalid signature
return sig
},
"signature 0 is not valid: invalid signature",
},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
s := tc.makeSig()
ts, client := fakeNoiseServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
switch r.URL.Path {
case "/machine/tka/affected-sigs":
body := new(tailcfg.TKASignaturesUsingKeyRequest)
if err := json.NewDecoder(r.Body).Decode(body); err != nil {
t.Fatal(err)
}
if body.Version != tailcfg.CurrentCapabilityVersion {
t.Errorf("sign CapVer = %v, want %v", body.Version, tailcfg.CurrentCapabilityVersion)
}
if body.NodeKey != nodePriv.Public() {
t.Errorf("nodeKey = %v, want %v", body.NodeKey, nodePriv.Public())
}
w.WriteHeader(200)
if err := json.NewEncoder(w).Encode(tailcfg.TKASignaturesUsingKeyResponse{
Signatures: []tkatype.MarshaledSignature{s.Serialize()},
}); err != nil {
t.Fatal(err)
}
default:
t.Errorf("unhandled endpoint path: %v", r.URL.Path)
w.WriteHeader(404)
}
}))
defer ts.Close()
cc := fakeControlClient(t, client)
b := LocalBackend{
varRoot: temp,
cc: cc,
ccAuto: cc,
logf: t.Logf,
tka: &tkaState{
authority: authority,
storage: chonk,
},
pm: pm,
store: pm.Store(),
}
sigs, err := b.NetworkLockAffectedSigs(nlPriv.KeyID())
switch {
case tc.wantErr == "" && err != nil:
t.Errorf("NetworkLockAffectedSigs() failed: %v", err)
case tc.wantErr != "" && err == nil:
t.Errorf("NetworkLockAffectedSigs().err = nil, want %q", tc.wantErr)
case tc.wantErr != "" && err.Error() != tc.wantErr:
t.Errorf("NetworkLockAffectedSigs().err = %q, want %q", err.Error(), tc.wantErr)
}
if tc.wantErr == "" {
if len(sigs) != 1 {
t.Fatalf("len(sigs) = %d, want 1", len(sigs))
}
if !bytes.Equal(s.Serialize(), sigs[0]) {
t.Errorf("unexpected signature: got %v, want %v", sigs[0], s.Serialize())
}
}
})
}
}

View File

@@ -45,6 +45,7 @@ import (
"tailscale.com/net/interfaces"
"tailscale.com/net/netaddr"
"tailscale.com/net/netutil"
"tailscale.com/net/sockstats"
"tailscale.com/tailcfg"
"tailscale.com/util/clientmetric"
"tailscale.com/util/multierr"
@@ -670,7 +671,7 @@ func (h *peerAPIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
if peerAPIRequestShouldGetSecurityHeaders(r) {
w.Header().Set("Content-Security-Policy", `default-src 'none'; frame-ancestors 'none'; script-src 'none'; script-src-elem 'none'; script-src-attr 'none'`)
w.Header().Set("Content-Security-Policy", `default-src 'none'; frame-ancestors 'none'; script-src 'none'; script-src-elem 'none'; script-src-attr 'none'; style-src 'unsafe-inline'`)
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-Content-Type-Options", "nosniff")
}
@@ -709,6 +710,8 @@ func (h *peerAPIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
case "/v0/doctor":
h.handleServeDoctor(w, r)
case "/v0/sockstats":
h.handleServeSockStats(w, r)
return
case "/v0/ingress":
metricIngressCalls.Add(1)
@@ -758,12 +761,12 @@ func (h *peerAPIHandler) handleServeIngress(w http.ResponseWriter, r *http.Reque
bad("Tailscale-Ingress-Src header invalid; want ip:port")
return
}
target := r.Header.Get("Tailscale-Ingress-Target")
target := ipn.HostPort(r.Header.Get("Tailscale-Ingress-Target"))
if target == "" {
bad("Tailscale-Ingress-Target header not set")
return
}
if _, _, err := net.SplitHostPort(target); err != nil {
if _, _, err := net.SplitHostPort(string(target)); err != nil {
bad("Tailscale-Ingress-Target header invalid; want host:port")
return
}
@@ -776,13 +779,17 @@ func (h *peerAPIHandler) handleServeIngress(w http.ResponseWriter, r *http.Reque
return nil, false
}
io.WriteString(conn, "HTTP/1.1 101 Switching Protocols\r\n\r\n")
return conn, true
return &ipn.FunnelConn{
Conn: conn,
Src: srcAddr,
Target: target,
}, true
}
sendRST := func() {
http.Error(w, "denied", http.StatusForbidden)
}
h.ps.b.HandleIngressTCPConn(h.peerNode, ipn.HostPort(target), srcAddr, getConn, sendRST)
h.ps.b.HandleIngressTCPConn(h.peerNode, target, srcAddr, getConn, sendRST)
}
func (h *peerAPIHandler) handleServeInterfaces(w http.ResponseWriter, r *http.Request) {
@@ -799,15 +806,21 @@ func (h *peerAPIHandler) handleServeInterfaces(w http.ResponseWriter, r *http.Re
fmt.Fprintf(w, "<h3>Could not get the default route: %s</h3>\n", html.EscapeString(err.Error()))
}
if hasCGNATInterface, err := interfaces.HasCGNATInterface(); hasCGNATInterface {
fmt.Fprintln(w, "<p>There is another interface using the CGNAT range.</p>")
} else if err != nil {
fmt.Fprintf(w, "<p>Could not check for CGNAT interfaces: %s</p>\n", html.EscapeString(err.Error()))
}
i, err := interfaces.GetList()
if err != nil {
fmt.Fprintf(w, "Could not get interfaces: %s\n", html.EscapeString(err.Error()))
return
}
fmt.Fprintln(w, "<table>")
fmt.Fprintln(w, "<table style='border-collapse: collapse' border=1 cellspacing=0 cellpadding=2>")
fmt.Fprint(w, "<tr>")
for _, v := range []any{"Index", "Name", "MTU", "Flags", "Addrs"} {
for _, v := range []any{"Index", "Name", "MTU", "Flags", "Addrs", "Extra"} {
fmt.Fprintf(w, "<th>%v</th> ", v)
}
fmt.Fprint(w, "</tr>\n")
@@ -816,6 +829,11 @@ func (h *peerAPIHandler) handleServeInterfaces(w http.ResponseWriter, r *http.Re
for _, v := range []any{iface.Index, iface.Name, iface.MTU, iface.Flags, ipps} {
fmt.Fprintf(w, "<td>%s</td> ", html.EscapeString(fmt.Sprintf("%v", v)))
}
if extras, err := interfaces.InterfaceDebugExtras(iface.Index); err == nil && extras != "" {
fmt.Fprintf(w, "<td>%s</td> ", html.EscapeString(extras))
} else if err != nil {
fmt.Fprintf(w, "<td>%s</td> ", html.EscapeString(err.Error()))
}
fmt.Fprint(w, "</tr>\n")
})
fmt.Fprintln(w, "</table>")
@@ -839,6 +857,91 @@ func (h *peerAPIHandler) handleServeDoctor(w http.ResponseWriter, r *http.Reques
fmt.Fprintln(w, "</pre>")
}
func (h *peerAPIHandler) handleServeSockStats(w http.ResponseWriter, r *http.Request) {
if !h.canDebug() {
http.Error(w, "denied; no debug access", http.StatusForbidden)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintln(w, "<!DOCTYPE html><h1>Socket Stats</h1>")
stats, validation := sockstats.GetWithValidation()
if stats == nil {
fmt.Fprintln(w, "No socket stats available")
return
}
fmt.Fprintln(w, "<table border='1' cellspacing='0' style='border-collapse: collapse;'>")
fmt.Fprintln(w, "<thead>")
fmt.Fprintln(w, "<th>Label</th>")
fmt.Fprintln(w, "<th>Tx</th>")
fmt.Fprintln(w, "<th>Rx</th>")
for _, iface := range stats.Interfaces {
fmt.Fprintf(w, "<th>Tx (%s)</th>", html.EscapeString(iface))
fmt.Fprintf(w, "<th>Rx (%s)</th>", html.EscapeString(iface))
}
fmt.Fprintln(w, "<th>Validation</th>")
fmt.Fprintln(w, "</thead>")
fmt.Fprintln(w, "<tbody>")
labels := make([]sockstats.Label, 0, len(stats.Stats))
for label := range stats.Stats {
labels = append(labels, label)
}
slices.SortFunc(labels, func(a, b sockstats.Label) bool {
return a.String() < b.String()
})
txTotal := uint64(0)
rxTotal := uint64(0)
txTotalByInterface := map[string]uint64{}
rxTotalByInterface := map[string]uint64{}
for _, label := range labels {
stat := stats.Stats[label]
fmt.Fprintln(w, "<tr>")
fmt.Fprintf(w, "<td>%s</td>", html.EscapeString(label.String()))
fmt.Fprintf(w, "<td align=right>%d</td>", stat.TxBytes)
fmt.Fprintf(w, "<td align=right>%d</td>", stat.RxBytes)
txTotal += stat.TxBytes
rxTotal += stat.RxBytes
for _, iface := range stats.Interfaces {
fmt.Fprintf(w, "<td align=right>%d</td>", stat.TxBytesByInterface[iface])
fmt.Fprintf(w, "<td align=right>%d</td>", stat.RxBytesByInterface[iface])
txTotalByInterface[iface] += stat.TxBytesByInterface[iface]
rxTotalByInterface[iface] += stat.RxBytesByInterface[iface]
}
if validationStat, ok := validation.Stats[label]; ok && (validationStat.RxBytes > 0 || validationStat.TxBytes > 0) {
fmt.Fprintf(w, "<td>Tx=%d (%+d) Rx=%d (%+d)</td>",
validationStat.TxBytes,
int64(validationStat.TxBytes)-int64(stat.TxBytes),
validationStat.RxBytes,
int64(validationStat.RxBytes)-int64(stat.RxBytes))
} else {
fmt.Fprintln(w, "<td></td>")
}
fmt.Fprintln(w, "</tr>")
}
fmt.Fprintln(w, "</tbody>")
fmt.Fprintln(w, "<tfoot>")
fmt.Fprintln(w, "<th>Total</th>")
fmt.Fprintf(w, "<th>%d</th>", txTotal)
fmt.Fprintf(w, "<th>%d</th>", rxTotal)
for _, iface := range stats.Interfaces {
fmt.Fprintf(w, "<th>%d</th>", txTotalByInterface[iface])
fmt.Fprintf(w, "<th>%d</th>", rxTotalByInterface[iface])
}
fmt.Fprintln(w, "<th></th>")
fmt.Fprintln(w, "</tfoot>")
fmt.Fprintln(w, "</table>")
}
type incomingFile struct {
name string // "foo.jpg"
started time.Time

View File

@@ -281,9 +281,22 @@ func (b *LocalBackend) HandleIngressTCPConn(ingressPeer *tailcfg.Node, target ip
sendRST()
return
}
dport := uint16(port16)
if b.getTCPHandlerForFunnelFlow != nil {
handler := b.getTCPHandlerForFunnelFlow(srcAddr, dport)
if handler != nil {
c, ok := getConn()
if !ok {
b.logf("localbackend: getConn didn't complete from %v to port %v", srcAddr, dport)
return
}
handler(c)
return
}
}
// TODO(bradfitz): pass ingressPeer etc in context to HandleInterceptedTCPConn,
// extend serveHTTPContext or similar.
b.HandleInterceptedTCPConn(uint16(port16), srcAddr, getConn, sendRST)
b.HandleInterceptedTCPConn(dport, srcAddr, getConn, sendRST)
}
func (b *LocalBackend) HandleInterceptedTCPConn(dport uint16, srcAddr netip.AddrPort, getConn func() (net.Conn, bool), sendRST func()) {

View File

@@ -88,6 +88,7 @@ type TKAFilteredPeer struct {
ID tailcfg.NodeID
StableID tailcfg.StableNodeID
TailscaleIPs []netip.Addr // Tailscale IP(s) assigned to this node
NodeKey key.NodePublic
}
// NetworkLockStatus represents whether network-lock is enabled,

View File

@@ -9,6 +9,7 @@ import (
"net/netip"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
)
// Clone makes a deep copy of TKAFilteredPeer.
@@ -29,4 +30,5 @@ var _TKAFilteredPeerCloneNeedsRegeneration = TKAFilteredPeer(struct {
ID tailcfg.NodeID
StableID tailcfg.StableNodeID
TailscaleIPs []netip.Addr
NodeKey key.NodePublic
}{})

View File

@@ -4,13 +4,17 @@
package localapi
import (
"crypto/tls"
"encoding/json"
"fmt"
"net"
"net/http"
"strconv"
"tailscale.com/derp/derphttp"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
)
func (h *Handler) serveDebugDERPRegion(w http.ResponseWriter, r *http.Request) {
@@ -51,6 +55,9 @@ func (h *Handler) serveDebugDERPRegion(w http.ResponseWriter, r *http.Request) {
return
}
st.Info = append(st.Info, fmt.Sprintf("Region %v == %q", reg.RegionID, reg.RegionCode))
if len(dm.Regions) == 1 {
st.Warnings = append(st.Warnings, "Having only a single DERP region (i.e. removing the default Tailscale-provided regions) is a single point of failure and could hamper connectivity")
}
if reg.Avoid {
st.Warnings = append(st.Warnings, "Region is marked with Avoid bit")
@@ -60,10 +67,120 @@ func (h *Handler) serveDebugDERPRegion(w http.ResponseWriter, r *http.Request) {
return
}
ctx := r.Context()
var (
dialer net.Dialer
client *http.Client = http.DefaultClient
)
checkConn := func(derpNode *tailcfg.DERPNode) bool {
port := firstNonzero(derpNode.DERPPort, 443)
var (
hasIPv4 bool
hasIPv6 bool
)
// Check IPv4 first
addr := net.JoinHostPort(firstNonzero(derpNode.IPv4, derpNode.HostName), strconv.Itoa(port))
conn, err := dialer.DialContext(ctx, "tcp4", addr)
if err != nil {
st.Errors = append(st.Errors, fmt.Sprintf("Error connecting to node %q @ %q over IPv4: %v", derpNode.HostName, addr, err))
} else {
defer conn.Close()
// Upgrade to TLS and verify that works properly.
tlsConn := tls.Client(conn, &tls.Config{
ServerName: firstNonzero(derpNode.CertName, derpNode.HostName),
})
if err := tlsConn.HandshakeContext(ctx); err != nil {
st.Errors = append(st.Errors, fmt.Sprintf("Error upgrading connection to node %q @ %q to TLS over IPv4: %v", derpNode.HostName, addr, err))
} else {
hasIPv4 = true
}
}
// Check IPv6
addr = net.JoinHostPort(firstNonzero(derpNode.IPv6, derpNode.HostName), strconv.Itoa(port))
conn, err = dialer.DialContext(ctx, "tcp6", addr)
if err != nil {
st.Errors = append(st.Errors, fmt.Sprintf("Error connecting to node %q @ %q over IPv6: %v", derpNode.HostName, addr, err))
} else {
defer conn.Close()
// Upgrade to TLS and verify that works properly.
tlsConn := tls.Client(conn, &tls.Config{
ServerName: firstNonzero(derpNode.CertName, derpNode.HostName),
// TODO(andrew-d): we should print more
// detailed failure information on if/why TLS
// verification fails
})
if err := tlsConn.HandshakeContext(ctx); err != nil {
st.Errors = append(st.Errors, fmt.Sprintf("Error upgrading connection to node %q @ %q to TLS over IPv6: %v", derpNode.HostName, addr, err))
} else {
hasIPv6 = true
}
}
// If we only have an IPv6 conn, then warn; we want both.
if hasIPv6 && !hasIPv4 {
st.Warnings = append(st.Warnings, fmt.Sprintf("Node %q only has IPv6 connectivity, not IPv4", derpNode.HostName))
} else if hasIPv6 && hasIPv4 {
st.Info = append(st.Info, fmt.Sprintf("Node %q has working IPv4 and IPv6 connectivity", derpNode.HostName))
}
return hasIPv4 || hasIPv6
}
// Start by checking whether we can establish a HTTP connection
for _, derpNode := range reg.Nodes {
connSuccess := checkConn(derpNode)
// Verify that the /generate_204 endpoint works
captivePortalURL := "http://" + derpNode.HostName + "/generate_204"
resp, err := client.Get(captivePortalURL)
if err != nil {
st.Warnings = append(st.Warnings, fmt.Sprintf("Error making request to the captive portal check %q; is port 80 blocked?", captivePortalURL))
} else {
resp.Body.Close()
}
if !connSuccess {
continue
}
fakePrivKey := key.NewNode()
// Next, repeatedly get the server key to see if the node is
// behind a load balancer (incorrectly).
serverPubKeys := make(map[key.NodePublic]bool)
for i := 0; i < 5; i++ {
func() {
rc := derphttp.NewRegionClient(fakePrivKey, h.logf, func() *tailcfg.DERPRegion {
return &tailcfg.DERPRegion{
RegionID: reg.RegionID,
RegionCode: reg.RegionCode,
RegionName: reg.RegionName,
Nodes: []*tailcfg.DERPNode{derpNode},
}
})
if err := rc.Connect(ctx); err != nil {
st.Errors = append(st.Errors, fmt.Sprintf("Error connecting to node %q @ try %d: %v", derpNode.HostName, i, err))
return
}
if len(serverPubKeys) == 0 {
st.Info = append(st.Info, fmt.Sprintf("Successfully established a DERP connection with node %q", derpNode.HostName))
}
serverPubKeys[rc.ServerPublicKey()] = true
}()
}
if len(serverPubKeys) > 1 {
st.Errors = append(st.Errors, fmt.Sprintf("Received multiple server public keys (%d); is the DERP server behind a load balancer?", len(serverPubKeys)))
}
}
// TODO(bradfitz): finish:
// * first try TCP connection
// * reconnect 4 or 5 times; see if we ever get a different server key.
// if so, they're load balancing the wrong way. error.
// * try to DERP auth with new public key.
// * if rejected, add Info that it's likely the DERP server authz is on,
// try with LocalBackend's node key instead.
@@ -75,17 +192,17 @@ func (h *Handler) serveDebugDERPRegion(w http.ResponseWriter, r *http.Request) {
// in DERPRegion. Or maybe even list all their server pub keys that it's peered
// with.
// * try STUN queries
// * warn about IPv6 only
// * If their certificate is bad, either expired or just wrongly
// issued in the first place, tell them specifically that the
// cert is bad not just that the connection failed.
// * If /generate_204 on port 80 cannot be reached, warn
// that they won't get captive portal detection and
// should allow port 80.
// * If they have exactly one DERP region because they
// removed all of Tailscale's DERPs, warn that they have
// a SPOF that will hamper even direct connections from
// working. (warning, not error, as that's probably a likely
// config for headscale users)
st.Info = append(st.Info, "TODO: 🦉")
}
func firstNonzero[T comparable](items ...T) T {
var zero T
for _, item := range items {
if item != zero {
return item
}
}
return zero
}

View File

@@ -35,6 +35,7 @@ import (
"tailscale.com/ipn/ipnstate"
"tailscale.com/logtail"
"tailscale.com/net/netutil"
"tailscale.com/net/portmapper"
"tailscale.com/tailcfg"
"tailscale.com/tka"
"tailscale.com/types/key"
@@ -44,6 +45,7 @@ import (
"tailscale.com/util/httpm"
"tailscale.com/util/mak"
"tailscale.com/version"
"tailscale.com/wgengine/monitor"
)
type localAPIHandler func(*Handler, http.ResponseWriter, *http.Request)
@@ -68,6 +70,8 @@ var handler = map[string]localAPIHandler{
"debug-derp-region": (*Handler).serveDebugDERPRegion,
"debug-packet-filter-matches": (*Handler).serveDebugPacketFilterMatches,
"debug-packet-filter-rules": (*Handler).serveDebugPacketFilterRules,
"debug-portmap": (*Handler).serveDebugPortmap,
"debug-peer-endpoint-changes": (*Handler).serveDebugPeerEndpointChanges,
"debug-capture": (*Handler).serveDebugCapture,
"derpmap": (*Handler).serveDERPMap,
"dev-set-state-store": (*Handler).serveDevSetStateStore,
@@ -96,6 +100,8 @@ var handler = map[string]localAPIHandler{
"tka/status": (*Handler).serveTKAStatus,
"tka/disable": (*Handler).serveTKADisable,
"tka/force-local-disable": (*Handler).serveTKALocalDisable,
"tka/affected-sigs": (*Handler).serveTKAAffectedSigs,
"tka/wrap-preauth-key": (*Handler).serveTKAWrapPreauthKey,
"upload-client-metrics": (*Handler).serveUploadClientMetrics,
"watch-ipn-bus": (*Handler).serveWatchIPNBus,
"whois": (*Handler).serveWhoIs,
@@ -150,7 +156,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "server has no local backend", http.StatusInternalServerError)
return
}
if r.Referer() != "" || r.Header.Get("Origin") != "" || !validHost(r.Host) {
if r.Referer() != "" || r.Header.Get("Origin") != "" || !h.validHost(r.Host) {
metricInvalidRequests.Add(1)
http.Error(w, "invalid localapi request", http.StatusForbidden)
return
@@ -180,21 +186,20 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
// validLocalHost allows either localhost or loopback IP hosts on platforms
// that use token security.
var validLocalHost = runtime.GOOS == "darwin" || runtime.GOOS == "ios" || runtime.GOOS == "android"
// validLocalHostForTesting allows loopback handlers without RequiredPassword for testing.
var validLocalHostForTesting = false
// validHost reports whether h is a valid Host header value for a LocalAPI request.
func validHost(h string) bool {
func (h *Handler) validHost(hostname string) bool {
// The client code sends a hostname of "local-tailscaled.sock".
switch h {
switch hostname {
case "", apitype.LocalAPIHost:
return true
}
if !validLocalHost {
return false
if !validLocalHostForTesting && h.RequiredPassword == "" {
return false // only allow localhost with basic auth or in tests
}
host, _, err := net.SplitHostPort(h)
host, _, err := net.SplitHostPort(hostname)
if err != nil {
return false
}
@@ -601,6 +606,153 @@ func (h *Handler) serveDebugPacketFilterMatches(w http.ResponseWriter, r *http.R
enc.Encode(nm.PacketFilter)
}
func (h *Handler) serveDebugPortmap(w http.ResponseWriter, r *http.Request) {
if !h.PermitWrite {
http.Error(w, "debug access denied", http.StatusForbidden)
return
}
w.Header().Set("Content-Type", "text/plain")
dur, err := time.ParseDuration(r.FormValue("duration"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
gwSelf := r.FormValue("gateway_and_self")
// Update portmapper debug flags
debugKnobs := &portmapper.DebugKnobs{VerboseLogs: true}
switch r.FormValue("type") {
case "":
case "pmp":
debugKnobs.DisablePCP = true
debugKnobs.DisableUPnP = true
case "pcp":
debugKnobs.DisablePMP = true
debugKnobs.DisableUPnP = true
case "upnp":
debugKnobs.DisablePCP = true
debugKnobs.DisablePMP = true
default:
http.Error(w, "unknown portmap debug type", http.StatusBadRequest)
return
}
var (
logLock sync.Mutex
handlerDone bool
)
logf := func(format string, args ...any) {
if !strings.HasSuffix(format, "\n") {
format = format + "\n"
}
logLock.Lock()
defer logLock.Unlock()
// The portmapper can call this log function after the HTTP
// handler returns, which is not allowed and can cause a panic.
// If this happens, ignore the log lines since this typically
// occurs due to a client disconnect.
if handlerDone {
return
}
// Write and flush each line to the client so that output is streamed
fmt.Fprintf(w, format, args...)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
defer func() {
logLock.Lock()
handlerDone = true
logLock.Unlock()
}()
ctx, cancel := context.WithTimeout(r.Context(), dur)
defer cancel()
done := make(chan bool, 1)
var c *portmapper.Client
c = portmapper.NewClient(logger.WithPrefix(logf, "portmapper: "), debugKnobs, func() {
logf("portmapping changed.")
logf("have mapping: %v", c.HaveMapping())
if ext, ok := c.GetCachedMappingOrStartCreatingOne(); ok {
logf("cb: mapping: %v", ext)
select {
case done <- true:
default:
}
return
}
logf("cb: no mapping")
})
defer c.Close()
linkMon, err := monitor.New(logger.WithPrefix(logf, "monitor: "))
if err != nil {
logf("error creating monitor: %v", err)
return
}
gatewayAndSelfIP := func() (gw, self netip.Addr, ok bool) {
if a, b, ok := strings.Cut(gwSelf, "/"); ok {
gw = netip.MustParseAddr(a)
self = netip.MustParseAddr(b)
return gw, self, true
}
return linkMon.GatewayAndSelfIP()
}
c.SetGatewayLookupFunc(gatewayAndSelfIP)
gw, selfIP, ok := gatewayAndSelfIP()
if !ok {
logf("no gateway or self IP; %v", linkMon.InterfaceState())
return
}
logf("gw=%v; self=%v", gw, selfIP)
uc, err := net.ListenPacket("udp", "0.0.0.0:0")
if err != nil {
return
}
defer uc.Close()
c.SetLocalPort(uint16(uc.LocalAddr().(*net.UDPAddr).Port))
res, err := c.Probe(ctx)
if err != nil {
logf("error in Probe: %v", err)
return
}
logf("Probe: %+v", res)
if !res.PCP && !res.PMP && !res.UPnP {
logf("no portmapping services available")
return
}
if ext, ok := c.GetCachedMappingOrStartCreatingOne(); ok {
logf("mapping: %v", ext)
} else {
logf("no mapping")
}
select {
case <-done:
case <-ctx.Done():
if r.Context().Err() == nil {
logf("serveDebugPortmap: context done: %v", ctx.Err())
} else {
h.logf("serveDebugPortmap: context done: %v", ctx.Err())
}
}
}
func (h *Handler) serveComponentDebugLogging(w http.ResponseWriter, r *http.Request) {
if !h.PermitWrite {
http.Error(w, "debug access denied", http.StatusForbidden)
@@ -718,6 +870,34 @@ func (h *Handler) serveStatus(w http.ResponseWriter, r *http.Request) {
e.Encode(st)
}
func (h *Handler) serveDebugPeerEndpointChanges(w http.ResponseWriter, r *http.Request) {
if !h.PermitRead {
http.Error(w, "status access denied", http.StatusForbidden)
return
}
ipStr := r.FormValue("ip")
if ipStr == "" {
http.Error(w, "missing 'ip' parameter", 400)
return
}
ip, err := netip.ParseAddr(ipStr)
if err != nil {
http.Error(w, "invalid IP", 400)
return
}
w.Header().Set("Content-Type", "application/json")
chs, err := h.b.GetPeerEndpointChanges(r.Context(), ip)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
e := json.NewEncoder(w)
e.SetIndent("", "\t")
e.Encode(chs)
}
// InUseOtherUserIPNStream reports whether r is a request for the watch-ipn-bus
// handler. If so, it writes an ipn.Notify InUseOtherUser message to the user
// and returns true. Otherwise it returns false, in which case it doesn't write
@@ -1391,6 +1571,40 @@ func (h *Handler) serveTKAModify(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(204)
}
func (h *Handler) serveTKAWrapPreauthKey(w http.ResponseWriter, r *http.Request) {
if !h.PermitWrite {
http.Error(w, "network-lock modify access denied", http.StatusForbidden)
return
}
if r.Method != httpm.POST {
http.Error(w, "use POST", http.StatusMethodNotAllowed)
return
}
type wrapRequest struct {
TSKey string
TKAKey string // key.NLPrivate.MarshalText
}
var req wrapRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 12*1024)).Decode(&req); err != nil {
http.Error(w, "invalid JSON body", http.StatusBadRequest)
return
}
var priv key.NLPrivate
if err := priv.UnmarshalText([]byte(req.TKAKey)); err != nil {
http.Error(w, "invalid JSON body", http.StatusBadRequest)
return
}
wrappedKey, err := h.b.NetworkLockWrapPreauthKey(req.TSKey, priv)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(200)
w.Write([]byte(wrappedKey))
}
func (h *Handler) serveTKADisable(w http.ResponseWriter, r *http.Request) {
if !h.PermitWrite {
http.Error(w, "network-lock modify access denied", http.StatusForbidden)
@@ -1470,6 +1684,32 @@ func (h *Handler) serveTKALog(w http.ResponseWriter, r *http.Request) {
w.Write(j)
}
func (h *Handler) serveTKAAffectedSigs(w http.ResponseWriter, r *http.Request) {
if r.Method != httpm.POST {
http.Error(w, "use POST", http.StatusMethodNotAllowed)
return
}
keyID, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, 2048))
if err != nil {
http.Error(w, "reading body", http.StatusBadRequest)
return
}
sigs, err := h.b.NetworkLockAffectedSigs(keyID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
j, err := json.MarshalIndent(sigs, "", "\t")
if err != nil {
http.Error(w, "JSON encoding error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}
// serveProfiles serves profile switching-related endpoints. Supported methods
// and paths are:
// - GET /profiles/: list all profiles (JSON-encoded array of ipn.LoginProfiles)

View File

@@ -14,6 +14,7 @@ import (
"tailscale.com/client/tailscale/apitype"
"tailscale.com/hostinfo"
"tailscale.com/ipn/ipnlocal"
"tailscale.com/tstest"
)
func TestValidHost(t *testing.T) {
@@ -23,9 +24,9 @@ func TestValidHost(t *testing.T) {
}{
{"", true},
{apitype.LocalAPIHost, true},
{"localhost:9109", validLocalHost},
{"127.0.0.1:9110", validLocalHost},
{"[::1]:9111", validLocalHost},
{"localhost:9109", false},
{"127.0.0.1:9110", false},
{"[::1]:9111", false},
{"100.100.100.100:41112", false},
{"10.0.0.1:41112", false},
{"37.16.9.210:41112", false},
@@ -33,7 +34,8 @@ func TestValidHost(t *testing.T) {
for _, test := range tests {
t.Run(test.host, func(t *testing.T) {
if got := validHost(test.host); got != test.valid {
h := &Handler{}
if got := h.validHost(test.host); got != test.valid {
t.Errorf("validHost(%q)=%v, want %v", test.host, got, test.valid)
}
})
@@ -41,11 +43,7 @@ func TestValidHost(t *testing.T) {
}
func TestSetPushDeviceToken(t *testing.T) {
origValidLocalHost := validLocalHost
validLocalHost = true
defer func() {
validLocalHost = origValidLocalHost
}()
tstest.Replace(t, &validLocalHostForTesting, true)
h := &Handler{
PermitWrite: true,

View File

@@ -3,6 +3,19 @@
package ipn
import (
"errors"
"fmt"
"net"
"net/netip"
"net/url"
"strconv"
"strings"
"golang.org/x/exp/slices"
"tailscale.com/tailcfg"
)
// ServeConfigKey returns a StateKey that stores the
// JSON-encoded ServeConfig for a config profile.
func ServeConfigKey(profileID ProfileID) StateKey {
@@ -29,6 +42,26 @@ type ServeConfig struct {
// There is no implicit port 443. It must contain a colon.
type HostPort string
// A FunnelConn wraps a net.Conn that is coming over a
// Funnel connection. It can be used to determine further
// information about the connection, like the source address
// and the target SNI name.
type FunnelConn struct {
// Conn is the underlying connection.
net.Conn
// Target is what was presented in the "Tailscale-Ingress-Target"
// HTTP header.
Target HostPort
// Src is the source address of the connection.
// This is the address of the client that initiated the
// connection, not the address of the Tailscale Funnel
// node which is relaying the connection. That address
// can be found in Conn.RemoteAddr.
Src netip.AddrPort
}
// WebServerConfig describes a web server's configuration.
type WebServerConfig struct {
Handlers map[string]*HTTPHandler // mountPoint => handler
@@ -143,3 +176,83 @@ func (sc *ServeConfig) IsFunnelOn() bool {
}
return false
}
// CheckFunnelAccess checks whether Funnel access is allowed for the given node
// and port.
// It checks:
// 1. an invite was used to join the Funnel alpha
// 2. HTTPS is enabled on the Tailnet
// 3. the node has the "funnel" nodeAttr
// 4. the port is allowed for Funnel
//
// The nodeAttrs arg should be the node's Self.Capabilities which should contain
// the attribute we're checking for and possibly warning-capabilities for
// Funnel.
func CheckFunnelAccess(port uint16, nodeAttrs []string) error {
if slices.Contains(nodeAttrs, tailcfg.CapabilityWarnFunnelNoInvite) {
return errors.New("Funnel not available; an invite is required to join the alpha. See https://tailscale.com/kb/1223/tailscale-funnel/.")
}
if slices.Contains(nodeAttrs, tailcfg.CapabilityWarnFunnelNoHTTPS) {
return errors.New("Funnel not available; HTTPS must be enabled. See https://tailscale.com/kb/1153/enabling-https/.")
}
if !slices.Contains(nodeAttrs, tailcfg.NodeAttrFunnel) {
return errors.New("Funnel not available; \"funnel\" node attribute not set. See https://tailscale.com/kb/1223/tailscale-funnel/.")
}
return checkFunnelPort(port, nodeAttrs)
}
// checkFunnelPort checks whether the given port is allowed for Funnel.
// It uses the tailcfg.CapabilityFunnelPorts nodeAttr to determine the allowed
// ports.
func checkFunnelPort(wantedPort uint16, nodeAttrs []string) error {
deny := func(allowedPorts string) error {
if allowedPorts == "" {
return fmt.Errorf("port %d is not allowed for funnel", wantedPort)
}
return fmt.Errorf("port %d is not allowed for funnel; allowed ports are: %v", wantedPort, allowedPorts)
}
var portsStr string
for _, attr := range nodeAttrs {
if !strings.HasPrefix(attr, tailcfg.CapabilityFunnelPorts) {
continue
}
u, err := url.Parse(attr)
if err != nil {
return deny("")
}
portsStr = u.Query().Get("ports")
if portsStr == "" {
return deny("")
}
u.RawQuery = ""
if u.String() != tailcfg.CapabilityFunnelPorts {
return deny("")
}
}
wantedPortString := strconv.Itoa(int(wantedPort))
for _, ps := range strings.Split(portsStr, ",") {
if ps == "" {
continue
}
first, last, ok := strings.Cut(ps, "-")
if !ok {
if first == wantedPortString {
return nil
}
continue
}
fp, err := strconv.ParseUint(first, 10, 16)
if err != nil {
continue
}
lp, err := strconv.ParseUint(last, 10, 16)
if err != nil {
continue
}
pr := tailcfg.PortRange{First: uint16(fp), Last: uint16(lp)}
if pr.Contains(wantedPort) {
return nil
}
}
return deny(portsStr)
}

40
ipn/serve_test.go Normal file
View File

@@ -0,0 +1,40 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package ipn
import (
"testing"
"tailscale.com/tailcfg"
)
func TestCheckFunnelAccess(t *testing.T) {
portAttr := "https://tailscale.com/cap/funnel-ports?ports=443,8080-8090,8443,"
tests := []struct {
port uint16
caps []string
wantErr bool
}{
{443, []string{portAttr}, true}, // No "funnel" attribute
{443, []string{portAttr, tailcfg.CapabilityWarnFunnelNoInvite}, true},
{443, []string{portAttr, tailcfg.CapabilityWarnFunnelNoHTTPS}, true},
{443, []string{portAttr, tailcfg.NodeAttrFunnel}, false},
{8443, []string{portAttr, tailcfg.NodeAttrFunnel}, false},
{8321, []string{portAttr, tailcfg.NodeAttrFunnel}, true},
{8083, []string{portAttr, tailcfg.NodeAttrFunnel}, false},
{8091, []string{portAttr, tailcfg.NodeAttrFunnel}, true},
{3000, []string{portAttr, tailcfg.NodeAttrFunnel}, true},
}
for _, tt := range tests {
err := CheckFunnelAccess(tt.port, tt.caps)
switch {
case err != nil && tt.wantErr,
err == nil && !tt.wantErr:
continue
case tt.wantErr:
t.Fatalf("got no error, want error")
case !tt.wantErr:
t.Fatalf("got error %v, want no error", err)
}
}
}

View File

@@ -14,11 +14,15 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"sync"
"time"
"tailscale.com/util/multierr"
)
const (
@@ -26,7 +30,19 @@ const (
defaultURL = "https://kubernetes.default.svc"
)
// rootPathForTests is set by tests to override the root path to the
// service account directory.
var rootPathForTests string
// SetRootPathForTesting sets the path to the service account directory.
func SetRootPathForTesting(p string) {
rootPathForTests = p
}
func readFile(n string) ([]byte, error) {
if rootPathForTests != "" {
return os.ReadFile(filepath.Join(rootPathForTests, saPath, n))
}
return os.ReadFile(filepath.Join(saPath, n))
}
@@ -68,6 +84,12 @@ func New() (*Client, error) {
}, nil
}
// SetURL sets the URL to use for the Kubernetes API.
// This is used only for testing.
func (c *Client) SetURL(url string) {
c.url = url
}
func (c *Client) expireToken() {
c.mu.Lock()
defer c.mu.Unlock()
@@ -111,28 +133,27 @@ func getError(resp *http.Response) error {
return st
}
func (c *Client) doRequest(ctx context.Context, method, url string, in, out any) error {
tk, err := c.getOrRenewToken()
func setHeader(key, value string) func(*http.Request) {
return func(req *http.Request) {
req.Header.Set(key, value)
}
}
// doRequest performs an HTTP request to the Kubernetes API.
// If in is not nil, it is expected to be a JSON-encodable object and will be
// sent as the request body.
// If out is not nil, it is expected to be a pointer to an object that can be
// decoded from JSON.
// If the request fails with a 401, the token is expired and a new one is
// requested.
func (c *Client) doRequest(ctx context.Context, method, url string, in, out any, opts ...func(*http.Request)) error {
req, err := c.newRequest(ctx, method, url, in)
if err != nil {
return err
}
var body io.Reader
if in != nil {
var b bytes.Buffer
if err := json.NewEncoder(&b).Encode(in); err != nil {
return err
}
body = &b
for _, opt := range opts {
opt(req)
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return err
}
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Authorization", "Bearer "+tk)
resp, err := c.client.Do(req)
if err != nil {
return err
@@ -150,6 +171,36 @@ func (c *Client) doRequest(ctx context.Context, method, url string, in, out any)
return nil
}
func (c *Client) newRequest(ctx context.Context, method, url string, in any) (*http.Request, error) {
tk, err := c.getOrRenewToken()
if err != nil {
return nil, err
}
var body io.Reader
if in != nil {
switch in := in.(type) {
case []byte:
body = bytes.NewReader(in)
default:
var b bytes.Buffer
if err := json.NewEncoder(&b).Encode(in); err != nil {
return nil, err
}
body = &b
}
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Authorization", "Bearer "+tk)
return req, nil
}
// GetSecret fetches the secret from the Kubernetes API.
func (c *Client) GetSecret(ctx context.Context, name string) (*Secret, error) {
s := &Secret{Data: make(map[string][]byte)}
@@ -169,3 +220,97 @@ func (c *Client) CreateSecret(ctx context.Context, s *Secret) error {
func (c *Client) UpdateSecret(ctx context.Context, s *Secret) error {
return c.doRequest(ctx, "PUT", c.secretURL(s.Name), s, nil)
}
// JSONPatch is a JSON patch operation.
// It currently (2023-03-02) only supports the "remove" operation.
//
// https://tools.ietf.org/html/rfc6902
type JSONPatch struct {
Op string `json:"op"`
Path string `json:"path"`
}
// JSONPatchSecret updates a secret in the Kubernetes API using a JSON patch.
// It currently (2023-03-02) only supports the "remove" operation.
func (c *Client) JSONPatchSecret(ctx context.Context, name string, patch []JSONPatch) error {
for _, p := range patch {
if p.Op != "remove" {
panic(fmt.Errorf("unsupported JSON patch operation: %q", p.Op))
}
}
return c.doRequest(ctx, "PATCH", c.secretURL(name), patch, nil, setHeader("Content-Type", "application/json-patch+json"))
}
// StrategicMergePatchSecret updates a secret in the Kubernetes API using a
// strategic merge patch.
// If a fieldManager is provided, it will be used to track the patch.
func (c *Client) StrategicMergePatchSecret(ctx context.Context, name string, s *Secret, fieldManager string) error {
surl := c.secretURL(name)
if fieldManager != "" {
uv := url.Values{
"fieldManager": {fieldManager},
}
surl += "?" + uv.Encode()
}
s.Namespace = c.ns
s.Name = name
return c.doRequest(ctx, "PATCH", surl, s, nil, setHeader("Content-Type", "application/strategic-merge-patch+json"))
}
// CheckSecretPermissions checks the secret access permissions of the current
// pod. It returns an error if the basic permissions tailscale needs are
// missing, and reports whether the patch permission is additionally present.
//
// Errors encountered during the access checking process are logged, but ignored
// so that the pod tries to fail alive if the permissions exist and there's just
// something wrong with SelfSubjectAccessReviews. There shouldn't be, pods
// should always be able to use SSARs to assess their own permissions, but since
// we didn't use to check permissions this way we'll be cautious in case some
// old version of k8s deviates from the current behavior.
func (c *Client) CheckSecretPermissions(ctx context.Context, secretName string) (canPatch bool, err error) {
var errs []error
for _, verb := range []string{"get", "update"} {
ok, err := c.checkPermission(ctx, verb, secretName)
if err != nil {
log.Printf("error checking %s permission on secret %s: %v", verb, secretName, err)
} else if !ok {
errs = append(errs, fmt.Errorf("missing %s permission on secret %q", verb, secretName))
}
}
if len(errs) > 0 {
return false, multierr.New(errs...)
}
ok, err := c.checkPermission(ctx, "patch", secretName)
if err != nil {
log.Printf("error checking patch permission on secret %s: %v", secretName, err)
return false, nil
}
return ok, nil
}
// checkPermission reports whether the current pod has permission to use the
// given verb (e.g. get, update, patch) on secretName.
func (c *Client) checkPermission(ctx context.Context, verb, secretName string) (bool, error) {
sar := map[string]any{
"apiVersion": "authorization.k8s.io/v1",
"kind": "SelfSubjectAccessReview",
"spec": map[string]any{
"resourceAttributes": map[string]any{
"namespace": c.ns,
"verb": verb,
"resource": "secrets",
"name": secretName,
},
},
}
var res struct {
Status struct {
Allowed bool `json:"allowed"`
} `json:"status"`
}
url := c.url + "/apis/authorization.k8s.io/v1/selfsubjectaccessreviews"
if err := c.doRequest(ctx, "POST", url, sar, &res); err != nil {
return false, err
}
return res.Status.Allowed, nil
}

View File

@@ -52,15 +52,15 @@ Client][]. See also the dependencies in the [Tailscale CLI][].
- [go4.org/mem](https://pkg.go.dev/go4.org/mem) ([Apache-2.0](https://github.com/go4org/mem/blob/927187094b94/LICENSE))
- [go4.org/netipx](https://pkg.go.dev/go4.org/netipx) ([BSD-3-Clause](https://github.com/go4org/netipx/blob/7e7bdc8411bf/LICENSE))
- [go4.org/unsafe/assume-no-moving-gc](https://pkg.go.dev/go4.org/unsafe/assume-no-moving-gc) ([BSD-3-Clause](https://github.com/go4org/unsafe-assume-no-moving-gc/blob/ee73d164e760/LICENSE))
- [golang.org/x/crypto](https://pkg.go.dev/golang.org/x/crypto) ([BSD-3-Clause](https://cs.opensource.google/go/x/crypto/+/v0.3.0:LICENSE))
- [golang.org/x/crypto](https://pkg.go.dev/golang.org/x/crypto) ([BSD-3-Clause](https://cs.opensource.google/go/x/crypto/+/v0.6.0:LICENSE))
- [golang.org/x/exp](https://pkg.go.dev/golang.org/x/exp) ([BSD-3-Clause](https://cs.opensource.google/go/x/exp/+/47842c84:LICENSE))
- [golang.org/x/exp/shiny](https://pkg.go.dev/golang.org/x/exp/shiny) ([BSD-3-Clause](https://cs.opensource.google/go/x/exp/+/334a2380:shiny/LICENSE))
- [golang.org/x/image](https://pkg.go.dev/golang.org/x/image) ([BSD-3-Clause](https://cs.opensource.google/go/x/image/+/062f8c9f:LICENSE))
- [golang.org/x/net](https://pkg.go.dev/golang.org/x/net) ([BSD-3-Clause](https://cs.opensource.google/go/x/net/+/v0.5.0:LICENSE))
- [golang.org/x/image](https://pkg.go.dev/golang.org/x/image) ([BSD-3-Clause](https://cs.opensource.google/go/x/image/+/v0.5.0:LICENSE))
- [golang.org/x/net](https://pkg.go.dev/golang.org/x/net) ([BSD-3-Clause](https://cs.opensource.google/go/x/net/+/v0.7.0:LICENSE))
- [golang.org/x/sync/errgroup](https://pkg.go.dev/golang.org/x/sync/errgroup) ([BSD-3-Clause](https://cs.opensource.google/go/x/sync/+/v0.1.0:LICENSE))
- [golang.org/x/sys](https://pkg.go.dev/golang.org/x/sys) ([BSD-3-Clause](https://cs.opensource.google/go/x/sys/+/e7d7f631:LICENSE))
- [golang.org/x/term](https://pkg.go.dev/golang.org/x/term) ([BSD-3-Clause](https://cs.opensource.google/go/x/term/+/v0.4.0:LICENSE))
- [golang.org/x/text](https://pkg.go.dev/golang.org/x/text) ([BSD-3-Clause](https://cs.opensource.google/go/x/text/+/v0.6.0:LICENSE))
- [golang.org/x/sys](https://pkg.go.dev/golang.org/x/sys) ([BSD-3-Clause](https://cs.opensource.google/go/x/sys/+/v0.5.0:LICENSE))
- [golang.org/x/term](https://pkg.go.dev/golang.org/x/term) ([BSD-3-Clause](https://cs.opensource.google/go/x/term/+/v0.5.0:LICENSE))
- [golang.org/x/text](https://pkg.go.dev/golang.org/x/text) ([BSD-3-Clause](https://cs.opensource.google/go/x/text/+/v0.7.0:LICENSE))
- [golang.org/x/time/rate](https://pkg.go.dev/golang.org/x/time/rate) ([BSD-3-Clause](https://cs.opensource.google/go/x/time/+/579cf78f:LICENSE))
- [gvisor.dev/gvisor/pkg](https://pkg.go.dev/gvisor.dev/gvisor/pkg) ([Apache-2.0](https://github.com/google/gvisor/blob/703fd9b7fbc0/LICENSE))
- [inet.af/netaddr](https://pkg.go.dev/inet.af/netaddr) ([BSD-3-Clause](https://github.com/inetaf/netaddr/blob/097006376321/LICENSE))

View File

@@ -42,7 +42,7 @@ and [iOS][]. See also the dependencies in the [Tailscale CLI][].
- [go4.org/mem](https://pkg.go.dev/go4.org/mem) ([Apache-2.0](https://github.com/go4org/mem/blob/4f986261bf13/LICENSE))
- [go4.org/netipx](https://pkg.go.dev/go4.org/netipx) ([BSD-3-Clause](https://github.com/go4org/netipx/blob/7e7bdc8411bf/LICENSE))
- [golang.org/x/crypto](https://pkg.go.dev/golang.org/x/crypto) ([BSD-3-Clause](https://cs.opensource.google/go/x/crypto/+/v0.6.0:LICENSE))
- [golang.org/x/exp](https://pkg.go.dev/golang.org/x/exp) ([BSD-3-Clause](https://cs.opensource.google/go/x/exp/+/47842c84:LICENSE))
- [golang.org/x/exp](https://pkg.go.dev/golang.org/x/exp) ([BSD-3-Clause](https://cs.opensource.google/go/x/exp/+/cafedaf6:LICENSE))
- [golang.org/x/net](https://pkg.go.dev/golang.org/x/net) ([BSD-3-Clause](https://cs.opensource.google/go/x/net/+/v0.7.0:LICENSE))
- [golang.org/x/sync/errgroup](https://pkg.go.dev/golang.org/x/sync/errgroup) ([BSD-3-Clause](https://cs.opensource.google/go/x/sync/+/v0.1.0:LICENSE))
- [golang.org/x/sys](https://pkg.go.dev/golang.org/x/sys) ([BSD-3-Clause](https://cs.opensource.google/go/x/sys/+/v0.5.0:LICENSE))

View File

@@ -14,8 +14,10 @@ Windows][]. See also the dependencies in the [Tailscale CLI][].
- [github.com/alexbrainman/sspi](https://pkg.go.dev/github.com/alexbrainman/sspi) ([BSD-3-Clause](https://github.com/alexbrainman/sspi/blob/909beea2cc74/LICENSE))
- [github.com/apenwarr/fixconsole](https://pkg.go.dev/github.com/apenwarr/fixconsole) ([Apache-2.0](https://github.com/apenwarr/fixconsole/blob/5a9f6489cc29/LICENSE))
- [github.com/apenwarr/w32](https://pkg.go.dev/github.com/apenwarr/w32) ([BSD-3-Clause](https://github.com/apenwarr/w32/blob/aa00fece76ab/LICENSE))
- [github.com/dblohm7/wingoes](https://pkg.go.dev/github.com/dblohm7/wingoes) ([BSD-3-Clause](https://github.com/dblohm7/wingoes/blob/2b26ab7fb5f9/LICENSE))
- [github.com/fxamacker/cbor/v2](https://pkg.go.dev/github.com/fxamacker/cbor/v2) ([MIT](https://github.com/fxamacker/cbor/blob/v2.4.0/LICENSE))
- [github.com/golang/groupcache/lru](https://pkg.go.dev/github.com/golang/groupcache/lru) ([Apache-2.0](https://github.com/golang/groupcache/blob/41bb18bfe9da/LICENSE))
- [github.com/google/uuid](https://pkg.go.dev/github.com/google/uuid) ([BSD-3-Clause](https://github.com/google/uuid/blob/v1.3.0/LICENSE))
- [github.com/hdevalence/ed25519consensus](https://pkg.go.dev/github.com/hdevalence/ed25519consensus) ([BSD-3-Clause](https://github.com/hdevalence/ed25519consensus/blob/c00d1f31bab3/LICENSE))
- [github.com/josharian/native](https://pkg.go.dev/github.com/josharian/native) ([MIT](https://github.com/josharian/native/blob/5c7d0dd6ab86/license))
- [github.com/jsimonetti/rtnetlink](https://pkg.go.dev/github.com/jsimonetti/rtnetlink) ([MIT](https://github.com/jsimonetti/rtnetlink/blob/d380b505068b/LICENSE.md))
@@ -25,14 +27,18 @@ Windows][]. See also the dependencies in the [Tailscale CLI][].
- [github.com/mdlayher/netlink](https://pkg.go.dev/github.com/mdlayher/netlink) ([MIT](https://github.com/mdlayher/netlink/blob/v1.7.1/LICENSE.md))
- [github.com/mdlayher/socket](https://pkg.go.dev/github.com/mdlayher/socket) ([MIT](https://github.com/mdlayher/socket/blob/v0.4.0/LICENSE.md))
- [github.com/mitchellh/go-ps](https://pkg.go.dev/github.com/mitchellh/go-ps) ([MIT](https://github.com/mitchellh/go-ps/blob/v1.0.0/LICENSE.md))
- [github.com/nfnt/resize](https://pkg.go.dev/github.com/nfnt/resize) ([ISC](https://github.com/nfnt/resize/blob/83c6a9932646/LICENSE))
- [github.com/skip2/go-qrcode](https://pkg.go.dev/github.com/skip2/go-qrcode) ([MIT](https://github.com/skip2/go-qrcode/blob/da1b6568686e/LICENSE))
- [github.com/tailscale/walk](https://pkg.go.dev/github.com/tailscale/walk) ([BSD-3-Clause](https://github.com/tailscale/walk/blob/e7f9a47617c0/LICENSE))
- [github.com/tailscale/win](https://pkg.go.dev/github.com/tailscale/win) ([BSD-3-Clause](https://github.com/tailscale/win/blob/e8ccca099752/LICENSE))
- [github.com/tailscale/walk](https://pkg.go.dev/github.com/tailscale/walk) ([BSD-3-Clause](https://github.com/tailscale/walk/blob/31689615ddb4/LICENSE))
- [github.com/tailscale/win](https://pkg.go.dev/github.com/tailscale/win) ([BSD-3-Clause](https://github.com/tailscale/win/blob/ad93eed16885/LICENSE))
- [github.com/tc-hib/winres](https://pkg.go.dev/github.com/tc-hib/winres) ([0BSD](https://github.com/tc-hib/winres/blob/v0.1.6/LICENSE))
- [github.com/x448/float16](https://pkg.go.dev/github.com/x448/float16) ([MIT](https://github.com/x448/float16/blob/v0.8.4/LICENSE))
- [go4.org/mem](https://pkg.go.dev/go4.org/mem) ([Apache-2.0](https://github.com/go4org/mem/blob/4f986261bf13/LICENSE))
- [go4.org/netipx](https://pkg.go.dev/go4.org/netipx) ([BSD-3-Clause](https://github.com/go4org/netipx/blob/7e7bdc8411bf/LICENSE))
- [golang.org/x/crypto](https://pkg.go.dev/golang.org/x/crypto) ([BSD-3-Clause](https://cs.opensource.google/go/x/crypto/+/v0.6.0:LICENSE))
- [golang.org/x/exp](https://pkg.go.dev/golang.org/x/exp) ([BSD-3-Clause](https://cs.opensource.google/go/x/exp/+/47842c84:LICENSE))
- [golang.org/x/exp](https://pkg.go.dev/golang.org/x/exp) ([BSD-3-Clause](https://cs.opensource.google/go/x/exp/+/cafedaf6:LICENSE))
- [golang.org/x/image/bmp](https://pkg.go.dev/golang.org/x/image/bmp) ([BSD-3-Clause](https://cs.opensource.google/go/x/image/+/v0.5.0:LICENSE))
- [golang.org/x/mod](https://pkg.go.dev/golang.org/x/mod) ([BSD-3-Clause](https://cs.opensource.google/go/x/mod/+/v0.7.0:LICENSE))
- [golang.org/x/net](https://pkg.go.dev/golang.org/x/net) ([BSD-3-Clause](https://cs.opensource.google/go/x/net/+/v0.7.0:LICENSE))
- [golang.org/x/sync/errgroup](https://pkg.go.dev/golang.org/x/sync/errgroup) ([BSD-3-Clause](https://cs.opensource.google/go/x/sync/+/v0.1.0:LICENSE))
- [golang.org/x/sys](https://pkg.go.dev/golang.org/x/sys) ([BSD-3-Clause](https://cs.opensource.google/go/x/sys/+/v0.5.0:LICENSE))

View File

@@ -43,7 +43,9 @@ import (
"tailscale.com/safesocket"
"tailscale.com/smallzstd"
"tailscale.com/types/logger"
"tailscale.com/types/logid"
"tailscale.com/util/clientmetric"
"tailscale.com/util/must"
"tailscale.com/util/racebuild"
"tailscale.com/util/winutil"
"tailscale.com/version"
@@ -94,8 +96,8 @@ func LogHost() string {
// Config represents an instance of logs in a collection.
type Config struct {
Collection string
PrivateID logtail.PrivateID
PublicID logtail.PublicID
PrivateID logid.PrivateID
PublicID logid.PublicID
}
// Policy is a logger and its public ID.
@@ -103,15 +105,12 @@ type Policy struct {
// Logtail is the logger.
Logtail *logtail.Logger
// PublicID is the logger's instance identifier.
PublicID logtail.PublicID
PublicID logid.PublicID
}
// NewConfig creates a Config with collection and a newly generated PrivateID.
func NewConfig(collection string) *Config {
id, err := logtail.NewPrivateID()
if err != nil {
panic("logtail.NewPrivateID should never fail")
}
id := must.Get(logid.NewPrivateID())
return &Config{
Collection: collection,
PrivateID: id,

View File

@@ -125,11 +125,11 @@ The caller can query-encode the following fields:
"collections": {
"collection1.yourcompany.com": {
"instances": {
"<logtail.PublicID>" :{
"<logid.PublicID>" :{
"first-seen": "timestamp",
"size": 4096
},
"<logtail.PublicID>" :{
"<logid.PublicID>" :{
"first-seen": "timestamp",
"size": 512000,
"orphan": true,

View File

@@ -15,7 +15,7 @@ import (
"strings"
"time"
"tailscale.com/logtail"
"tailscale.com/types/logid"
)
func main() {
@@ -56,7 +56,7 @@ func main() {
log.Fatalf("logreprocess: read error %d: %s", resp.StatusCode, string(b))
}
tracebackCache := make(map[logtail.PublicID]*ProcessedMsg)
tracebackCache := make(map[logid.PublicID]*ProcessedMsg)
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
@@ -98,8 +98,8 @@ func main() {
type Msg struct {
Logtail struct {
Instance logtail.PublicID `json:"instance"`
ClientTime time.Time `json:"client_time"`
Instance logid.PublicID `json:"instance"`
ClientTime time.Time `json:"client_time"`
} `json:"logtail"`
Text string `json:"text"`
@@ -110,6 +110,6 @@ type ProcessedMsg struct {
ClientTime time.Time `json:"client_time"`
} `json:"logtail"`
OrigInstance logtail.PublicID `json:"orig_instance"`
Text string `json:"text"`
OrigInstance logid.PublicID `json:"orig_instance"`
Text string `json:"text"`
}

View File

@@ -12,6 +12,7 @@ import (
"os"
"tailscale.com/logtail"
"tailscale.com/types/logid"
)
func main() {
@@ -25,7 +26,7 @@ func main() {
log.SetFlags(0)
var id logtail.PrivateID
var id logid.PrivateID
if err := id.UnmarshalText([]byte(*privateID)); err != nil {
log.Fatalf("logtail: bad -privateid: %v", err)
}

View File

@@ -12,6 +12,8 @@ import (
"testing"
"unicode"
"unsafe"
"tailscale.com/tstest"
)
type filchTest struct {
@@ -177,10 +179,7 @@ func TestFilchStderr(t *testing.T) {
defer pipeR.Close()
defer pipeW.Close()
stderrFD = int(pipeW.Fd())
defer func() {
stderrFD = 2
}()
tstest.Replace(t, &stderrFD, int(pipeW.Fd()))
filePrefix := t.TempDir()
f := newFilchTest(t, filePrefix, Options{ReplaceStderr: true})

View File

@@ -1,27 +0,0 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package logtail
import "tailscale.com/types/logid"
// Deprecated: Use "tailscale.com/types/logid".PrivateID instead.
type PrivateID = logid.PrivateID
// Deprecated: Use "tailscale.com/types/logid".NewPrivateID instead.
func NewPrivateID() (PrivateID, error) {
return logid.NewPrivateID()
}
// Deprecated: Use "tailscale.com/types/logid".ParsePrivateID instead.
func ParsePrivateID(s string) (PrivateID, error) {
return logid.ParsePrivateID(s)
}
// Deprecated: Use "tailscale.com/types/logid".PublicID instead.
type PublicID = logid.PublicID
// Deprecated: Use "tailscale.com/types/logid".ParsePublicID instead.
func ParsePublicID(s string) (PublicID, error) {
return logid.ParsePublicID(s)
}

View File

@@ -24,7 +24,9 @@ import (
"tailscale.com/envknob"
"tailscale.com/logtail/backoff"
"tailscale.com/net/interfaces"
"tailscale.com/net/sockstats"
tslogger "tailscale.com/types/logger"
"tailscale.com/types/logid"
"tailscale.com/util/set"
"tailscale.com/wgengine/monitor"
)
@@ -48,8 +50,8 @@ type Encoder interface {
type Config struct {
Collection string // collection name, a domain name
PrivateID PrivateID // private ID for the primary log stream
CopyPrivateID PrivateID // private ID for a log stream that is a superset of this log stream
PrivateID logid.PrivateID // private ID for the primary log stream
CopyPrivateID logid.PrivateID // private ID for a log stream that is a superset of this log stream
BaseURL string // if empty defaults to "https://log.tailscale.io"
HTTPC *http.Client // if empty defaults to http.DefaultClient
SkipClientTime bool // if true, client_time is not written to logs
@@ -188,7 +190,7 @@ type Logger struct {
uploadCancel func()
explainedRaw bool
metricsDelta func() string // or nil
privateID PrivateID
privateID logid.PrivateID
httpDoCalls atomic.Int32
procID uint32
@@ -198,8 +200,9 @@ type Logger struct {
procSequence uint64
flushTimer *time.Timer // used when flushDelay is >0
shutdownStart chan struct{} // closed when shutdown begins
shutdownDone chan struct{} // closed when shutdown complete
shutdownStartMu sync.Mutex // guards the closing of shutdownStart
shutdownStart chan struct{} // closed when shutdown begins
shutdownDone chan struct{} // closed when shutdown complete
}
// SetVerbosityLevel controls the verbosity level that should be
@@ -220,7 +223,7 @@ func (l *Logger) SetLinkMonitor(lm *monitor.Mon) {
// PrivateID returns the logger's private log ID.
//
// It exists for internal use only.
func (l *Logger) PrivateID() PrivateID { return l.privateID }
func (l *Logger) PrivateID() logid.PrivateID { return l.privateID }
// Shutdown gracefully shuts down the logger while completing any
// remaining uploads.
@@ -240,7 +243,16 @@ func (l *Logger) Shutdown(ctx context.Context) error {
close(done)
}()
l.shutdownStartMu.Lock()
select {
case <-l.shutdownStart:
l.shutdownStartMu.Unlock()
return nil
default:
}
close(l.shutdownStart)
l.shutdownStartMu.Unlock()
io.WriteString(l, "logger closing down\n")
<-done
@@ -416,6 +428,7 @@ func (l *Logger) awaitInternetUp(ctx context.Context) {
// origlen of -1 indicates that the body is not compressed.
func (l *Logger) upload(ctx context.Context, body []byte, origlen int) (uploaded bool, err error) {
const maxUploadTime = 45 * time.Second
ctx = sockstats.WithSockStats(ctx, sockstats.LabelLogtailLogger)
ctx, cancel := context.WithTimeout(ctx, maxUploadTime)
defer cancel()
@@ -450,14 +463,6 @@ func (l *Logger) upload(ctx context.Context, body []byte, origlen int) (uploaded
return uploaded, fmt.Errorf("log upload of %d bytes %s failed %d: %q", len(body), compressedNote, resp.StatusCode, b)
}
// Try to read to EOF, in case server's response is
// chunked. We want to reuse the TCP connection if it's
// HTTP/1. On success, we expect 0 bytes.
// TODO(bradfitz): can remove a few days after 2020-04-04 once
// server is fixed.
if resp.ContentLength == -1 {
resp.Body.Read(make([]byte, 1))
}
return true, nil
}

View File

@@ -295,28 +295,6 @@ func TestParseAndRemoveLogLevel(t *testing.T) {
}
}
func TestPublicIDUnmarshalText(t *testing.T) {
const hexStr = "6c60a9e0e7af57170bb1347b2d477e4cbc27d4571a4923b21651456f931e3d55"
x := []byte(hexStr)
var id PublicID
if err := id.UnmarshalText(x); err != nil {
t.Fatal(err)
}
if id.String() != hexStr {
t.Errorf("String = %q; want %q", id.String(), hexStr)
}
err := tstest.MinAllocsPerRun(t, 0, func() {
var id PublicID
if err := id.UnmarshalText(x); err != nil {
t.Fatal(err)
}
})
if err != nil {
t.Fatal(err)
}
}
func unmarshalOne(t *testing.T, body []byte) map[string]any {
t.Helper()
var entries []map[string]any

View File

@@ -51,12 +51,14 @@ func NewOSConfigurator(logf logger.Logf, interfaceName string) (OSConfigurator,
ret.nrptDB = newNRPTRuleDatabase(logf)
}
// Log WSL status once at startup.
if distros, err := wslDistros(); err != nil {
logf("WSL: could not list distributions: %v", err)
} else {
logf("WSL: found %d distributions", len(distros))
}
go func() {
// Log WSL status once at startup.
if distros, err := wslDistros(); err != nil {
logf("WSL: could not list distributions: %v", err)
} else {
logf("WSL: found %d distributions", len(distros))
}
}()
return ret, nil
}

View File

@@ -26,6 +26,7 @@ import (
"tailscale.com/net/dnscache"
"tailscale.com/net/neterror"
"tailscale.com/net/netns"
"tailscale.com/net/sockstats"
"tailscale.com/net/tsdial"
"tailscale.com/types/dnstype"
"tailscale.com/types/logger"
@@ -383,6 +384,7 @@ func (f *forwarder) getKnownDoHClientForProvider(urlBase string) (c *http.Client
dialer := dnscache.Dialer(nsDialer.DialContext, &dnscache.Resolver{
SingleHost: dohURL.Hostname(),
SingleHostStaticResult: allIPs,
Logf: f.logf,
})
c = &http.Client{
Transport: &http.Transport{
@@ -406,6 +408,7 @@ func (f *forwarder) getKnownDoHClientForProvider(urlBase string) (c *http.Client
const dohType = "application/dns-message"
func (f *forwarder) sendDoH(ctx context.Context, urlBase string, c *http.Client, packet []byte) ([]byte, error) {
ctx = sockstats.WithSockStats(ctx, sockstats.LabelDNSForwarderDoH)
metricDNSFwdDoH.Add(1)
req, err := http.NewRequestWithContext(ctx, "POST", urlBase, bytes.NewReader(packet))
if err != nil {
@@ -485,6 +488,7 @@ func (f *forwarder) sendUDP(ctx context.Context, fq *forwardQuery, rr resolverAn
return nil, fmt.Errorf("unrecognized resolver type %q", rr.name.Addr)
}
metricDNSFwdUDP.Add(1)
ctx = sockstats.WithSockStats(ctx, sockstats.LabelDNSForwarderUDP)
ln, err := f.packetListener(ipp.Addr())
if err != nil {

View File

@@ -997,11 +997,8 @@ func TestMarshalResponseFormatError(t *testing.T) {
}
func TestForwardLinkSelection(t *testing.T) {
old := initListenConfig
defer func() { initListenConfig = old }()
configCall := make(chan string, 1)
initListenConfig = func(nc *net.ListenConfig, mon *monitor.Mon, tunName string) error {
tstest.Replace(t, &initListenConfig, func(nc *net.ListenConfig, mon *monitor.Mon, tunName string) error {
select {
case configCall <- tunName:
return nil
@@ -1009,7 +1006,7 @@ func TestForwardLinkSelection(t *testing.T) {
t.Error("buffer full")
return errors.New("buffer full")
}
}
})
// specialIP is some IP we pretend that our link selector
// routes differently.

View File

@@ -5,6 +5,7 @@ package dns
import (
"bytes"
"context"
"errors"
"fmt"
"os"
@@ -12,6 +13,7 @@ import (
"os/user"
"strings"
"syscall"
"time"
"golang.org/x/sys/windows"
"tailscale.com/types/logger"
@@ -20,7 +22,13 @@ import (
// wslDistros reports the names of the installed WSL2 linux distributions.
func wslDistros() ([]string, error) {
b, err := wslCombinedOutput(exec.Command("wsl.exe", "-l"))
// There is a bug in some builds of wsl.exe that causes it to block
// indefinitely while executing this operation. Set a timeout so that we don't
// get wedged! (Issue #7476)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
b, err := wslCombinedOutput(exec.CommandContext(ctx, "wsl.exe", "-l"))
if err != nil {
return nil, fmt.Errorf("%v: %q", err, string(b))
}

View File

@@ -24,6 +24,7 @@ import (
"tailscale.com/types/logger"
"tailscale.com/util/cloudenv"
"tailscale.com/util/singleflight"
"tailscale.com/util/slicesx"
)
var zaddr netip.Addr
@@ -577,7 +578,7 @@ func (dc *dialCall) raceDial(ctx context.Context, ips []netip.Addr) (net.Conn, e
iv4 = append(iv4, ip)
}
}
ips = interleaveSlices(iv6, iv4)
ips = slicesx.Interleave(iv6, iv4)
go func() {
for i, ip := range ips {
@@ -636,21 +637,6 @@ func (dc *dialCall) raceDial(ctx context.Context, ips []netip.Addr) (net.Conn, e
}
}
// interleaveSlices combines two slices of the form [a, b, c] and [x, y, z]
// into a slice with elements interleaved; i.e. [a, x, b, y, c, z].
func interleaveSlices[T any](a, b []T) []T {
var (
i int
ret = make([]T, 0, len(a)+len(b))
)
for i = 0; i < len(a) && i < len(b); i++ {
ret = append(ret, a[i], b[i])
}
ret = append(ret, a[i:]...)
ret = append(ret, b[i:]...)
return ret
}
func v4addrs(aa []netip.Addr) (ret []netip.Addr) {
for _, a := range aa {
a = a.Unmap()

View File

@@ -13,6 +13,8 @@ import (
"reflect"
"testing"
"time"
"tailscale.com/tstest"
)
var dialTest = flag.String("dial-test", "", "if non-empty, addr:port to test dial")
@@ -141,34 +143,8 @@ func TestResolverAllHostStaticResult(t *testing.T) {
}
}
func TestInterleaveSlices(t *testing.T) {
testCases := []struct {
name string
a, b []int
want []int
}{
{name: "equal", a: []int{1, 3, 5}, b: []int{2, 4, 6}, want: []int{1, 2, 3, 4, 5, 6}},
{name: "short_b", a: []int{1, 3, 5}, b: []int{2, 4}, want: []int{1, 2, 3, 4, 5}},
{name: "short_a", a: []int{1, 3}, b: []int{2, 4, 6}, want: []int{1, 2, 3, 4, 6}},
{name: "len_1", a: []int{1}, b: []int{2, 4, 6}, want: []int{1, 2, 4, 6}},
{name: "nil_a", a: nil, b: []int{2, 4, 6}, want: []int{2, 4, 6}},
{name: "nil_all", a: nil, b: nil, want: []int{}},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
merged := interleaveSlices(tc.a, tc.b)
if !reflect.DeepEqual(merged, tc.want) {
t.Errorf("got %v; want %v", merged, tc.want)
}
})
}
}
func TestShouldTryBootstrap(t *testing.T) {
oldDebug := debug
t.Cleanup(func() { debug = oldDebug })
debug = func() bool { return true }
tstest.Replace(t, &debug, func() bool { return true })
type step struct {
ip netip.Addr // IP we pretended to dial

View File

@@ -14,7 +14,6 @@ import (
"errors"
"fmt"
"log"
"math/rand"
"net"
"net/http"
"net/netip"
@@ -31,6 +30,7 @@ import (
"tailscale.com/syncs"
"tailscale.com/tailcfg"
"tailscale.com/types/logger"
"tailscale.com/util/slicesx"
)
func Lookup(ctx context.Context, host string) ([]netip.Addr, error) {
@@ -56,8 +56,8 @@ func Lookup(ctx context.Context, host string) ([]netip.Addr, error) {
}
}
}
rand.Shuffle(len(cands4), func(i, j int) { cands4[i], cands4[j] = cands4[j], cands4[i] })
rand.Shuffle(len(cands6), func(i, j int) { cands6[i], cands6[j] = cands6[j], cands6[i] })
slicesx.Shuffle(cands4)
slicesx.Shuffle(cands6)
const maxCands = 6
var cands []nameIP // up to maxCands alternating v4/v6 as long as we have both
@@ -87,6 +87,7 @@ func Lookup(ctx context.Context, host string) ([]netip.Addr, error) {
continue
}
if ips := dm[host]; len(ips) > 0 {
slicesx.Shuffle(ips)
logf("bootstrapDNS(%q, %q) for %q = %v", cand.dnsName, cand.ip, host, ips)
return ips, nil
}
@@ -249,10 +250,13 @@ func SetCachePath(path string) {
// logfunc stores the logging function to use for this package.
var logfunc syncs.AtomicValue[logger.Logf]
// SetLogger sets the logging function that this package will use. The default
// logger if this function is not called is 'log.Printf'.
func SetLogger(log logger.Logf) {
logfunc.Store(log)
// SetLogger sets the logging function that this package will use, and returns
// the old value (which may be nil).
//
// If this function is never called, or if this function is called with a nil
// value, 'log.Printf' will be used to print logs.
func SetLogger(log logger.Logf) (old logger.Logf) {
return logfunc.Swap(log)
}
func logf(format string, args ...any) {

View File

@@ -353,6 +353,12 @@ func (s *State) String() string {
return sb.String()
}
// ChangeFunc is a callback function (usually registered with
// wgengine/monitor's Mon) that's called when the network
// changed. The changed parameter is whether the network changed
// enough for State to have changed since the last callback.
type ChangeFunc func(changed bool, state *State)
// An InterfaceFilter indicates whether EqualFiltered should use i when deciding whether two States are equal.
// ips are all the IPPrefixes associated with i.
type InterfaceFilter func(i Interface, ips []netip.Prefix) bool
@@ -607,8 +613,18 @@ func LikelyHomeRouterIP() (gateway, myIP netip.Addr, ok bool) {
return
}
ForeachInterfaceAddress(func(i Interface, pfx netip.Prefix) {
if !i.IsUp() {
// Skip interfaces that aren't up.
return
} else if myIP.IsValid() {
// We already have a valid self IP; skip this one.
return
}
ip := pfx.Addr()
if !i.IsUp() || !ip.IsValid() || myIP.IsValid() {
if !ip.IsValid() || !ip.Is4() {
// Skip IPs that aren't valid or aren't IPv4, since we
// always return an IPv4 address.
return
}
if gateway.IsPrivate() && ip.IsPrivate() {
@@ -756,3 +772,15 @@ func HasCGNATInterface() (bool, error) {
}
return hasCGNATInterface, nil
}
var interfaceDebugExtras func(ifIndex int) (string, error)
// InterfaceDebugExtras returns extra debugging information about an interface
// if any (an empty string will be returned if there are no additional details).
// Formatting is platform-dependent and should not be parsed.
func InterfaceDebugExtras(ifIndex int) (string, error) {
if interfaceDebugExtras != nil {
return interfaceDebugExtras(ifIndex)
}
return "", nil
}

View File

@@ -4,6 +4,7 @@
package interfaces
import (
"fmt"
"net"
"strings"
"sync"
@@ -29,6 +30,10 @@ var ifNames struct {
m map[int]string // ifindex => name
}
func init() {
interfaceDebugExtras = interfaceDebugExtrasDarwin
}
// getDelegatedInterface returns the interface index of the underlying interface
// for the given interface index. 0 is returned if the interface does not
// delegate.
@@ -93,3 +98,14 @@ func getDelegatedInterface(ifIndex int) (int, error) {
}
return int(ifr.ifr_delegated), nil
}
func interfaceDebugExtrasDarwin(ifIndex int) (string, error) {
delegated, err := getDelegatedInterface(ifIndex)
if err != nil {
return "", err
}
if delegated == 0 {
return "", nil
}
return fmt.Sprintf("delegated=%d", delegated), nil
}

View File

@@ -10,14 +10,14 @@ import (
"os"
"path/filepath"
"testing"
"tailscale.com/tstest"
)
// test the specific /proc/net/route path as found on Google Cloud Run instances
func TestGoogleCloudRunDefaultRouteInterface(t *testing.T) {
dir := t.TempDir()
savedProcNetRoutePath := procNetRoutePath
defer func() { procNetRoutePath = savedProcNetRoutePath }()
procNetRoutePath = filepath.Join(dir, "CloudRun")
tstest.Replace(t, &procNetRoutePath, filepath.Join(dir, "CloudRun"))
buf := []byte("Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\tMTU\tWindow\tIRTT\n" +
"eth0\t8008FEA9\t00000000\t0001\t0\t0\t0\t01FFFFFF\t0\t0\t0\n" +
"eth1\t00000000\t00000000\t0001\t0\t0\t0\t00000000\t0\t0\t0\n")
@@ -39,9 +39,7 @@ func TestGoogleCloudRunDefaultRouteInterface(t *testing.T) {
// size can be handled.
func TestExtremelyLongProcNetRoute(t *testing.T) {
dir := t.TempDir()
savedProcNetRoutePath := procNetRoutePath
defer func() { procNetRoutePath = savedProcNetRoutePath }()
procNetRoutePath = filepath.Join(dir, "VeryLong")
tstest.Replace(t, &procNetRoutePath, filepath.Join(dir, "VeryLong"))
f, err := os.Create(procNetRoutePath)
if err != nil {
t.Fatal(err)
@@ -76,9 +74,7 @@ func TestExtremelyLongProcNetRoute(t *testing.T) {
// test the specific /proc/net/route path as found on AWS App Runner instances
func TestAwsAppRunnerDefaultRouteInterface(t *testing.T) {
dir := t.TempDir()
savedProcNetRoutePath := procNetRoutePath
defer func() { procNetRoutePath = savedProcNetRoutePath }()
procNetRoutePath = filepath.Join(dir, "CloudRun")
tstest.Replace(t, &procNetRoutePath, filepath.Join(dir, "CloudRun"))
buf := []byte("Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\tMTU\tWindow\tIRTT\n" +
"eth0\t00000000\tF9AFFEA9\t0003\t0\t0\t0\t00000000\t0\t0\t0\n" +
"*\tFEA9FEA9\t00000000\t0005\t0\t0\t0\tFFFFFFFF\t0\t0\t0\n" +

View File

@@ -8,6 +8,8 @@ import (
"net"
"net/netip"
"testing"
"tailscale.com/tstest"
)
func TestGetState(t *testing.T) {
@@ -37,12 +39,110 @@ func TestGetState(t *testing.T) {
}
func TestLikelyHomeRouterIP(t *testing.T) {
ipnet := func(s string) net.Addr {
ip, ipnet, err := net.ParseCIDR(s)
ipnet.IP = ip
if err != nil {
t.Fatal(err)
}
return ipnet
}
mockInterfaces := []Interface{
// Interface that's not running
{
Interface: &net.Interface{
Index: 1,
MTU: 1500,
Name: "down0",
Flags: net.FlagBroadcast | net.FlagMulticast,
},
AltAddrs: []net.Addr{
ipnet("10.0.0.100/8"),
},
},
// Interface that's up, but only has an IPv6 address
{
Interface: &net.Interface{
Index: 2,
MTU: 1500,
Name: "ipsixonly0",
Flags: net.FlagUp | net.FlagBroadcast | net.FlagMulticast | net.FlagRunning,
},
AltAddrs: []net.Addr{
ipnet("76f9:2e7d:55dd:48e1:48d0:763a:b591:b1bc/64"),
},
},
// Fake interface with a gateway to the internet
{
Interface: &net.Interface{
Index: 3,
MTU: 1500,
Name: "fake0",
Flags: net.FlagUp | net.FlagBroadcast | net.FlagMulticast | net.FlagRunning,
},
AltAddrs: []net.Addr{
ipnet("23a1:99c9:3a88:1d29:74d4:957b:2133:3f4e/64"),
ipnet("192.168.7.100/24"),
},
},
}
// Mock out the responses from netInterfaces()
tstest.Replace(t, &altNetInterfaces, func() ([]Interface, error) {
return mockInterfaces, nil
})
// Mock out the likelyHomeRouterIP to return a known gateway.
tstest.Replace(t, &likelyHomeRouterIP, func() (netip.Addr, bool) {
return netip.MustParseAddr("192.168.7.1"), true
})
gw, my, ok := LikelyHomeRouterIP()
if !ok {
t.Logf("no result")
return
t.Fatal("expected success")
}
t.Logf("myIP = %v; gw = %v", my, gw)
if want := netip.MustParseAddr("192.168.7.1"); gw != want {
t.Errorf("got gateway %v; want %v", gw, want)
}
if want := netip.MustParseAddr("192.168.7.100"); my != want {
t.Errorf("got self IP %v; want %v", my, want)
}
// Verify that no IP is returned if there are no IPv4 addresses on
// local interfaces.
t.Run("NoIPv4Addrs", func(t *testing.T) {
tstest.Replace(t, &mockInterfaces, []Interface{
// Interface that's up, but only has an IPv6 address
{
Interface: &net.Interface{
Index: 2,
MTU: 1500,
Name: "en0",
Flags: net.FlagUp | net.FlagBroadcast | net.FlagMulticast | net.FlagRunning,
},
AltAddrs: []net.Addr{
ipnet("76f9:2e7d:55dd:48e1:48d0:763a:b591:b1bc/64"),
},
},
})
_, _, ok := LikelyHomeRouterIP()
if ok {
t.Fatal("expected no success")
}
})
}
func TestLikelyHomeRouterIP_NoMocks(t *testing.T) {
// Verify that this works properly when called on a real live system,
// without any mocks.
gw, my, ok := LikelyHomeRouterIP()
t.Logf("LikelyHomeRouterIP: gw=%v my=%v ok=%v", gw, my, ok)
}
func TestIsUsableV6(t *testing.T) {

View File

@@ -31,6 +31,7 @@ import (
"tailscale.com/net/netns"
"tailscale.com/net/ping"
"tailscale.com/net/portmapper"
"tailscale.com/net/sockstats"
"tailscale.com/net/stun"
"tailscale.com/syncs"
"tailscale.com/tailcfg"
@@ -783,6 +784,8 @@ func (c *Client) GetReport(ctx context.Context, dm *tailcfg.DERPMap) (_ *Report,
ctx, cancel := context.WithTimeout(ctx, overallProbeTimeout)
defer cancel()
ctx = sockstats.WithSockStats(ctx, sockstats.LabelNetcheckClient)
if dm == nil {
return nil, errors.New("netcheck: GetReport: DERP map is nil")
}

View File

@@ -22,6 +22,7 @@ import (
"tailscale.com/net/stun"
"tailscale.com/net/stun/stuntest"
"tailscale.com/tailcfg"
"tailscale.com/tstest"
)
func TestHairpinSTUN(t *testing.T) {
@@ -679,9 +680,7 @@ func TestNoCaptivePortalWhenUDP(t *testing.T) {
}
})
oldTransport := noRedirectClient.Transport
t.Cleanup(func() { noRedirectClient.Transport = oldTransport })
noRedirectClient.Transport = tr
tstest.Replace(t, &noRedirectClient.Transport, http.RoundTripper(tr))
stunAddr, cleanup := stuntest.Serve(t)
defer cleanup()

Some files were not shown because too many files have changed in this diff Show More