unbraid

Articles · Published

Inbound tailnet connections in unbraid's Android split tunnel

Work in progress. This article is about an experimental feature in the unbraid 3.1.2 test build (build 61). It isn’t in a regular release. It is off by default, Android only, and still being tested, so what you read here may change, and parts of it may be redesigned or dropped. It is careful work by a small team, not enterprise grade security. Please read the limits near the end before you rely on it.

This is a long article. Some parts explain the ideas in everyday words, and some go deep into packets, sequence numbers and code. Skip whatever you don’t need.

How this started

It started with an issue on our GitHub. Someone wanted KDE Connect to work between their phone and their computer over Tailscale while unbraid was running, and it didn’t: the two would not link up at all. The request was about a specific build of KDE Connect, a community fork that runs with Shizuku, based on KDE Connect 1.35.9. It came with a careful analysis of what was going wrong and a short wish list: optional, through Tailscale only, to the phone itself only, and ideally only for apps the user picks.

We found it intriguing. It sounds like a small ask: let my own devices reach my own phone. But it touches almost everything that makes unbraid careful. How Android hands out its one VPN slot. How unbraid spreads apps over several tunnels at the same time. How the built-in Tailscale works. And a rule we added on purpose so that nothing comes in through a tunnel. Saying yes meant finding a way through all of that without opening the door to everything.

KDE Connect is the example all the way through this article, because that’s where it started. The feature itself isn’t tied to KDE Connect. It’s meant for any app that waits for incoming connections over IPv4 on a port from 1024 up. Besides KDE Connect we tested an SSH server and Syncthing over TCP, and a small echo service over UDP. More lab testing with other apps is planned.

Some background

Tailscale links your own devices into one private network, which it calls a tailnet. Your phone, laptop and home server can then reach each other from anywhere, as if they sat on the same home network. Each device gets a tailnet address, usually starting with 100.

KDE Connect links a phone and a computer: shared clipboard, files, notifications, media controls. Both sides have to be able to open connections to the other.

unbraid is a split tunneling VPN client. Different apps can use different exits at the same time: one app through one VPN provider, another through a second provider, another through your home WireGuard, another straight out. Android allows one active VPN app at a time (per user or work profile), so unbraid has Tailscale built in rather than running next to the Tailscale app. That lets the phone reach your tailnet while other apps use a VPN.

Until now that only worked in one direction: from the phone out to the tailnet (the Tailscale guide covers that part, and the Headscale guide covers a self-hosted control server). The request was about the other direction, the tailnet reaching in to the phone.

Why unbraid kept the door shut

unbraid refuses every new connection that a VPN server or a tailnet device starts toward the phone. Without that rule, whoever sits at the far end of a tunnel could use your phone as a way into your home network, your local network or one of your other tunnels. The rule is the first one unbraid writes into the engine’s routing:

// The tunnels carry the phone's own connections and their replies, never new ones a server or peer
// opens: those would reach the phone, its network and the home network through another route.
// ...
if (tunnels.isNotEmpty()) add(obj("inbound" to JsonArray(tunnels.map(::JsonPrimitive)), "action" to "reject"))

This explains what the issue described: the phone looked reachable for a moment, then the connection was cut with nothing sent. That was the rule doing its job. The built-in Tailscale answers the first step of a connection itself, and the engine closes it once the rule refuses it.

The rule stays. The new feature is a narrow way past it, for Tailscale only. New connections that a VPN provider’s server or your home WireGuard opens are still refused.

What makes this hard

A routing exception could allow a port. It couldn’t tell us which app would receive the connection, and it would have kept a second problem too. Here is what stood in the way.

Tailscale inside unbraid works differently

The official Tailscale app is part of Android’s networking: it owns the VPN interface. When a tailnet device connects to the phone, Android receives the connection and hands it to the app that is listening, with the sender’s real address. In Tailscale’s Android code that is one line:

ns.ProcessLocalIPs = false // let Android kernel handle it; VpnBuilder sets this up

unbraid’s Tailscale is a program running inside unbraid’s engine (sing-box), next to the other tunnels. Tailscale calls this userspace mode: it brings its own small network stack and has no interface of its own, so Android never sees its visitors. In this mode a connection to the phone’s tailnet address gets its destination changed to loopback (127.0.0.1, the phone talking to itself) and goes through the engine’s routing rules, where unbraid refuses it.

Simply letting those through would be wrong twice. Any app listening on that port on loopback would receive the connection, chosen or not. And the app would see the phone itself as the sender, not your laptop. That second part matters for KDE Connect: when it fetches a file, it connects back to the address the other side came from. If that address is the phone, the file never arrives.

Android doesn’t simply tell you who is listening

