// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Signing over the tailnet: the route, beside the forward, by which a remote //! machine B signs with the agent on a key machine A during an SSH session //! from A to B. //! //! When that session came over the tailnet, `SSH_CONNECTION` on B begins //! with A's tailnet address, and B dials the agent there directly, on the //! port A's agent listens on. A connection is answered only when three //! things hold, checked in order: //! //! 1. **The address is a node of the tailnet.** tailscaled on A is asked who //! the address is (`whois`, over its LocalAPI), which names the node and //! gives its stable ID. //! 2. **The node is paired, and the pairing token is right.** The tailnet //! names machines, not people: any account on B can reach A's port. The //! pairing gives B a token that only the user can read there, and A keeps //! its SHA-256 against the node's stable ID. //! 3. **There is an SSH session for it.** B sends its `SSH_CONNECTION`, and //! A finds the TCP connection it names -- from A's address and port to //! B's -- owned by this user, and the process holding it: the `ssh` //! carrying the session. On Linux that is `/proc/net/tcp` and the //! descriptors under `/proc`; on Windows, `GetExtendedTcpTable`, which //! names the process, and the process token, which names the user. That //! process is the session, exactly as the one carrying a forward is, so //! confirmation, `bwgpg remote allow`, and its ending when ssh exits all //! work the same. //! //! What crosses is the agent's own protocol, restricted as on the extra //! socket: `ping`, `describe` and `sign`, with no environment. //! //! Pairing: `bwgpg remote pair B`, on A, makes the pairing token, keeps its //! hash in `tailnet-peers.json` in A's state directory, and hands the token //! to `bwgpg remote join` on B over ssh, which keeps it in //! `tailnet-agents.json` beside B's config, readable by its owner alone. //! Those are the two halves of the pairing. const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const Io = std.Io; const IpAddress = Io.net.IpAddress; const Environ = std.process.Environ; const testing = std.testing; const Sha256 = std.crypto.hash.sha2.Sha256; const config_mod = @import("../config.zig"); const platform = @import("../platform.zig"); /// The port suggested for the agent over the tailnet: what the Home Manager /// module and the systemd unit use. pub const default_port: u16 = 7743; /// The length of a pairing token, before base64. pub const token_len = 32; // -- addresses --------------------------------------------------------------- /// An IPv4 address mapped into IPv6 (`::ffff:a.b.c.d`), as a dual-stack /// socket reports an IPv4 peer, made back into IPv4. Anything else is /// returned as it is. pub fn unmap(a: IpAddress) IpAddress { switch (a) { .ip4 => return a, .ip6 => |a6| { const prefix = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff }; if (!std.mem.eql(u8, a6.bytes[0..12], &prefix)) return a; return .{ .ip4 = .{ .bytes = a6.bytes[12..16].*, .port = a6.port } }; }, } } /// Whether `a` is in the ranges Tailscale and headscale hand out: /// 100.64.0.0/10 and fd7a:115c:a1e0::/48. pub fn isTailnet(a: IpAddress) bool { return switch (unmap(a)) { .ip4 => |a4| a4.bytes[0] == 100 and a4.bytes[1] & 0xc0 == 64, .ip6 => |a6| std.mem.eql(u8, a6.bytes[0..6], &.{ 0xfd, 0x7a, 0x11, 0x5c, 0xa1, 0xe0 }), }; } /// Whether `a` and `b` are the same host, whatever their ports. pub fn sameHost(a: IpAddress, b: IpAddress) bool { return switch (unmap(a)) { .ip4 => |a4| switch (unmap(b)) { .ip4 => |b4| std.mem.eql(u8, &a4.bytes, &b4.bytes), .ip6 => false, }, .ip6 => |a6| switch (unmap(b)) { .ip4 => false, .ip6 => |b6| std.mem.eql(u8, &a6.bytes, &b6.bytes), }, }; } /// An address as tailscaled writes one, which may carry a prefix length /// (`100.64.0.3/32`). pub fn parseAddress(text: []const u8, port: u16) ?IpAddress { const bare = if (std.mem.findScalar(u8, text, '/')) |slash| text[0..slash] else text; return IpAddress.parse(bare, port) catch null; } /// The two ends of an SSH session, from `SSH_CONNECTION`: the client, which /// is A, and the server, which is this machine. pub const SshConnection = struct { client: IpAddress, server: IpAddress, }; /// `SSH_CONNECTION`: the client's address and port, then the server's. pub fn parseSshConnection(text: []const u8) ?SshConnection { var it = std.mem.tokenizeScalar(u8, text, ' '); const client_ip = it.next() orelse return null; const client_port = std.fmt.parseInt(u16, it.next() orelse return null, 10) catch return null; const server_ip = it.next() orelse return null; const server_port = std.fmt.parseInt(u16, it.next() orelse return null, 10) catch return null; if (it.next() != null) return null; return .{ .client = IpAddress.parse(client_ip, client_port) catch return null, .server = IpAddress.parse(server_ip, server_port) catch return null, }; } // -- tailscaled's LocalAPI --------------------------------------------------- /// Where tailscaled listens for its LocalAPI: a Unix socket, or on Windows /// a named pipe. `BWGPG_TAILSCALED_SOCKET` overrides it, which the tests /// use. pub fn tailscaledSocket(env: *const Environ.Map) []const u8 { return env.get("BWGPG_TAILSCALED_SOCKET") orelse if (builtin.os.tag == .windows) windows_pipe else "/run/tailscale/tailscaled.sock"; } const windows_pipe = "\\\\.\\pipe\\ProtectedPrefix\\Administrators\\Tailscale\\tailscaled"; fn isPipe(path: []const u8) bool { return std.ascii.startsWithIgnoreCase(path, "\\\\.\\pipe\\"); } pub const LocalApiError = error{ /// tailscaled is not running, or its socket is somewhere else. TailscaledUnreachable, /// It answered with something other than 200: for `whois`, 404 means /// the address is not a node of the tailnet. TailscaledRefused, /// What it answered could not be read. TailscaledUnreadable, } || Allocator.Error || Io.Cancelable; /// The most a LocalAPI answer is allowed to be. A status listing of a /// large tailnet is the biggest thing asked for. const max_response = 8 << 20; /// `GET target` from tailscaled, and the body of a 200 answer. /// /// This is HTTP/1.0 written by hand. `std.http.Client.connectUnix` would be /// the obvious way, and in 0.17 it does not compile, since it calls an /// `Io.net` function that no longer exists. HTTP/1.0 keeps it small: Go's /// server answers it without chunking and closes when done, so the body is /// everything after the head. On Windows the same goes over a named pipe. fn localApiGet(gpa: Allocator, io: Io, socket_path: []const u8, target: []const u8) LocalApiError![]u8 { var write_buf: [512]u8 = undefined; var read_buf: [4096]u8 = undefined; if (isPipe(socket_path)) { const pipe = platform.openPipe(socket_path) catch return error.TailscaledUnreachable; defer pipe.close(io); var writer = pipe.writer(io, &write_buf); var reader = pipe.readerStreaming(io, &read_buf); return localApiExchange(gpa, target, &writer.interface, &reader.interface); } const address = Io.net.UnixAddress.init(socket_path) catch return error.TailscaledUnreachable; const stream = address.connect(io) catch |err| switch (err) { error.Canceled => return error.Canceled, else => return error.TailscaledUnreachable, }; defer stream.close(io); var writer = stream.writer(io, &write_buf); var reader = stream.reader(io, &read_buf); return localApiExchange(gpa, target, &writer.interface, &reader.interface); } fn localApiExchange(gpa: Allocator, target: []const u8, writer: *Io.Writer, reader: *Io.Reader) LocalApiError![]u8 { writer.print("GET {s} HTTP/1.0\r\nHost: local-tailscaled.sock\r\n\r\n", .{target}) catch return error.TailscaledUnreachable; writer.flush() catch return error.TailscaledUnreachable; const raw = reader.allocRemaining(gpa, .limited(max_response)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.TailscaledUnreadable, }; defer gpa.free(raw); return gpa.dupe(u8, try responseBody(raw)); } /// The body of an HTTP/1.x response, if its status is 200. fn responseBody(raw: []const u8) error{ TailscaledRefused, TailscaledUnreadable }![]const u8 { const head_end = std.mem.find(u8, raw, "\r\n\r\n") orelse return error.TailscaledUnreadable; const head = raw[0..head_end]; const status_end = std.mem.find(u8, head, "\r\n") orelse head.len; var status_line = std.mem.tokenizeScalar(u8, head[0..status_end], ' '); const version = status_line.next() orelse return error.TailscaledUnreadable; if (!std.mem.startsWith(u8, version, "HTTP/1.")) return error.TailscaledUnreadable; const code = status_line.next() orelse return error.TailscaledUnreadable; if (!std.mem.eql(u8, code, "200")) return error.TailscaledRefused; // Not asked for, and not expected from an HTTP/1.0 request; refused // rather than misread. var lines = std.mem.splitSequence(u8, head[status_end..], "\r\n"); while (lines.next()) |line| { const colon = std.mem.findScalar(u8, line, ':') orelse continue; if (std.ascii.eqlIgnoreCase(std.mem.trim(u8, line[0..colon], " "), "transfer-encoding")) { return error.TailscaledUnreadable; } } return raw[head_end + 4 ..]; } /// A node of the tailnet, as tailscaled describes it. pub const Node = struct { /// Its short host name: `b` of `b.tailnet.example.`. name: []const u8, /// Its fully qualified name, without the final dot. dns_name: []const u8, /// The ID the control server keeps for it, which survives its addresses /// and names changing. stable_id: []const u8, addresses: []const IpAddress, /// The same, as text without a prefix length or a port: what `bwgpg /// remote pair` writes for the remote machine. address_texts: []const []const u8, /// Whether `host` -- a short name, a full name, or an address -- names /// this node. pub fn matches(n: Node, host: []const u8) bool { const h = std.mem.trimEnd(u8, host, "."); if (std.ascii.eqlIgnoreCase(h, n.name) or std.ascii.eqlIgnoreCase(h, n.dns_name)) return true; // The first label of its DNS name, which is what MagicDNS answers to // and may differ from the host name the machine reports. const label = n.dns_name[0 .. std.mem.findScalar(u8, n.dns_name, '.') orelse n.dns_name.len]; if (std.ascii.eqlIgnoreCase(h, label)) return true; const literal = parseAddress(h, 0) orelse return false; return n.has(literal); } pub fn has(n: Node, a: IpAddress) bool { for (n.addresses) |mine| if (sameHost(mine, a)) return true; return false; } }; fn nodeFrom(arena: Allocator, name: []const u8, dns_name: []const u8, stable_id: []const u8, addresses: []const []const u8) Allocator.Error!Node { const full = std.mem.trimEnd(u8, dns_name, "."); const short = if (name.len > 0) name else full[0 .. std.mem.findScalar(u8, full, '.') orelse full.len]; var list: std.ArrayList(IpAddress) = .empty; var texts: std.ArrayList([]const u8) = .empty; for (addresses) |text| { if (parseAddress(text, 0)) |a| { try list.append(arena, a); try texts.append(arena, if (std.mem.findScalar(u8, text, '/')) |slash| text[0..slash] else text); } } return .{ .name = short, .dns_name = full, .stable_id = stable_id, .addresses = try list.toOwnedSlice(arena), .address_texts = try texts.toOwnedSlice(arena), }; } const WhoisJson = struct { Node: struct { Name: []const u8 = "", StableID: []const u8 = "", Addresses: []const []const u8 = &.{}, }, }; /// Parses a `whois` answer. pub fn parseWhois(arena: Allocator, body: []const u8) LocalApiError!Node { const parsed = std.json.parseFromSliceLeaky(WhoisJson, arena, body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch |err| return switch (err) { error.OutOfMemory => error.OutOfMemory, else => error.TailscaledUnreadable, }; const n = parsed.Node; if (n.StableID.len == 0) return error.TailscaledUnreadable; return nodeFrom(arena, "", n.Name, n.StableID, n.Addresses); } /// Which node of the tailnet is at `address`. An address that is not on the /// tailnet is `TailscaledRefused`. pub fn whois(arena: Allocator, io: Io, socket_path: []const u8, address: IpAddress) LocalApiError!Node { var addr_buf: [96]u8 = undefined; var w: Io.Writer = .fixed(&addr_buf); unmap(address).format(&w) catch return error.TailscaledUnreadable; // An IPv6 address comes bracketed, and `[`, `]` and a zone's `%` do not // belong bare in a query. var target_buf: [256]u8 = undefined; var t: Io.Writer = .fixed(&target_buf); t.writeAll("/localapi/v0/whois?addr=") catch unreachable; for (w.buffered()) |c| switch (c) { '[', ']', '%' => t.print("%{X:0>2}", .{c}) catch unreachable, else => t.writeByte(c) catch unreachable, }; const body = try localApiGet(arena, io, socket_path, t.buffered()); return parseWhois(arena, body); } /// This machine and the others on the tailnet. pub const Status = struct { self: Node, peers: []const Node, /// The node `host` names, if any. pub fn find(s: Status, host: []const u8) ?Node { for (s.peers) |p| if (p.matches(host)) return p; return null; } }; const PeerJson = struct { ID: []const u8 = "", HostName: []const u8 = "", DNSName: []const u8 = "", TailscaleIPs: ?[]const []const u8 = null, }; const StatusJson = struct { Self: ?PeerJson = null, Peer: ?std.json.ArrayHashMap(PeerJson) = null, }; /// Parses a `status` answer. pub fn parseStatus(arena: Allocator, body: []const u8) LocalApiError!Status { const parsed = std.json.parseFromSliceLeaky(StatusJson, arena, body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch |err| return switch (err) { error.OutOfMemory => error.OutOfMemory, else => error.TailscaledUnreadable, }; const self = parsed.Self orelse return error.TailscaledUnreadable; var peers: std.ArrayList(Node) = .empty; if (parsed.Peer) |map| for (map.map.values()) |p| { try peers.append(arena, try nodeFrom(arena, p.HostName, p.DNSName, p.ID, p.TailscaleIPs orelse &.{})); }; return .{ .self = try nodeFrom(arena, self.HostName, self.DNSName, self.ID, self.TailscaleIPs orelse &.{}), .peers = try peers.toOwnedSlice(arena), }; } pub fn status(arena: Allocator, io: Io, socket_path: []const u8) LocalApiError!Status { const body = try localApiGet(arena, io, socket_path, "/localapi/v0/status"); return parseStatus(arena, body); } // -- pairing ----------------------------------------------------------------- // The field names below are the pairing files' format, and those of // `KeyMachinePairing` are also what `remote pair` hands `remote join`, so // they stay as they are whatever the types are called. /// The key machine's half of a pairing: a remote machine allowed to sign /// with this machine's agent over the tailnet. pub const RemotePairing = struct { /// The remote machine's node name when it was paired, for people; /// `stable_id` is what counts. node: []const u8, stable_id: []const u8, /// SHA-256 of the pairing token, in hex. token_sha256: []const u8, }; /// What the key machine keeps in `tailnet-peers.json`. pub const RemotePairings = struct { peers: []const RemotePairing = &.{}, }; /// The remote machine's half of a pairing: a key machine whose agent this /// machine may sign with over the tailnet. pub const KeyMachinePairing = struct { /// The key machine's node name, for people. node: []const u8, /// Its tailnet addresses, which `SSH_CONNECTION` is matched against. addresses: []const []const u8, port: u16, /// The pairing token, base64. token: []const u8, pub fn has(p: KeyMachinePairing, address: IpAddress) bool { for (p.addresses) |text| { if (parseAddress(text, 0)) |mine| if (sameHost(mine, address)) return true; } return false; } }; /// What the remote machine keeps in `tailnet-agents.json`. pub const KeyMachinePairings = struct { agents: []const KeyMachinePairing = &.{}, pub fn find(l: KeyMachinePairings, address: IpAddress) ?KeyMachinePairing { for (l.agents) |p| if (p.has(address)) return p; return null; } }; /// Where the key machine keeps its pairings: `tailnet-peers.json` in the /// state directory. pub fn remotePairingsPath(gpa: Allocator, io: Io, env: *const Environ.Map) ![]u8 { const dir = try config_mod.stateDir(gpa, io, env); defer gpa.free(dir); return std.fs.path.join(gpa, &.{ dir, "tailnet-peers.json" }); } /// Where the remote machine keeps its pairings: `tailnet-agents.json` beside /// the config. pub fn keyMachinePairingsPath(gpa: Allocator, io: Io, env: *const Environ.Map) ![]u8 { const config_path = try config_mod.configPath(gpa, io, env); defer gpa.free(config_path); const dir = std.fs.path.dirname(config_path) orelse "."; return std.fs.path.join(gpa, &.{ dir, "tailnet-agents.json" }); } pub const FileError = error{ /// The file is readable by others, and holds secrets or decides who /// may sign. InsecurePermissions, /// The file is there and is not what it should be. InvalidPairingFile, } || Allocator.Error; /// Reads one of the two pairing files into `arena`; `T`'s default when /// there is none. pub fn load(comptime T: type, arena: Allocator, io: Io, path: []const u8) FileError!T { const public = config_mod.readableByOthers(io, path) catch return .{}; if (public) return error.InsecurePermissions; const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.FileNotFound => return .{}, else => return error.InvalidPairingFile, }; return std.json.parseFromSliceLeaky(T, arena, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch |err| switch (err) { error.OutOfMemory => error.OutOfMemory, else => error.InvalidPairingFile, }; } /// A new token, base64. pub fn newToken(io: Io) [std.base64.standard.Encoder.calcSize(token_len)]u8 { var raw: [token_len]u8 = undefined; io.random(&raw); defer std.crypto.secureZero(u8, &raw); var out: [std.base64.standard.Encoder.calcSize(token_len)]u8 = undefined; _ = std.base64.standard.Encoder.encode(&out, &raw); return out; } /// The hex SHA-256 of a pairing token, as `RemotePairing.token_sha256` keeps /// it; null for something that is not a token. pub fn tokenHash(token: []const u8) ?[Sha256.digest_length * 2]u8 { const decoder = std.base64.standard.Decoder; const len = decoder.calcSizeForSlice(token) catch return null; if (len != token_len) return null; var raw: [token_len]u8 = undefined; defer std.crypto.secureZero(u8, &raw); decoder.decode(&raw, token) catch return null; var digest: [Sha256.digest_length]u8 = undefined; Sha256.hash(&raw, &digest, .{}); return std.fmt.bytesToHex(digest, .lower); } /// Whether `token` is the one paired with the node `stable_id`. The /// comparison takes the same time however much of it matches. pub fn tokenMatches(list: RemotePairings, stable_id: []const u8, token: []const u8) bool { const presented = tokenHash(token) orelse return false; for (list.peers) |p| { if (!std.mem.eql(u8, p.stable_id, stable_id)) continue; if (p.token_sha256.len != presented.len) return false; return std.crypto.timing_safe.eql([presented.len]u8, p.token_sha256[0..presented.len].*, presented); } return false; } // -- the SSH session, from /proc --------------------------------------------- /// One line of `/proc/net/tcp` or `/proc/net/tcp6`. pub const TcpEntry = struct { local: IpAddress, remote: IpAddress, /// The kernel's `TCP_` state; 1 is established. state: u8, uid: u32, inode: u64, }; pub const tcp_established = 1; /// An address and port as `/proc/net/tcp` writes them: the address as the /// 32-bit words holding it in memory, each in hex as a native integer, and /// the port in hex. fn parseProcAddress(text: []const u8) ?IpAddress { const colon = std.mem.findScalar(u8, text, ':') orelse return null; const hex = text[0..colon]; const port = std.fmt.parseInt(u16, text[colon + 1 ..], 16) catch return null; switch (hex.len) { 8 => { var a: Io.net.Ip4Address = .{ .bytes = undefined, .port = port }; const word = std.fmt.parseInt(u32, hex, 16) catch return null; std.mem.writeInt(u32, &a.bytes, word, .native); return .{ .ip4 = a }; }, 32 => { var a: Io.net.Ip6Address = .{ .bytes = undefined, .port = port }; for (0..4) |i| { const word = std.fmt.parseInt(u32, hex[i * 8 ..][0..8], 16) catch return null; std.mem.writeInt(u32, a.bytes[i * 4 ..][0..4], word, .native); } return .{ .ip6 = a }; }, else => return null, } } /// A line of `/proc/net/tcp`, or null for the header or anything else. pub fn parseTcpLine(line: []const u8) ?TcpEntry { var it = std.mem.tokenizeAny(u8, line, " \t"); const slot = it.next() orelse return null; if (!std.mem.endsWith(u8, slot, ":")) return null; const local = parseProcAddress(it.next() orelse return null) orelse return null; const remote = parseProcAddress(it.next() orelse return null) orelse return null; const state = std.fmt.parseInt(u8, it.next() orelse return null, 16) catch return null; _ = it.next() orelse return null; // tx_queue:rx_queue _ = it.next() orelse return null; // tr:tm->when _ = it.next() orelse return null; // retrnsmt const uid = std.fmt.parseInt(u32, it.next() orelse return null, 10) catch return null; _ = it.next() orelse return null; // timeout const inode = std.fmt.parseInt(u64, it.next() orelse return null, 10) catch return null; return .{ .local = local, .remote = remote, .state = state, .uid = uid, .inode = inode }; } /// Whether `entry` is an established connection of `uid`'s from `local` to /// `remote`, addresses and ports both. pub fn entryMatches(entry: TcpEntry, uid: u32, local: IpAddress, remote: IpAddress) bool { return entry.state == tcp_established and entry.uid == uid and sameEnds(entry.local, entry.remote, local, remote); } /// Whether a connection from `a_local` to `a_remote` is the one from /// `local` to `remote`, addresses and ports both. fn sameEnds(a_local: IpAddress, a_remote: IpAddress, local: IpAddress, remote: IpAddress) bool { return sameHost(a_local, local) and a_local.getPort() == local.getPort() and sameHost(a_remote, remote) and a_remote.getPort() == remote.getPort(); } /// A file under `/proc`, read to its end. They report a size of zero, so /// anything sized by `stat` reads nothing. fn readProcFile(gpa: Allocator, io: Io, path: []const u8) ![]u8 { var file = try Io.Dir.cwd().openFile(io, path, .{}); defer file.close(io); var buf: [4096]u8 = undefined; var reader = file.readerStreaming(io, &buf); return reader.interface.allocRemaining(gpa, .limited(64 << 20)); } /// The process of this user's holding an established TCP connection from /// `local` to `remote`: for an SSH session from here, the `ssh` carrying it. /// Null when there is none. pub fn sessionProcess(gpa: Allocator, io: Io, local: IpAddress, remote: IpAddress) !?i32 { if (builtin.os.tag == .windows) return windowsSessionProcess(gpa, local, remote); if (builtin.os.tag != .linux) return null; const uid = std.os.linux.getuid(); const inode = for ([_][]const u8{ "/proc/net/tcp", "/proc/net/tcp6" }) |path| { const text = readProcFile(gpa, io, path) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => continue, }; defer gpa.free(text); var lines = std.mem.splitScalar(u8, text, '\n'); const found = while (lines.next()) |line| { const entry = parseTcpLine(line) orelse continue; if (entryMatches(entry, uid, local, remote)) break entry.inode; } else null; if (found) |i| break i; } else return null; return socketOwner(io, inode); } /// The process holding socket `inode` open, among those whose descriptors /// this user may read, which is this user's own. fn socketOwner(io: Io, inode: u64) ?i32 { var want_buf: [32]u8 = undefined; const want = std.fmt.bufPrint(&want_buf, "socket:[{d}]", .{inode}) catch return null; var proc = Io.Dir.cwd().openDir(io, "/proc", .{ .iterate = true }) catch return null; defer proc.close(io); var procs = proc.iterate(); while (procs.next(io) catch return null) |entry| { const pid = std.fmt.parseInt(i32, entry.name, 10) catch continue; var path_buf: [64]u8 = undefined; const path = std.fmt.bufPrint(&path_buf, "{d}/fd", .{pid}) catch continue; var fds = proc.openDir(io, path, .{ .iterate = true }) catch continue; defer fds.close(io); var it = fds.iterate(); while (it.next(io) catch null) |fd| { var link_buf: [64]u8 = undefined; const n = fds.readLink(io, fd.name, &link_buf) catch continue; if (std.mem.eql(u8, link_buf[0..n], want)) return pid; } } return null; } // -- the SSH session, on Windows --------------------------------------------- /// What `GetExtendedTcpTable` is asked for on Windows: established /// connections, with the process holding each. const win_tcp = struct { const DWORD = std.os.windows.DWORD; const AF_INET = 2; const AF_INET6 = 23; const TCP_TABLE_OWNER_PID_CONNECTIONS = 4; const MIB_TCP_STATE_ESTAB = 5; const ERROR_INSUFFICIENT_BUFFER = 122; const Row4 = extern struct { state: DWORD, local_addr: [4]u8, local_port: DWORD, remote_addr: [4]u8, remote_port: DWORD, pid: DWORD, }; const Row6 = extern struct { local_addr: [16]u8, local_scope: DWORD, local_port: DWORD, remote_addr: [16]u8, remote_scope: DWORD, remote_port: DWORD, state: DWORD, pid: DWORD, }; extern "iphlpapi" fn GetExtendedTcpTable( table: ?*anyopaque, size: *DWORD, order: std.os.windows.BOOL, family: c_ulong, class: c_int, reserved: c_ulong, ) callconv(.winapi) DWORD; /// A port as the table keeps it: in network order, in the low half of /// a DWORD. fn port(p: DWORD) u16 { return std.mem.bigToNative(u16, @truncate(p)); } }; /// `sessionProcess` on Windows. The table names the process holding each /// connection outright; whose it is, is asked of its token. fn windowsSessionProcess(gpa: Allocator, local: IpAddress, remote: IpAddress) !?i32 { const family: c_ulong = switch (unmap(local)) { .ip4 => win_tcp.AF_INET, .ip6 => win_tcp.AF_INET6, }; // The table can grow between asking its size and reading it. var size: win_tcp.DWORD = 0; var buf: []align(@alignOf(win_tcp.Row6)) u8 = &.{}; defer gpa.free(buf); for (0..4) |_| { const rc = win_tcp.GetExtendedTcpTable(if (buf.len == 0) null else buf.ptr, &size, .FALSE, family, win_tcp.TCP_TABLE_OWNER_PID_CONNECTIONS, 0); if (rc == 0 and buf.len != 0) break; if (rc != 0 and rc != win_tcp.ERROR_INSUFFICIENT_BUFFER) return null; gpa.free(buf); buf = &.{}; buf = try gpa.alignedAlloc(u8, .of(win_tcp.Row6), size); } else return null; // A DWORD count, then the rows, aligned as they need. const count = std.mem.bytesToValue(win_tcp.DWORD, buf[0..4]); const pid: win_tcp.DWORD = switch (family) { win_tcp.AF_INET => find: { const rows: [*]const win_tcp.Row4 = @ptrCast(@alignCast(buf.ptr + @alignOf(win_tcp.Row4))); for (rows[0..count]) |r| { if (r.state != win_tcp.MIB_TCP_STATE_ESTAB) continue; const l: IpAddress = .{ .ip4 = .{ .bytes = r.local_addr, .port = win_tcp.port(r.local_port) } }; const rm: IpAddress = .{ .ip4 = .{ .bytes = r.remote_addr, .port = win_tcp.port(r.remote_port) } }; if (sameEnds(l, rm, local, remote)) break :find r.pid; } return null; }, else => find: { const rows: [*]const win_tcp.Row6 = @ptrCast(@alignCast(buf.ptr + @alignOf(win_tcp.Row6))); for (rows[0..count]) |r| { if (r.state != win_tcp.MIB_TCP_STATE_ESTAB) continue; const l: IpAddress = .{ .ip6 = .{ .bytes = r.local_addr, .port = win_tcp.port(r.local_port) } }; const rm: IpAddress = .{ .ip6 = .{ .bytes = r.remote_addr, .port = win_tcp.port(r.remote_port) } }; if (sameEnds(l, rm, local, remote)) break :find r.pid; } return null; }, }; const p: i32 = @intCast(pid); // Anyone's connection is in the table; only this user's is a session. return if (platform.processIsSelf(p)) p else null; } // -- tests ------------------------------------------------------------------- fn ip(text: []const u8, port: u16) IpAddress { return IpAddress.parse(text, port) catch unreachable; } test "the tailnet's address ranges" { try testing.expect(isTailnet(ip("100.64.0.3", 0))); try testing.expect(isTailnet(ip("100.127.255.255", 0))); try testing.expect(!isTailnet(ip("100.128.0.1", 0))); try testing.expect(!isTailnet(ip("100.63.0.1", 0))); try testing.expect(!isTailnet(ip("192.0.2.1", 0))); try testing.expect(isTailnet(ip("fd7a:115c:a1e0::17", 0))); try testing.expect(!isTailnet(ip("fd7a:115c:a1e1::17", 0))); // As a dual-stack socket reports an IPv4 peer. try testing.expect(isTailnet(ip("::ffff:100.64.0.3", 0))); try testing.expect(sameHost(ip("::ffff:100.64.0.3", 1), ip("100.64.0.3", 2))); try testing.expect(!sameHost(ip("100.64.0.3", 1), ip("100.64.0.4", 1))); } test "SSH_CONNECTION" { const sc = parseSshConnection("100.64.0.3 50022 100.64.0.7 22").?; try testing.expect(sameHost(sc.client, ip("100.64.0.3", 0))); try testing.expectEqual(@as(u16, 50022), sc.client.getPort()); try testing.expect(sameHost(sc.server, ip("100.64.0.7", 0))); try testing.expectEqual(@as(u16, 22), sc.server.getPort()); const six = parseSshConnection("fd7a:115c:a1e0::17 40000 fd7a:115c:a1e0::2 22").?; try testing.expect(isTailnet(six.client)); try testing.expectEqual(@as(?SshConnection, null), parseSshConnection("")); try testing.expectEqual(@as(?SshConnection, null), parseSshConnection("100.64.0.3 50022 100.64.0.7")); try testing.expectEqual(@as(?SshConnection, null), parseSshConnection("host 1 100.64.0.7 22")); try testing.expectEqual(@as(?SshConnection, null), parseSshConnection("100.64.0.3 99999 100.64.0.7 22")); } test "an HTTP response's body" { try testing.expectEqualStrings("{}", try responseBody("HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n{}")); try testing.expectError(error.TailscaledRefused, responseBody("HTTP/1.0 404 Not Found\r\n\r\nno match for IP:port\n")); try testing.expectError(error.TailscaledUnreadable, responseBody("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n\r\n")); try testing.expectError(error.TailscaledUnreadable, responseBody("HTTP/1.0 200 OK\r\n")); try testing.expectError(error.TailscaledUnreadable, responseBody("SSH-2.0-OpenSSH\r\n\r\n")); } test "a whois answer" { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); // Cut down from what headscale's tailscaled answers. const node = try parseWhois(arena, \\{"Node":{"ID":733,"StableID":"733","Name":"home04.ts.ocj.io.", \\"Addresses":["100.64.0.3/32","fd7a:115c:a1e0::17/128"],"Tags":null}, \\"UserProfile":{"ID":1,"LoginName":"home","DisplayName":"home"},"CapMap":{}} ); try testing.expectEqualStrings("733", node.stable_id); try testing.expectEqualStrings("home04", node.name); try testing.expectEqualStrings("home04.ts.ocj.io", node.dns_name); try testing.expectEqual(@as(usize, 2), node.addresses.len); try testing.expectEqualStrings("100.64.0.3", node.address_texts[0]); try testing.expect(node.has(ip("100.64.0.3", 0))); try testing.expect(node.has(ip("fd7a:115c:a1e0::17", 0))); try testing.expect(node.matches("home04")); try testing.expect(node.matches("HOME04.ts.ocj.io.")); try testing.expect(node.matches("100.64.0.3")); try testing.expect(!node.matches("home05")); try testing.expectError(error.TailscaledUnreadable, parseWhois(arena, "{\"Node\":{\"Name\":\"x.\"}}")); try testing.expectError(error.TailscaledUnreadable, parseWhois(arena, "no match for IP:port")); } test "a status answer" { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const s = try parseStatus(arena, \\{"Version":"1.90.0","BackendState":"Running", \\"Self":{"ID":"733","HostName":"home04","DNSName":"home04.ts.ocj.io.", \\"TailscaleIPs":["100.64.0.3","fd7a:115c:a1e0::17"]}, \\"Peer":{"nodekey:aa":{"ID":"12","HostName":"cloud01","DNSName":"cloud01.ts.ocj.io.", \\"TailscaleIPs":["100.64.0.7"]}, \\"nodekey:bb":{"ID":"13","HostName":"localhost","DNSName":"lab.ts.ocj.io.", \\"TailscaleIPs":null}}} ); try testing.expectEqualStrings("home04", s.self.name); try testing.expectEqual(@as(usize, 2), s.self.addresses.len); // What `bwgpg remote pair` hands the remote machine, which has to find // this one's address in its SSH_CONNECTION by them. try testing.expectEqualStrings("100.64.0.3", s.self.address_texts[0]); try testing.expectEqualStrings("fd7a:115c:a1e0::17", s.self.address_texts[1]); const handed: KeyMachinePairing = .{ .node = "home04", .addresses = s.self.address_texts, .port = default_port, .token = "" }; try testing.expect(handed.has(parseSshConnection("100.64.0.3 50022 100.64.0.7 22").?.client)); try testing.expectEqual(@as(usize, 2), s.peers.len); try testing.expectEqualStrings("12", s.find("cloud01").?.stable_id); try testing.expectEqualStrings("12", s.find("100.64.0.7").?.stable_id); // A node whose host name is not its DNS name answers to both. try testing.expectEqualStrings("13", s.find("lab").?.stable_id); try testing.expectEqual(@as(?Node, null), s.find("nowhere")); } test "tokens" { const token = newToken(testing.io); const hash = tokenHash(&token).?; const list: RemotePairings = .{ .peers = &.{.{ .node = "b", .stable_id = "12", .token_sha256 = &hash }} }; try testing.expect(tokenMatches(list, "12", &token)); try testing.expect(!tokenMatches(list, "13", &token)); const other = newToken(testing.io); try testing.expect(!tokenMatches(list, "12", &other)); try testing.expect(!tokenMatches(list, "12", "not a token")); try testing.expect(!tokenMatches(list, "12", "")); try testing.expectEqual(@as(?[64]u8, null), tokenHash("c2hvcnQ=")); } test "a line of /proc/net/tcp" { // The words are written as native integers; these lines are a // little-endian machine's. if (builtin.cpu.arch.endian() != .little) return error.SkipZigTest; const four = parseTcpLine(" 3: 0300400A:0016 0700400A:C35A 01 00000000:00000000 02:000A2C4E 00000000 1000 0 123456 2 0000000000000000 20 4 30 10 -1").?; try testing.expect(sameHost(four.local, ip("10.64.0.3", 0))); try testing.expectEqual(@as(u16, 22), four.local.getPort()); try testing.expect(sameHost(four.remote, ip("10.64.0.7", 0))); try testing.expectEqual(@as(u16, 50010), four.remote.getPort()); try testing.expectEqual(@as(u8, tcp_established), four.state); try testing.expectEqual(@as(u32, 1000), four.uid); try testing.expectEqual(@as(u64, 123456), four.inode); try testing.expect(entryMatches(four, 1000, ip("10.64.0.3", 22), ip("10.64.0.7", 50010))); try testing.expect(!entryMatches(four, 1001, ip("10.64.0.3", 22), ip("10.64.0.7", 50010))); try testing.expect(!entryMatches(four, 1000, ip("10.64.0.3", 22), ip("10.64.0.7", 50011))); // fd7a:115c:a1e0::17, port 22. const six = parseTcpLine(" 0: 5C117AFD0000E0A1000000001700000:0016 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 999 1 0000000000000000 100 0 0 10 0"); try testing.expectEqual(@as(?TcpEntry, null), six); // 31 digits: refused const six_ok = parseTcpLine(" 0: 5C117AFD0000E0A10000000017000000:0016 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 999 1 0000000000000000 100 0 0 10 0").?; try testing.expect(sameHost(six_ok.local, ip("fd7a:115c:a1e0::17", 0))); try testing.expectEqual(@as(u16, 22), six_ok.local.getPort()); try testing.expectEqual(@as(u8, 0x0a), six_ok.state); try testing.expectEqual(@as(?TcpEntry, null), parseTcpLine(" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode")); try testing.expectEqual(@as(?TcpEntry, null), parseTcpLine("")); } test "the pairing files: missing, private, and public" { if (builtin.os.tag == .windows) return error.SkipZigTest; var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const io = testing.io; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try tmp.dir.realPathFileAlloc(io, ".", arena); const path = try std.fs.path.join(arena, &.{ dir, "tailnet-agents.json" }); const none = try load(KeyMachinePairings, arena, io, path); try testing.expectEqual(@as(usize, 0), none.agents.len); const list: KeyMachinePairings = .{ .agents = &.{.{ .node = "a", .addresses = &.{ "100.64.0.3", "fd7a:115c:a1e0::17" }, .port = default_port, .token = "dG9rZW4=", }} }; try config_mod.savePrivate(testing.allocator, io, path, list); const back = try load(KeyMachinePairings, arena, io, path); try testing.expectEqual(@as(usize, 1), back.agents.len); try testing.expectEqual(default_port, back.find(ip("::ffff:100.64.0.3", 0)).?.port); try testing.expectEqual(@as(?KeyMachinePairing, null), back.find(ip("100.64.0.4", 0))); var f = try Io.Dir.cwd().openFile(io, path, .{}); try f.setPermissions(io, .fromMode(0o644)); f.close(io); try testing.expectError(error.InsecurePermissions, load(KeyMachinePairings, arena, io, path)); } test "a TCP connection of this user's names its process" { if (builtin.os.tag != .linux and builtin.os.tag != .windows) return error.SkipZigTest; const gpa = testing.allocator; const io = testing.io; var server = try ip("127.0.0.1", 0).listen(io, .{}); defer server.deinit(io); const client = try server.socket.address.connect(io, .{ .mode = .stream }); defer client.close(io); const accepted = try server.accept(io); defer accepted.close(io); // The client's end, from its own side: from its port to the server's. const from = accepted.socket.address; const to = server.socket.address; const pid = try sessionProcess(gpa, io, from, to); try testing.expectEqual(@as(?i32, platform.currentPid()), pid); // The same ports the other way round is the server's end; a port // nothing uses is nothing. try testing.expectEqual(@as(?i32, platform.currentPid()), try sessionProcess(gpa, io, to, from)); try testing.expectEqual(@as(?i32, null), try sessionProcess(gpa, io, ip("127.0.0.1", 1), to)); }