Files
VirtualBuddy/VirtualCore/Source/GuestSupport/ServiceTunnelPolicyMonitor.swift
Guilherme Rambo 4181d09e17 Guest<>host port and Unix socket forwarding (#824)
* Custom socket tunnels

* Improve tunnel configuration UI

* Tweak tunnel editing UI to be less confusing

* Create tunnel socket parent path if it doesn't already exist

* Security: Harden tunnel approval verification

* Security: harden tunnel approval UI against tampered strings, use only digest for validating approvals

* Security: refuse to start a TCP listener when something already answers at its address; replace existing socket when appropriate

* Fix newly added tunnel that replaces an existing listener being blocked by address in use

* Security: make tunnel status text from the other side safe to display

Status and failure text is chosen by the other side of a tunnel and shown
next to the tunnel in settings. Remove invisible, reordering and
line-breaking characters from it and limit its length.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

* Security: require a trusted owner for every folder enclosing a tunnel socket

Each component of a listener's path, as written and as resolved through
links, has to belong to this account or to a system account. Set the
socket's permissions without following links.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

* Security: check who owns a Unix socket tunnel destination

Apply the path ownership check to destinations, and require the service
that accepts the connection to run as this account or a system account.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

* Security: give each tunnel its own share of a virtual machine's connections

Raise the limit to 64 connections per virtual machine with at most 32 for
one tunnel, so holding one tunnel's connections open can't starve the
others. Pause a listener that runs out of descriptors or memory instead
of stopping it for good.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

* Security: keep the reason a tunnel failed on the host from the guest

The guest is only told that a tunnel isn't available on the host.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

* Update service tunnels audit report with the status of F5 to F10

Notes what was fixed for each finding and what was left as is.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

* Support managed preference restrictions on tunnels

* Remove audit file

* Tunnels UI tweaks

* Rewrite service tunnels documentation

---------

Co-authored-by: Claude Mythos 5.2 <noreply@anthropic.com>
2026-11-25 18:17:16 -03:00

97 lines
5.4 KiB
Swift

import Foundation
import ManagedPreferencesKit
import Observation
import VirtualWormhole
public extension VirtualBuddyManagedPreferences {
/// The service tunnel policy currently in effect, as set by the organization's configuration profile.
static func serviceTunnelPolicy(preferences: Reader = schema.reader()) -> ServiceTunnelPolicy {
var policy = ServiceTunnelPolicy()
policy.tunnelsDisabled = preferences.value(for: .disableServiceTunnels, default: false)
policy.hostServicesDisabled = preferences.value(for: .disableServiceTunnelsToHostServices, default: false)
policy.guestServicesDisabled = preferences.value(for: .disableServiceTunnelsToGuestServices, default: false)
policy.unixSocketsDisabled = preferences.value(for: .disableServiceTunnelUnixSockets, default: false)
policy.tcpPortsDisabled = preferences.value(for: .disableServiceTunnelTCPPorts, default: false)
policy.requestsDisabled = preferences.value(for: .disableServiceTunnelRequests, default: false)
policy.setHostPorts(
allowed: list(.serviceTunnelAllowedHostPorts, in: preferences, acceptingIntegers: true),
denied: list(.serviceTunnelDeniedHostPorts, in: preferences, acceptingIntegers: true) ?? []
)
policy.setHostSocketPaths(
allowed: list(.serviceTunnelAllowedHostSocketPaths, in: preferences),
denied: list(.serviceTunnelDeniedHostSocketPaths, in: preferences) ?? []
)
return policy
}
/// An entry that every list reads as a mistake: it allows nothing where things are allowed, and denies everything where they're denied.
private static let unreadableEntry = ""
/// The entries of a list preference, or `nil` when the organization hasn't set it.
///
/// A list restricts what tunnels can do, so a value that can't be read must not turn into no restriction at all,
/// which is what falling back to the preference being absent would amount to. Anything unreadable becomes an entry
/// the policy doesn't understand, and the policy fails closed on those.
private static func list(_ preference: Preference<[String]>, in preferences: Reader, acceptingIntegers: Bool = false) -> [String]? {
let resolution = preferences.resolve(preference)
guard let rawValue = resolution.rawValue else { return nil }
guard let entries = rawValue as? [Any] else {
logger.error("\(preference.key, privacy: .public) is not a list. Service tunnels are restricted as if it allowed nothing.")
return [unreadableEntry]
}
return entries.map { entry in
if let text = entry as? String { return text }
// A Boolean is a number to the property list, but never a port.
if acceptingIntegers, let number = entry as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() { return number.stringValue }
logger.error("\(preference.key, privacy: .public) has an entry of the wrong type. Service tunnels are restricted as if it allowed nothing.")
return unreadableEntry
}
}
/// Calls the handler when any preference that the service tunnel policy is made of may have changed.
@MainActor
static func observeServiceTunnelPolicy(
preferences: Reader = schema.reader(),
handler: @escaping @MainActor @Sendable () -> Void
) -> [ManagedPreferenceObservation] {
let switches: [Preference<Bool>] = [
.disableServiceTunnels, .disableServiceTunnelsToHostServices, .disableServiceTunnelsToGuestServices,
.disableServiceTunnelUnixSockets, .disableServiceTunnelTCPPorts, .disableServiceTunnelRequests
]
let lists: [Preference<[String]>] = [
.serviceTunnelAllowedHostPorts, .serviceTunnelDeniedHostPorts,
.serviceTunnelAllowedHostSocketPaths, .serviceTunnelDeniedHostSocketPaths
]
return switches.compactMap { preferences.observeChanges(for: $0, handler: handler) }
+ lists.compactMap { preferences.observeChanges(for: $0, handler: handler) }
}
}
/// Keeps track of the service tunnel policy while the organization's configuration profile is installed, changed or removed.
@MainActor @Observable
public final class ServiceTunnelPolicyMonitor {
public private(set) var policy: ServiceTunnelPolicy
/// Called after the policy has changed. Preferences that have nothing to do with tunnels change all the time, and don't count.
@ObservationIgnored public var onChange: (@MainActor (ServiceTunnelPolicy) -> Void)?
@ObservationIgnored private let preferences: VirtualBuddyManagedPreferences.Reader
@ObservationIgnored private var observations: [ManagedPreferenceObservation] = []
public init(preferences: VirtualBuddyManagedPreferences.Reader = VirtualBuddyManagedPreferences.schema.reader()) {
self.preferences = preferences
policy = VirtualBuddyManagedPreferences.serviceTunnelPolicy(preferences: preferences)
observations = VirtualBuddyManagedPreferences.observeServiceTunnelPolicy(preferences: preferences) { [weak self] in
self?.refresh()
}
}
public func refresh() {
let current = VirtualBuddyManagedPreferences.serviceTunnelPolicy(preferences: preferences)
guard current != policy else { return }
policy = current
VirtualBuddyManagedPreferences.logger.notice("The service tunnel policy changed")
onChange?(current)
}
}