“Only the apps I choose” means unbraid has to know which app a connection is going to. A port number doesn’t say: almost any app can listen on almost any port from 1024 up. Android lets the active VPN app ask “which app owns this connection?” (ConnectivityManager.getConnectionOwnerUid), and in our tests it only names apps whose traffic goes through the VPN. The documentation is about connections, not about apps waiting for one. Reading the system’s connection tables directly isn’t an option either: Android 10 closed that to apps.

unbraid’s other promises have to hold

The feature had to fit into what unbraid already does without bending it:

  • Several providers at once. Apps are spread over different exits. A reply to a connection that came in from the tailnet has to go back through Tailscale, not out through the VPN that app normally uses.
  • Tailscale has to keep working. The built-in Tailscale has its own outgoing connections, its own services on the phone, exit nodes, and the phone’s normal traffic to the tailnet. Taking the wrong packets would break it quietly.
  • Block means Block. An app set to Block gets nothing on any route, and that had to include the tailnet too.
  • Apps outside the VPN can’t be named by unbraid, and their replies never pass through it, so they can’t be offered.
  • Settings changes. A settings change that affects routing restarts the engine. The old engine can still be closing down when the new one starts, and nothing about a connection may cross from one to the other.

Not opening the door to everything

This was the hardest part, and it still is. Every shortcut we looked at let in more than it should. TCP below means connections with a handshake (files, logins, sync). UDP means single messages with no handshake (calls, games, discovery).

Shortcut What it would have let in
Pass tailnet connections to loopback Any app listening on those ports, and the sender shows up as the phone
Allow a list of ports Any app that happens to listen on one of them
Allow every port from 1024 up Tailscale’s own replies as well, since they use high ports too: Tailscale breaks
Trust Tailscale’s access rules alone Every device on a tailnet that still has the default allow-all policy
Check the app once, then let data flow Data reaching the wrong app if the answer comes late or the port changes hands
Treat UDP like TCP Data that arrives with the very first packet, before any check could run

So we set ourselves these goals. For TCP, no data reaches an app before Android has named it and it’s an app you chose, and an app on Block gets no TCP data. With UDP, a change of app can go unnoticed for up to about five seconds after the last good check. You can narrow the devices further than Tailscale’s rules do. Anything the feature doesn’t positively claim stays with Tailscale, as before. And nothing changes for people who leave it off.

Research first

The first evening was reading, no code.

  • Tailscale’s own Android app lets Android deliver incoming traffic (the line quoted above). A public Tailscale issue explains that userspace mode forwards incoming connections to localhost.
  • TailSocks, an unofficial Tailscale client for Android, also had to deal with its local proxies reaching the phone’s own localhost.
  • In KDE Connect’s Android code we looked at which addresses it accepts connections from (private ranges, which include Tailscale’s 100.x range and loopback), which ports it uses (the announcement goes to UDP 1716, and TCP starts at 1716; KDE’s published firewall range is 1714 to 1764), and the detail that decided a lot: it fetches files by connecting back to the address the other side came from.
  • On Android we looked at what a VPN app may ask the system, what Android 17’s new local network permission covers, and what Android 10 closed off.
  • In sing-box we looked at how the Tailscale endpoint, the VPN interface and the routing rules fit together, and at known issues about incoming traffic from Tailscale.
  • We also asked AI tools from several companies for independent opinions, and asked one to attack the plan on purpose. One research report got a key fact about Tailscale’s app wrong. The source code settled it, and from then on every claim was checked against code.

That left two options. The loopback way was simple but gave only part of KDE Connect. The full way would keep the real sender and check the app. The decision was the full way: chosen apps only, data held until checked, Android only.

A first try with loopback

To learn quickly we built a throwaway version that let tailnet connections on KDE Connect’s ports through to loopback.

We tested in a small lab with no real accounts:

  • a private Tailscale control server (Headscale) in Docker;
  • two exit nodes, a router, and a web server standing in for the internet;
  • a Debian “PC” running KDE Connect and Tailscale;
  • an Android emulator running unbraid, with KDE Connect from F-Droid (its checksum checked against F-Droid’s index).

Pairing worked once the phone had the PC’s tailnet address added by hand, and files from the phone to the PC worked. Files the other way should fail according to KDE Connect’s code, because the phone would try to fetch the file from itself. (Our test of that direction looked for the file in the wrong place, so it didn’t prove it either way.) An app set to Block still received connections, and a port list let any app on those ports receive them.

That was part of KDE Connect, and two holes in the safety story. We dropped it.

Letting Android receive the connection

The full version in one sentence: make Android receive the connection itself, as if the phone sat directly on the tailnet, and put a gatekeeper in front of it.

Two small patches let unbraid look at each packet at the right moment: once right after Tailscale has checked it, and once on its way back from the app. A third change, in the engine, holds it together.

The phone’s tailnet address on the VPN interface

When the feature is active, unbraid adds the phone’s own tailnet address to its VPN interface. Android then treats packets for that address as its own and delivers them to the listening app, with the sender’s real address. This is what the app writes into the engine’s configuration:

// With inbound on, the tailnet address too: Android then hands its connections to the listening app.
put("address", JsonArray((listOf("172.19.0.1/30") + listOfNotNull(inbound?.let { "${it.address4}/32" })).map(::JsonPrimitive)))
// With inbound on, Tailscale's 1280: Android then splits big datagrams itself (a sender that closes its
// socket at once never learns a smaller size), and its replies to handed-off connections need no clamping.
put("mtu", if (inbound != null) 1280 else 9000)

“Active” means more than the switch. Reach your tailnet has to be on, the phone’s tailnet address has to be known, at least one app has to be chosen with TCP or UDP turned on, and if you picked Only devices you choose, at least one device has to be chosen. Otherwise none of this is installed. The packet size line has its own story further down.

A patch to Tailscale

Inside the engine, Tailscale decrypts a packet from a tailnet device, checks it against your Tailscale access rules, and then gives it to its own network stack. We needed to step in between those last two: after Tailscale’s rules said yes, before its stack answers.

Tailscale has a hook there, but it is wired up when the stack is created, and wrapping it later would race with live traffic. So a small patch to Tailscale adds a slot that holds an optional function, read atomically for every packet:

// InboundHandoff, when set, sees every packet that passed the inbound filter before netstack does; returning true
// means it took the packet (unbraid patch: hands connections to the system's own stack).
InboundHandoff atomic.Pointer[func(*packet.Parsed) bool]
	ns.tundev.PostFilterPacketInboundFromWireGuard = ns.injectInboundOrHandoff
	// ...

// injectInboundOrHandoff offers the packet to InboundHandoff first (unbraid patch).
func (ns *Impl) injectInboundOrHandoff(p *packet.Parsed, t *tstun.Wrapper, gro *gro.GRO) (filter.Response, *gro.GRO) {
	if h := ns.InboundHandoff.Load(); h != nil && (*h)(p) {
		return filter.DropSilently, gro
	}
	return ns.injectInbound(p, t, gro)
}

With the feature off the slot is empty, and packets go where they went before.

A patch to the tunnel library

When the app answers, Android writes the reply into the VPN interface. Normally the engine’s own network stack (gVisor, inside the sing-tun library) picks it up, sees a reply to a connection it never opened, and answers with a reset, which closes the connection. So sing-tun got a small patch too: an interceptor that sees packets from Android before the stack does.

// PacketInterceptor takes packets the system writes into the TUN before they reach the stack.
type PacketInterceptor interface {
	// InterceptPacket is called once per packet with its source address; packet(n) returns the packet's first n bytes
	// (all of it for n <= 0 or more than its size), to be called only for packets that may be taken. True means the
	// packet was taken and must not reach the stack.
	InterceptPacket(source netip.Addr, packet func(n int) ([]byte, bool)) bool
}

Most packets have nothing to do with this feature. The tunnel library already reads each packet’s addresses, and if the source isn’t the phone’s tailnet address, the hand-off asks for nothing more and the packet goes on untouched. Otherwise it asks for up to 136 bytes, enough for the headers, to look for a matching connection. Only a packet that belongs to a handed-off connection is read in full and passed on to Tailscale.

func (h *handoff) Intercept(source netip.Addr, packet func(n int) ([]byte, bool)) bool {
	local := h.local.Load()
	if local == nil || *local != source {
		return false
	}
	head, ok := packet(handoffPeek)
	// ...

A small shared package in the engine (tunhandoff) links the Tailscale side and the interface side. There is one link per engine instance, so an engine that is closing down can’t write into the interface of the engine that replaced it.

Checking who is listening

The promise for TCP: no data reaches an app until Android has said which app it is, and it is one you chose. Two checks make that work. The first happens before Android sees the connection at all. The second happens after the handshake, while the data waits.

For a while we believed Android could only name the app of a connection that already exists. That would have meant setting up a connection before checking anything, so an app you didn’t choose would at least see the attempt.

Then we tried something. We asked Android the same “who owns this connection?” question for a connection that doesn’t exist yet, giving it the phone’s address and port as the local end and the tailnet device’s address and port as the remote end. Android answered with the app that is listening on that port. On the emulator it named KDE Connect as the TCP listener, and nobody for an unused port. Later we checked UDP too, with sockets that take IPv4 only and sockets that take both IPv4 and IPv6.

That answer became the first check. A TCP connection starts with a packet called SYN, the opening “hello”. Before Android sees it, unbraid asks who is listening:

// open vets a peer's SYN by the app listening on its port, then delivers it to the system under a new flow.
func (h *handoff) open(tab *handoffTable, key flowKey, node string, p tcp4, b []byte) bool {
	packages, found := h.lookup(false, p.dst, p.src, handoffVetWait)
	if !found {
		return false // no app of the VPN listens there: the stack's
	}
	reason := ""
	if len(h.allowNodes) > 0 && !h.allowNodes[node] {
		reason = "device"
	} else if !h.allowed(packages) {
		reason = h.refusal(packages)
	}
	if reason != "" {
		h.write(nil, false, rst4(p.dst, p.src, 0, p.seq+1, true))
		// ...
		return true
	}
	// ...
}

What can happen:

  • Android names nobody, or no answer comes within 300 ms: the packet isn’t taken. It goes to Tailscale’s own stack, as before. Tailscale’s own services on the phone keep working this way.
  • It names an app you didn’t choose, an app on Block, or the device isn’t one you allowed: unbraid takes the SYN and answers with an immediate “connection refused”. The app never sees the attempt.
  • It names an app you chose: the SYN goes to Android, and the second check follows.

This also avoided a nasty bug. The app tells the engine “ports 1024 to 65535”, because the check is about the app, not the port. A plain hand-off of all those ports would have swallowed the replies to Tailscale’s own outgoing connections, which use high ports too. The hand-off only ever claims a brand new connection, from a known tailnet device, that an app is listening for. Everything else stays with Tailscale:

// Anything else is the stack's, as without the hand-off: its own connections, and SYNs this can't take.
if !opening || p.payload != 0 || !isPeer || !room || !h.portAllowed(p.dst.Port()) {
	return false
}
return h.open(tab, key, node, p, b)

Checking again after the handshake

A TCP connection opens with three short packets: SYN, SYN-ACK, ACK. Once unbraid has passed on the final ACK, it asks Android again who owns that connection. That names the app that took it, not just the one listening. The second check exists in case the first answer was wrong, for example because an app started listening a moment later.

The handshake packets themselves pass to Android. Data doesn’t. The other device may already put data on its last handshake packet, so unbraid keeps that data aside and gives Android a copy of the packet with the data cut off, so Android can complete its side of the handshake:

case p.flags&tcpACK != 0 && f.haveLocalISN && p.seq == f.peerISN+1 && p.ack == f.localISN+1:
	// The final ACK. Data on it is held; the system gets a bare ACK so its socket can be established.
	if time.Now().After(f.deadline) {
		h.denyLocked(f)
		return
	}
	if p.payload > 0 || p.flags&(tcpFIN|tcpURG) != 0 {
		if !checksumsValid(pkt) {
			return // damaged: the peer sends it again
		}
		if !h.deliverSystemLocked(f, bareACK(pkt)) || !h.holdLocked(f, &f.in, pkt) {
			h.denyLocked(f)
			return
		}
	} else if !h.deliverSystemLocked(f, pkt) {
		h.denyLocked(f)
		return
	}
	f.state = flowChecking
	f.deadline = time.Now().Add(handoffCheckWait)
	go h.check(f)

The final ACK only counts if its sequence numbers match both sides’ starting numbers exactly. Something that merely looks like an ACK doesn’t move the connection forward.

unbraid then asks Android who owns the connection, retrying until a 3 second deadline. Some Android apps share one identity (a user ID). A connection only gets through if every app with that identity is chosen and none is on Block:

// allowedIn: every package of the user id is in allow and none is blocked.
func (h *handoff) allowedIn(allow map[string]bool, packages []string) bool {
	if len(packages) == 0 {
		return false
	}
	for _, name := range packages {
		if h.block[name] || !allow[name] {
			return false
		}
	}
	return true
}

If the answer is yes, the data that was kept aside is released in order, in both directions. If it’s no, or no answer came in time, both ends get a reset and unbraid remembers that connection for 30 seconds, dropping its packets. A new connection from the same device and port, with a fresh starting number, gets checked again.

Making resets count

A reset is a message that says “close this connection now”. The receiver only accepts it if it carries the right place-in-line number (the sequence number it expects next). Get it slightly wrong and the reset is ignored, leaving the connection half open. So for each direction unbraid tracks what was delivered and what the receiver acknowledged, and aims the reset at exactly that position:

// resetAt: the sequence numbers a reset must carry for this stream's receiver to take it. Its next expected byte is
// the last it acknowledged, or the end of what was delivered when it hasn't acknowledged that yet.
func (s *stream) resetAt() []uint32 {
	switch {
	case !s.started:
		return nil
	case s.acked && s.ack != s.next:
		return []uint32{s.ack, s.next}
	default:
		return []uint32{s.next}
	}
}

The same tracking handles polite endings. When both sides have said goodbye (a FIN) and both goodbyes were acknowledged, the connection is still forwarded for 30 seconds, so a goodbye that has to be sent again still arrives.

Choosing which devices can connect

Tailscale’s access rules decide first which devices may reach the phone at all. A new tailnet starts with a policy that lets every device reach every other. If yours still uses it, unbraid lets you narrow it: every device the rules allow, or only devices you pick.

Devices are identified by Tailscale’s stable node ID, taken from the live network map whenever it changes:

for _, node := range nm.Peers {
	addresses := node.Addresses()
	for i := 0; i < addresses.Len(); i++ {
		if prefix := addresses.At(i); prefix.IsSingleIP() && prefix.Addr().Is4() {
			peers[prefix.Addr()] = string(node.StableID())
		}
	}
}

Those IDs are only unique inside one tailnet, and a self-hosted control server may number its devices 1, 2, 3. So when you sign out or switch to another server, unbraid forgets the devices you picked. Only devices you choose stays selected, so nobody gets in until you choose again.

The choice also fails closed. Remove the last chosen device and the app doesn’t send an empty list, which the engine would read as “every device”. It switches the hand-off off instead:

val nodes = if (home.reachableOnly) home.reachableDevices.map { it.id }.ifEmpty { return null } else emptyList()

When a device leaves the tailnet, or its address now belongs to another device, its connections are dropped. When the phone’s own tailnet address changes, all handed-off connections are dropped. An idle TCP connection is closed after two hours.

Limits

A device you let onto your tailnet can still misbehave. Data kept aside lives in memory, and every check asks Android a question. So everything has a limit:

const (
	handoffMaxFlows     = 512
	handoffMaxPerPeer   = 64
	handoffMaxHeldFlow  = 64 << 10
	handoffMaxHeldTotal = 4 << 20
	handoffHeldCost     = 64                     // charged per held packet besides its bytes
	handoffVetWait      = 300 * time.Millisecond // the listener lookup, made before the system sees the SYN
	handoffOpenWait     = 10 * time.Second       // SYN to the final ACK
	handoffCheckWait    = 3 * time.Second        // final ACK to the decision
	handoffIdle         = 2 * time.Hour          // an allowed connection silent this long is closed
	handoffTombstone    = 30 * time.Second       // a refused or closed tuple stays dead this long
	handoffPeek         = 136                    // enough for any IPv4 header, TCP flags, or an ICMP error's quote
	handoffUDPIdle      = 2 * time.Minute        // a UDP exchange silent this long ends
	handoffUDPRecheck   = 3 * time.Second        // how often the app holding a UDP exchange's port is named again
	handoffUDPGrace     = 2 * time.Second        // past its check this long without a new answer, an exchange is held
	handoffMaxUDP       = 256                    // UDP exchanges at once, apart from the TCP flows
	handoffUDPTombstone = 10 * time.Second       // a refused UDP exchange stays dropped this long, without new lookups
	// ...
)

In plain numbers: up to 512 TCP connections and 256 UDP exchanges at a time. Each device address gets at most 64 TCP entries and 64 UDP entries. Entries that were refused or closed recently still count while unbraid remembers them, but a TCP connection refused at the first check never takes a slot. Up to 64 KB of data is kept aside per connection and 4 MB in total, and each packet counts for its size plus 64 bytes.

Questions to Android are limited too: at most eight at once in the whole app, counting ones that got stuck, because Android’s call can’t be cancelled. If every slot is busy the answer is “don’t know”, and “don’t know” is never a yes.

// handoffCalls bounds the owner lookups in flight in the whole process, stuck ones included: the platform call can't
// be cancelled, so a reload must not bring fresh slots.
var handoffCalls = make(chan struct{}, 8)

Things that surprised us

Packets that were too big. KDE Connect announces itself with a message larger than the packets Tailscale carries (1,280 bytes), and sends it marked “don’t split”. unbraid’s VPN interface normally uses large packets of 9,000 bytes. The engine told Android “too big”, but KDE Connect closes its socket right after sending, so Android never learned the smaller size, and every announcement disappeared. The fix: while the feature is active, the VPN interface uses 1,280 bytes too, and Android splits big packets itself. We also found that a big first UDP packet to a tailnet device can get lost the same way with the feature off. That needs its own fix, for everyone, and isn’t part of this work.

A hook set too late. Tailscale wires its stack to the inbound hook when it starts. Our first version wrapped the hook afterwards, which raced with live traffic. That’s why the Tailscale patch adds a slot of its own.

Two engines, one interface. When a settings change restarts the engine, the old engine may still be closing down while the new one starts. A single global link between Tailscale and the interface could have connected the old engine’s Tailscale to the new engine’s interface. Each engine instance now has its own link.

A build that depended on its folder. To patch Tailscale and sing-tun, the build copies them out of Go’s module cache and patches the copies. Go records where such a replaced module lives, so the engine library came out different depending on the folder it was built in. We want two builds of the same code to be identical, so that anyone can check a published app against its source. The build now uses one fixed folder, checked to belong to the user who builds and locked while a build runs. Built in two different folders, the engine library now comes out byte for byte the same.

UDP

TCP’s handshake gives a natural moment to check before data flows. UDP has no handshake: the data comes with the very first packet. That’s why the first version kept UDP closed.

Asking Android about listeners changed that. If Android can name the app holding a UDP port before any exchange exists, the first message can wait a moment for the answer. On the emulator Syncthing’s UDP ports were named Syncthing, and an unused port was named nobody. So UDP became an option per app, off by default.

How it works:

  • The first message of an exchange (the device’s address and port, and the phone’s port) waits up to 300 ms for Android’s answer. If Android names nobody, the message goes to Tailscale as before.
  • If the app or the device is refused, the exchange is dropped for 10 seconds without asking Android again.
  • While an exchange lasts, the app holding the port is named again every 3 seconds, because another app could take the port over. Five seconds after the last good answer, messages in both directions are dropped until a new check says yes.
  • When Android answers a message with “port unreachable” (the app’s socket is gone), the exchange ends at once, and the next message gets a fresh check.
  • After 2 minutes of silence an exchange ends.
  • Pieces of a split UDP message are never passed on.
if now := time.Now(); f.state == flowAllowed && !f.retired.Load() && now.Before(f.validUntil) {
	f.lastActive = now
	h.write(f, true, pkt)
}
return true // a refused exchange's datagrams, or one whose check is overdue, are dropped

UDP is weaker than TCP, and we’d rather say so plainly. There’s no handshake, so there’s no second check. If another app takes over the port, it can receive messages for up to about five seconds after the last good check. The app says UDP is weaker in a sentence right where you turn it on.

KDE Connect doesn’t need UDP turned on for the setup described below. Its announcement is larger than 1,280 bytes, so over Tailscale it arrives in pieces, which the UDP hand-off refuses on purpose. With the computer’s address added by hand, the phone announces itself to the computer, the computer connects back over TCP, and files go over TCP too.

The settings page

The settings page went through several design rounds, each with three drawn options and one picked.

It lives in Settings › Tailscale › Reachable on your tailnet, next to Reach your tailnet, so both directions sit together:

  • Allow incoming tailnet connections: one switch for everything. Off by default.
  • Reachable apps: the apps you add. Apps outside the VPN or on Block are listed but can’t be picked, and the reason is shown. Tap a chosen app to set TCP connections (on for new apps) and UDP messages (off for new apps), or to remove it.
  • Who can connect: every device your Tailscale access rules allow, or only devices you choose. Tailscale has to be connected for unbraid to list your devices.
  • Recent connections: the last 50 decisions unbraid recorded. Which device tried to reach which app, over TCP or UDP, allowed or refused and why. They’re kept in memory until the VPN stops and aren’t saved or included in reports. Attempts that Tailscale’s own rules stopped, or that never got as far as an app check, don’t show up here. For an app refusal, the explanation shown can change if you later edit your list of apps.
  • A short how-to while KDE Connect, or a fork of it with a package name starting the same way, is chosen.

Switching the feature off ends handed-off connections once the change takes effect. Your chosen apps, devices and protocols stay listed for next time. These settings stay on the phone and aren’t part of unbraid’s backups, like the other Tailscale settings.

Reviews

We used AI tools for four rounds of review, each asked to attack the design and find ways around the checks, and we read the code ourselves between rounds. Every reported problem was checked against the source before anything changed.

  • First round, on the prototype. 17 findings, five of them serious. Among them: an approval that could carry over to a later connection on the same addresses and ports, a slow check that could approve the wrong connection, an address change or shutdown that didn’t cancel pending deliveries, two engines cross-wired during a settings change, and one device able to fill memory. We worked on all 17: approvals tied to each connection, handshakes checked by sequence numbers, a lock per connection, limits per device and in total, deadlines that refuse when they run out, resets at the exact position each side expects, and one link per engine.
  • Second round. It confirmed six of those fixes as complete and found that the other 11 needed more work. It also raised ten new issues, among them a reset that a timeout could write onto a newer connection, and clean closes that weren’t tracked. Almost all of it was fixed. One point stays partly open: the limit of eight questions to Android now survives reloads, but one device can still take all eight slots. This is where “retired” connections and a write gate came from: every write checks that its connection is still the live one.
  • Third round, big problems only, after the settings page. Seven points, three fixed. Removing your last chosen device at the same moment as a settings reload could briefly mean “every device” (the setting was read twice; now it’s read once and fails closed). Chosen devices could carry over to another tailnet (now forgotten). And the recent connections list could show one late entry from the previous session (now cleared after the engine stops).
  • Fourth round, the UDP code. Three points, two fixed. An exchange could outlive the app’s socket if another app took the port (now checked every 3 seconds, stopped when a check is late, ended on “port unreachable”). And UDP could use up room meant for TCP (now separate limits).

What we wrote down instead of fixing, because we judged it small or older than this feature:

  • An exit node you use could send packets that carry another device’s address. For TCP the phone answers the real device, so the impostor can’t complete the handshake and gets no data. For UDP there’s no handshake, so that argument doesn’t hold: such packets could reach an app you turned UDP on for.
  • A device that guesses the port an allowed app uses for its own outgoing UDP could turn that conversation into a handed-off one. The messages still go between the same device and the same app.
  • The “who’s listening” question has no limit per device. The limit of eight at once protects the phone, but a misbehaving device on your own tailnet could slow down new connections from other devices while it floods.
  • Two things come from code that was there before. Turning the feature off may wait for a VPN provider lookup during the reload. Separately, an old outgoing connection’s return path in the engine could catch a new incoming connection on exactly the same addresses and ports.

Tests

The hand-off has 26 groups of engine tests with 39 cases. They cover allowed apps, apps not chosen, shared app identities, Block, unknown owners, reused addresses and ports, late checks, traffic that doesn’t belong to the feature, the hold limits, address changes, and for UDP: both directions, refusal for a TCP-only app, a port changing hands, idle exchanges, and damaged or split packets. They run repeatedly with Go’s race detector, a tool that hunts for timing bugs between threads. The app’s own test suite, 695 tests, passes, including new tests for what the settings send to the engine.

Then real apps, in the lab described earlier, with KDE Connect first:

Test Result
KDE Connect pairing Works
Files from PC to phone (impossible with loopback) Works, checksums match
Files from phone to PC Works, checksums match
KDE Connect not chosen Refused at once, the app never sees it
KDE Connect on Block Refused at once
Only other devices allowed Refused at once
Ports nobody listens on Closed, as before
Feature switched off Back to normal, including the usual packet size

A checksum is a short fingerprint of a file. If the copy’s fingerprint matches the original’s, the file arrived unchanged. In the first KDE Connect test series, 16 transfers of 1 to 5 MB went both ways, and all 16 received files had the same checksum as their originals.

The build of KDE Connect from the original request, the fork based on 1.35.9, behaved the same: it could be chosen like any app, it paired, and a 3 MB file went each way with matching checksums. That also showed our first how-to was wrong to name a minimum KDE Connect version. That advice came from the loopback design, and the full design doesn’t need it.

To make sure the feature isn’t tied to KDE Connect, we tried other apps:

  • An SSH server in Termux. Not chosen: “connection refused” at once. Chosen: the PC logged in over SSH, and files of 2 MB and 10 MB went both ways with matching checksums.
  • Syncthing. Relays and discovery were switched off on the PC, so the only way in was the phone’s tailnet address. Not chosen: refused. Chosen: the phone’s Syncthing showed the PC asking to connect from its real tailnet address, which is what the whole design is for. A shared folder then synced both ways with matching checksums.
  • A UDP echo service in Termux. With UDP off for the app, none of 15 test messages came back. With UDP on, all 15 came back intact, at 5, 500 and 1,200 bytes.

A Syncthing test over its UDP transport (QUIC) gave no result: the test PC’s Syncthing sent no QUIC packets at all, so there was nothing to measure. We’ll test more apps in the lab, UDP ones in particular.

On a real phone with a real tailnet, with a home server in the computer’s place, we checked TCP on an earlier test build: KDE Connect was reached when chosen, and refused at once when only another device or only another app was chosen. Recent connections showed all three with the right reason. UDP was tested on the emulator only.

Limitations

  • Experimental, off by default, test build only. It isn’t in a regular release, and there’s no date for one.
  • Android only. unbraid for Mac refuses connections that arrive through its tunnels in the same way, Tailscale included, so tailnet devices can’t reach apps on the Mac while it runs. This feature isn’t built for the Mac yet.
  • Phones with Android 13 or newer and a 64-bit ARM processor, like the rest of unbraid.
  • IPv4 only. Connections to the phone’s tailnet IPv6 address aren’t handed off, and the connecting device needs a tailnet IPv4 address too.
  • Ports from 1024 up. There’s no list of ports to pick: a chosen app can be reached on any port from 1024 up that it listens on, for the protocols you turned on.
  • The app has to listen on the phone’s tailnet address. An app that listens only on loopback won’t receive these connections. Many apps that wait for connections listen on every address, but not all.
  • Only apps that go through unbraid. An app set to bypass the VPN can’t be chosen.
  • Only Tailscale. VPN provider tunnels and your home WireGuard still refuse new connections.
  • Your Tailscale access rules apply first. unbraid can narrow them, not widen them.
  • With the feature off, unbraid doesn’t hand incoming connections to apps. Tailscale still handles its own traffic, such as ping, and unbraid refuses the new connections that the tunnels pass on.
  • No automatic discovery. Local broadcasts don’t cross Tailscale, so you add devices by their tailnet address.
  • UDP is weaker than TCP, as described above, and split UDP messages are refused.
  • Smaller packets while it’s active. The VPN interface uses 1,280 bytes for every app while the feature is active. We haven’t measured whether that costs speed.
  • Not tested enough on real phones. A full KDE Connect pairing with files hasn’t been done on a real phone yet, and neither have long running connections, switching between Wi-Fi and mobile data, or a phone that sleeps for hours.
  • After the VPN restarts, KDE Connect may need Refresh in its menu before it reconnects.

About security

This isn’t enterprise grade security, and we don’t want anyone to read it that way. The feature was designed with care, reviewed four times with AI tools asked to break it, and tested in a lab and briefly on a real phone. There has been no independent security audit, no formal verification, and no long period of real use.

If you worry about a device on your own tailnet being hacked, a VPN exit you use being compromised, or someone with time and skill studying this code for a way in, don’t rely on this feature. Leave it off, or keep the lists of apps and devices short. Leaving it off is still the safest setting.

How AI was used

AI tools from more than one company did a lot of this work. They read source code and documentation, wrote much of the code and the tests, ran the emulator, and reviewed the changes, with one company’s model building and another’s reviewing so each could catch what the other missed. A person chose what to build, how much risk to accept, which findings to fix, and when to publish. When an AI tool was confidently wrong, which happened more than once, the source code and the tests decided.

Trying the test build

The test build is unbraid 3.1.2 (build 61), published on GitHub as a pre-release called experimental-tailnet-inbound-1 and marked “not for general use”. unbraid’s update check doesn’t offer it, and the normal download stays on the current release. Please only install it if you want to help test, and expect it to change.

Before you install: you can install it over the GitHub build of 3.1.1 and keep your settings, but back them up in unbraid first anyway. The next regular release will install over the test build. Going back to an older release means uninstalling unbraid first, which removes its settings; after that, restore your backup, sign in again and set up Tailscale again.

With KDE Connect:

  1. In unbraid, open Settings › Tailscale, keep Reach your tailnet on, and open Reachable on your tailnet.
  2. Turn on Allow incoming tailnet connections. Tap Add apps, select KDE Connect, then tap Add. You may need Show my apps first. TCP is on for it, and UDP can stay off.
  3. On Android 17, give KDE Connect the Nearby devices permission if it asks for it. Without it, it won’t announce itself.
  4. Check that your Tailscale access rules let the computer and the phone reach each other on KDE Connect’s ports, 1714 to 1764 (the default allow-all policy does).
  5. If you have both the official KDE Connect and a fork installed, use just one of them: they want the same ports. (We tested the fork with the official app removed.)
  6. In KDE Connect on the phone, use Add devices by IP and enter the computer’s tailnet address.
  7. Pair from either side, and accept the request quickly: it expires after about 30 seconds.

Other apps are set up the same way: add the app, turn on the protocol it listens on, and point the other device at the phone’s tailnet address.

If something doesn’t work, look at Recent connections first. Then tell us on GitHub which app and protocol you tried and what happened, leaving out device names and addresses.

What comes next

This is still being tested, and the design may change with what we and the testers find. Next on the list:

  • more lab tests with other apps, UDP ones in particular;
  • real-phone testing: full pairings, long connections, network changes, sleep;
  • whether to keep UDP as it is, or how to make it stronger;
  • IPv6;
  • a limit per device on how often Android is asked;
  • the separate packet size fix for everyone.

The code

The app code, engine patches and engine tests for this build are public in the unbraid repository on GitHub: github.com/Quiet-Crafts/unbraid. The test build’s code is at the tag experimental-tailnet-inbound-1, and the work continues on the branch feat/tailnet-inbound. The engine changes are three patch files in tools/:

  • tailscale-handoff.patch: the slot in Tailscale’s stack;
  • sing-tun-handoff.patch: the interceptor in the tunnel library;
  • sing-box-tailscale-tun-handoff.patch: the hand-off itself, its options, the link between engine parts, the list of recent decisions, and the engine tests.

The app side is mostly in vpn/Compiler.kt, vpn/UnbraidVpn.kt and ui/Reachable.kt.

Sources